diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index ae7db338588..ba40036c669 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -9,3 +9,4 @@ * @googleapis/cloud-sdk-nodejs-team /handwritten/bigquery @googleapis/bigquery-team /handwritten/cloud-profiler @googleapis/cloud-profiler-team +/handwritten/firestore @googleapis/cloud-sdk-nodejs-team diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 9afa1ee8000..35d9d39608e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,9 +1,10 @@ { - "handwritten/datastore": "10.1.0", - "handwritten/logging-winston": "6.0.1", "handwritten/bigquery": "8.2.0", "handwritten/cloud-profiler": "6.0.4", + "handwritten/datastore": "10.1.0", + "handwritten/firestore": "8.3.0", "handwritten/logging-bunyan": "5.1.1", + "handwritten/logging-winston": "6.0.1", "packages/gapic-node-processing": "0.1.6", "packages/google-ads-admanager": "0.5.0", "packages/google-ads-datamanager": "0.1.0", diff --git a/handwritten/firestore/.OwlBot.yaml b/handwritten/firestore/.OwlBot.yaml new file mode 100644 index 00000000000..4bf33471f7f --- /dev/null +++ b/handwritten/firestore/.OwlBot.yaml @@ -0,0 +1,26 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +deep-remove-regex: + - /owl-bot-staging + +deep-copy-regex: + - source: /google/firestore/(v.*)/.*-nodejs + dest: /owl-bot-staging/firestore/$1 + - source: /google/firestore/admin/(v.*)/.*-nodejs + dest: /owl-bot-staging/admin/$1/$2 + +begin-after-commit-hash: d3509d2520fb8db862129633f1cf8406d17454e1 + diff --git a/handwritten/firestore/.eslintignore b/handwritten/firestore/.eslintignore new file mode 100644 index 00000000000..ea5b04aebe6 --- /dev/null +++ b/handwritten/firestore/.eslintignore @@ -0,0 +1,7 @@ +**/node_modules +**/coverage +test/fixtures +build/ +docs/ +protos/ +samples/generated/ diff --git a/handwritten/firestore/.eslintrc.json b/handwritten/firestore/.eslintrc.json new file mode 100644 index 00000000000..ed46c46a7ae --- /dev/null +++ b/handwritten/firestore/.eslintrc.json @@ -0,0 +1,73 @@ +{ + "extends": "./node_modules/gts", + "overrides": [ + { + "files": [ + "dev/src/**/*.ts" + ], + "excludedFiles": [ + "dev/src/v1/*.ts", + "dev/src/v1beta1/*.ts" + ], + "parser": "@typescript-eslint/parser", + "rules": { + "@typescript-eslint/explicit-function-return-type": [ + "error", + { + "allowExpressions": true, + "allowTypedFunctionExpressions": true + } + ], + "no-console": ["error", {"allow": ["error"]}], + "@typescript-eslint/no-unused-vars": [ + "warn", + { + // Ignore args that are underscore only + "argsIgnorePattern": "^_$" + } + ] + } + }, + { + "files": [ + "dev/test/*.ts", + "dev/system-test/*.ts" + ], + "parser": "@typescript-eslint/parser", + "rules": { + "no-restricted-properties": [ + "error", + { + "object": "describe", + "property": "only" + }, + { + "object": "it", + "property": "only" + } + ], + "@typescript-eslint/no-unused-vars": [ + "warn", + { + // Ignore args that are underscore only + "argsIgnorePattern": "^_$" + } + ], + "@typescript-eslint/no-floating-promises": "warn" + } + }, + { + "files": [ + "dev/src/v1/**/*.ts", + "dev/src/v1beta1/**/*.ts", + "dev/test/gapic_firestore_v1.ts", + "dev/test/gapic_firestore_admin_v1.ts", + "dev/test/gapic_firestore_admin_v1.ts" + ], + "rules": { + "@typescript-eslint/no-explicit-any": ["off"], + "@typescript-eslint/no-floating-promises": ["off"] + } + } + ] +} diff --git a/handwritten/firestore/.gitattributes b/handwritten/firestore/.gitattributes new file mode 100644 index 00000000000..33739cb74e4 --- /dev/null +++ b/handwritten/firestore/.gitattributes @@ -0,0 +1,4 @@ +*.ts text eol=lf +*.js text eol=lf +protos/* linguist-generated +**/api-extractor.json linguist-language=JSON-with-Comments diff --git a/handwritten/firestore/.gitignore b/handwritten/firestore/.gitignore new file mode 100644 index 00000000000..38694b07d03 --- /dev/null +++ b/handwritten/firestore/.gitignore @@ -0,0 +1,16 @@ +**/*.log +**/node_modules +/.coverage +/coverage +/.nyc_output +/docs/ +/out/ +/build/ +temp/ +types/tsdoc-metadata.json +system-test/secrets.js +system-test/*key.json +*.lock +.DS_Store +package-lock.json +__pycache__ diff --git a/handwritten/firestore/.idea/runConfigurations/Conformance_Tests.xml b/handwritten/firestore/.idea/runConfigurations/Conformance_Tests.xml new file mode 100644 index 00000000000..c0fe1889f47 --- /dev/null +++ b/handwritten/firestore/.idea/runConfigurations/Conformance_Tests.xml @@ -0,0 +1,17 @@ + + + node + + $PROJECT_DIR$/node_modules/mocha + $PROJECT_DIR$ + true + + + + bdd + --require ts-node/register/type-check --no-cache --no-timeout + TEST_FILE + $PROJECT_DIR$/dev/conformance/runner.ts + + + \ No newline at end of file diff --git a/handwritten/firestore/.idea/runConfigurations/System_Test.xml b/handwritten/firestore/.idea/runConfigurations/System_Test.xml new file mode 100644 index 00000000000..9dad0feeac9 --- /dev/null +++ b/handwritten/firestore/.idea/runConfigurations/System_Test.xml @@ -0,0 +1,17 @@ + + + node + + $PROJECT_DIR$/node_modules/mocha + $PROJECT_DIR$ + true + + + + bdd + --require ts-node/register/type-check --no-cache --timeout 60000 + PATTERN + $PROJECT_DIR$/dev/system-test/*.js $PROJECT_DIR$/dev/system-test/*.ts + + + \ No newline at end of file diff --git a/handwritten/firestore/.idea/runConfigurations/Unit_Tests.xml b/handwritten/firestore/.idea/runConfigurations/Unit_Tests.xml new file mode 100644 index 00000000000..3a84e9d1013 --- /dev/null +++ b/handwritten/firestore/.idea/runConfigurations/Unit_Tests.xml @@ -0,0 +1,17 @@ + + + node + + $PROJECT_DIR$/node_modules/mocha + $PROJECT_DIR$/dev + true + + + + bdd + --require ts-node/register/type-check --no-cache --no-timeout + PATTERN + $PROJECT_DIR$/dev/test/*.js $PROJECT_DIR$/dev/test/**/*.ts + + + \ No newline at end of file diff --git a/handwritten/firestore/.jsdoc.js b/handwritten/firestore/.jsdoc.js new file mode 100644 index 00000000000..e6352a87b4b --- /dev/null +++ b/handwritten/firestore/.jsdoc.js @@ -0,0 +1,55 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +'use strict'; + +module.exports = { + opts: { + readme: './README.md', + package: './package.json', + template: './node_modules/jsdoc-fresh', + recurse: true, + verbose: true, + destination: './docs/' + }, + plugins: [ + 'plugins/markdown', + 'jsdoc-region-tag' + ], + source: { + excludePattern: '(^|\\/|\\\\)[._]', + include: [ + 'build/src', + 'build/protos' + ], + includePattern: '\\.js$' + }, + templates: { + copyright: 'Copyright 2025 Google LLC', + includeDate: false, + sourceFiles: false, + systemName: '@google-cloud/firestore', + theme: 'lumen', + default: { + outputSourceFiles: false + } + }, + markdown: { + idInHeadings: true + } +}; diff --git a/handwritten/firestore/.kokoro/.gitattributes b/handwritten/firestore/.kokoro/.gitattributes new file mode 100644 index 00000000000..87acd4f484e --- /dev/null +++ b/handwritten/firestore/.kokoro/.gitattributes @@ -0,0 +1 @@ +* linguist-generated=true diff --git a/handwritten/firestore/.kokoro/common.cfg b/handwritten/firestore/.kokoro/common.cfg new file mode 100644 index 00000000000..67b4b3be98c --- /dev/null +++ b/handwritten/firestore/.kokoro/common.cfg @@ -0,0 +1,24 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-firestore/handwritten/firestore/.kokoro/trampoline.sh" + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-firestore/handwritten/firestore/.kokoro/test.sh" +} diff --git a/handwritten/firestore/.kokoro/continuous/node18/common.cfg b/handwritten/firestore/.kokoro/continuous/node18/common.cfg new file mode 100644 index 00000000000..67b4b3be98c --- /dev/null +++ b/handwritten/firestore/.kokoro/continuous/node18/common.cfg @@ -0,0 +1,24 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-firestore/handwritten/firestore/.kokoro/trampoline.sh" + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-firestore/handwritten/firestore/.kokoro/test.sh" +} diff --git a/handwritten/firestore/.kokoro/continuous/node18/lint.cfg b/handwritten/firestore/.kokoro/continuous/node18/lint.cfg new file mode 100644 index 00000000000..3875e4f978e --- /dev/null +++ b/handwritten/firestore/.kokoro/continuous/node18/lint.cfg @@ -0,0 +1,4 @@ +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-firestore/handwritten/firestore/.kokoro/lint.sh" +} diff --git a/handwritten/firestore/.kokoro/continuous/node18/samples-test.cfg b/handwritten/firestore/.kokoro/continuous/node18/samples-test.cfg new file mode 100644 index 00000000000..1ff4b5ffae5 --- /dev/null +++ b/handwritten/firestore/.kokoro/continuous/node18/samples-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-firestore/handwritten/firestore/.kokoro/samples-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "nodejs-firestore/handwritten/firestore-ci-samples-71b5f8aee66e" +} diff --git a/handwritten/firestore/.kokoro/continuous/node18/system-test.cfg b/handwritten/firestore/.kokoro/continuous/node18/system-test.cfg new file mode 100644 index 00000000000..816a128e619 --- /dev/null +++ b/handwritten/firestore/.kokoro/continuous/node18/system-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-firestore/handwritten/firestore/.kokoro/system-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "java-review_firestore-nodejs-it-6d41b624fec9" +} diff --git a/handwritten/firestore/.kokoro/continuous/node18/test.cfg b/handwritten/firestore/.kokoro/continuous/node18/test.cfg new file mode 100644 index 00000000000..e69de29bb2d diff --git a/handwritten/firestore/.kokoro/docs.sh b/handwritten/firestore/.kokoro/docs.sh new file mode 100755 index 00000000000..952403faede --- /dev/null +++ b/handwritten/firestore/.kokoro/docs.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=/home/node/.npm-global + +cd $(dirname $0)/.. + +npm install + +npm run docs-test diff --git a/handwritten/firestore/.kokoro/lint.sh b/handwritten/firestore/.kokoro/lint.sh new file mode 100755 index 00000000000..b03cb0439a6 --- /dev/null +++ b/handwritten/firestore/.kokoro/lint.sh @@ -0,0 +1,33 @@ +#!/bin/bash + +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=/home/node/.npm-global + +cd $(dirname $0)/.. + +npm install + +# Install and link samples +if [ -f samples/package.json ]; then + cd samples/ + npm link ../ + npm install + cd .. +fi + +npm run lint diff --git a/handwritten/firestore/.kokoro/populate-secrets.sh b/handwritten/firestore/.kokoro/populate-secrets.sh new file mode 100755 index 00000000000..6f9d228859d --- /dev/null +++ b/handwritten/firestore/.kokoro/populate-secrets.sh @@ -0,0 +1,43 @@ +#!/bin/bash +# Copyright 2020 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -eo pipefail + +function now { date +"%Y-%m-%d %H:%M:%S" | tr -d '\n' ;} +function msg { println "$*" >&2 ;} +function println { printf '%s\n' "$(now) $*" ;} + + +# Populates requested secrets set in SECRET_MANAGER_KEYS from service account: +# kokoro-trampoline@cloud-devrel-kokoro-resources.iam.gserviceaccount.com +SECRET_LOCATION="${KOKORO_GFILE_DIR}/secret_manager" +msg "Creating folder on disk for secrets: ${SECRET_LOCATION}" +mkdir -p ${SECRET_LOCATION} +for key in $(echo ${SECRET_MANAGER_KEYS} | sed "s/,/ /g") +do + msg "Retrieving secret ${key}" + docker run --entrypoint=gcloud \ + --volume=${KOKORO_GFILE_DIR}:${KOKORO_GFILE_DIR} \ + gcr.io/google.com/cloudsdktool/cloud-sdk \ + secrets versions access latest \ + --project cloud-devrel-kokoro-resources \ + --secret $key > \ + "$SECRET_LOCATION/$key" + if [[ $? == 0 ]]; then + msg "Secret written to ${SECRET_LOCATION}/${key}" + else + msg "Error retrieving secret ${key}" + fi +done diff --git a/handwritten/firestore/.kokoro/pre-samples-test.sh b/handwritten/firestore/.kokoro/pre-samples-test.sh new file mode 100755 index 00000000000..9fcefbcc6e1 --- /dev/null +++ b/handwritten/firestore/.kokoro/pre-samples-test.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +export GCLOUD_PROJECT=nodejs-firestore/handwritten/firestore-ci +export GOOGLE_APPLICATION_CREDENTIALS=${KOKORO_GFILE_DIR}/secret_manager/nodejs-firestore/handwritten/firestore-ci-samples-71b5f8aee66e diff --git a/handwritten/firestore/.kokoro/pre-system-test.sh b/handwritten/firestore/.kokoro/pre-system-test.sh new file mode 100755 index 00000000000..a04f4650ad3 --- /dev/null +++ b/handwritten/firestore/.kokoro/pre-system-test.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +export GCLOUD_PROJECT=java-review +export GOOGLE_APPLICATION_CREDENTIALS=${KOKORO_GFILE_DIR}/secret_manager/java-review_firestore-nodejs-it-6d41b624fec9 diff --git a/handwritten/firestore/.kokoro/presubmit/node18/common.cfg b/handwritten/firestore/.kokoro/presubmit/node18/common.cfg new file mode 100644 index 00000000000..67b4b3be98c --- /dev/null +++ b/handwritten/firestore/.kokoro/presubmit/node18/common.cfg @@ -0,0 +1,24 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-firestore/handwritten/firestore/.kokoro/trampoline.sh" + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-firestore/handwritten/firestore/.kokoro/test.sh" +} diff --git a/handwritten/firestore/.kokoro/presubmit/node18/samples-test.cfg b/handwritten/firestore/.kokoro/presubmit/node18/samples-test.cfg new file mode 100644 index 00000000000..1ff4b5ffae5 --- /dev/null +++ b/handwritten/firestore/.kokoro/presubmit/node18/samples-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-firestore/handwritten/firestore/.kokoro/samples-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "nodejs-firestore/handwritten/firestore-ci-samples-71b5f8aee66e" +} diff --git a/handwritten/firestore/.kokoro/presubmit/node18/system-test.cfg b/handwritten/firestore/.kokoro/presubmit/node18/system-test.cfg new file mode 100644 index 00000000000..816a128e619 --- /dev/null +++ b/handwritten/firestore/.kokoro/presubmit/node18/system-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-firestore/handwritten/firestore/.kokoro/system-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "java-review_firestore-nodejs-it-6d41b624fec9" +} diff --git a/handwritten/firestore/.kokoro/presubmit/node18/test.cfg b/handwritten/firestore/.kokoro/presubmit/node18/test.cfg new file mode 100644 index 00000000000..e69de29bb2d diff --git a/handwritten/firestore/.kokoro/presubmit/windows/common.cfg b/handwritten/firestore/.kokoro/presubmit/windows/common.cfg new file mode 100644 index 00000000000..d6e25e0b1b8 --- /dev/null +++ b/handwritten/firestore/.kokoro/presubmit/windows/common.cfg @@ -0,0 +1,2 @@ +# Format: //devtools/kokoro/config/proto/build.proto + diff --git a/handwritten/firestore/.kokoro/presubmit/windows/test.cfg b/handwritten/firestore/.kokoro/presubmit/windows/test.cfg new file mode 100644 index 00000000000..603649c2ea9 --- /dev/null +++ b/handwritten/firestore/.kokoro/presubmit/windows/test.cfg @@ -0,0 +1,2 @@ +# Use the test file directly +build_file: "nodejs-firestore/handwritten/firestore/.kokoro/test.bat" diff --git a/handwritten/firestore/.kokoro/publish.sh b/handwritten/firestore/.kokoro/publish.sh new file mode 100755 index 00000000000..6a4f1562128 --- /dev/null +++ b/handwritten/firestore/.kokoro/publish.sh @@ -0,0 +1,31 @@ +#!/bin/bash + +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=/home/node/.npm-global + +# Start the releasetool reporter +python3 -m pip install gcp-releasetool +python3 -m releasetool publish-reporter-script > /tmp/publisher-script; source /tmp/publisher-script + +cd $(dirname $0)/.. + +NPM_TOKEN=$(cat $KOKORO_KEYSTORE_DIR/73713_google-cloud-npm-token-1) +echo "//wombat-dressing-room.appspot.com/:_authToken=${NPM_TOKEN}" > ~/.npmrc + +npm install +npm publish --access=public --registry=https://wombat-dressing-room.appspot.com diff --git a/handwritten/firestore/.kokoro/release/common.cfg b/handwritten/firestore/.kokoro/release/common.cfg new file mode 100644 index 00000000000..3ba2eb095fe --- /dev/null +++ b/handwritten/firestore/.kokoro/release/common.cfg @@ -0,0 +1,8 @@ +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "yoshi-automation-github-key" + } + } +} diff --git a/handwritten/firestore/.kokoro/release/docs-devsite.cfg b/handwritten/firestore/.kokoro/release/docs-devsite.cfg new file mode 100644 index 00000000000..d7aee739fd8 --- /dev/null +++ b/handwritten/firestore/.kokoro/release/docs-devsite.cfg @@ -0,0 +1,26 @@ +# service account used to publish up-to-date docs. +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "docuploader_service_account" + } + } +} + +# doc publications use a Python image. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-firestore/handwritten/firestore/.kokoro/trampoline.sh" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-firestore/handwritten/firestore/.kokoro/release/docs-devsite.sh" +} diff --git a/handwritten/firestore/.kokoro/release/docs-devsite.sh b/handwritten/firestore/.kokoro/release/docs-devsite.sh new file mode 100755 index 00000000000..b6a4662b84b --- /dev/null +++ b/handwritten/firestore/.kokoro/release/docs-devsite.sh @@ -0,0 +1,29 @@ +#!/bin/bash + +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -eo pipefail + +if [[ -z "$CREDENTIALS" ]]; then + # if CREDENTIALS are explicitly set, assume we're testing locally + # and don't set NPM_CONFIG_PREFIX. + export NPM_CONFIG_PREFIX=${HOME}/.npm-global + export PATH="$PATH:${NPM_CONFIG_PREFIX}/bin" + cd $(dirname $0)/../.. +fi + +npm install +npm install --no-save @google-cloud/cloud-rad@^0.4.0 +npx @google-cloud/cloud-rad diff --git a/handwritten/firestore/.kokoro/release/docs.cfg b/handwritten/firestore/.kokoro/release/docs.cfg new file mode 100644 index 00000000000..9434a6c931c --- /dev/null +++ b/handwritten/firestore/.kokoro/release/docs.cfg @@ -0,0 +1,26 @@ +# service account used to publish up-to-date docs. +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "docuploader_service_account" + } + } +} + +# doc publications use a Python image. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-firestore/handwritten/firestore/.kokoro/trampoline.sh" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-firestore/handwritten/firestore/.kokoro/release/docs.sh" +} diff --git a/handwritten/firestore/.kokoro/release/docs.sh b/handwritten/firestore/.kokoro/release/docs.sh new file mode 100755 index 00000000000..7102bbf09fa --- /dev/null +++ b/handwritten/firestore/.kokoro/release/docs.sh @@ -0,0 +1,50 @@ +#!/bin/bash + +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -eo pipefail + +# build jsdocs (Python is installed on the Node 18 docker image). +if [[ -z "$CREDENTIALS" ]]; then + # if CREDENTIALS are explicitly set, assume we're testing locally + # and don't set NPM_CONFIG_PREFIX. + export NPM_CONFIG_PREFIX=/home/node/.npm-global + export PATH="$PATH:/home/node/.npm-global/bin" + cd $(dirname $0)/../.. +fi +npm install +npm run docs + +# create docs.metadata, based on package.json and .repo-metadata.json. +npm i json@9.0.6 -g +python3 -m pip install --user gcp-docuploader +python3 -m docuploader create-metadata \ + --name=$(cat .repo-metadata.json | json name) \ + --version=$(cat package.json | json version) \ + --language=$(cat .repo-metadata.json | json language) \ + --distribution-name=$(cat .repo-metadata.json | json distribution_name) \ + --product-page=$(cat .repo-metadata.json | json product_documentation) \ + --github-repository=$(cat .repo-metadata.json | json repo) \ + --issue-tracker=$(cat .repo-metadata.json | json issue_tracker) +cp docs.metadata ./docs/docs.metadata + +# deploy the docs. +if [[ -z "$CREDENTIALS" ]]; then + CREDENTIALS=${KOKORO_KEYSTORE_DIR}/73713_docuploader_service_account +fi +if [[ -z "$BUCKET" ]]; then + BUCKET=docs-staging +fi +python3 -m docuploader upload ./docs --credentials $CREDENTIALS --staging-bucket $BUCKET diff --git a/handwritten/firestore/.kokoro/release/publish.cfg b/handwritten/firestore/.kokoro/release/publish.cfg new file mode 100644 index 00000000000..64b9fd038a5 --- /dev/null +++ b/handwritten/firestore/.kokoro/release/publish.cfg @@ -0,0 +1,69 @@ +# Get npm token from Keystore +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "google-cloud-npm-token-1" + } + } +} + +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "yoshi-automation-github-key" + } + } +} + +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "docuploader_service_account" + } + } +} + +# Fetch magictoken to use with Magic Github Proxy +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "releasetool-magictoken" + } + } +} + +# Fetch api key to use with Magic Github Proxy +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "magic-github-proxy-api-key" + } + } +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem" +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-firestore/handwritten/firestore/.kokoro/trampoline.sh" + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-firestore/handwritten/firestore/.kokoro/publish.sh" +} diff --git a/handwritten/firestore/.kokoro/samples-test.sh b/handwritten/firestore/.kokoro/samples-test.sh new file mode 100755 index 00000000000..b0d655d6510 --- /dev/null +++ b/handwritten/firestore/.kokoro/samples-test.sh @@ -0,0 +1,68 @@ +#!/bin/bash + +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=/home/node/.npm-global + +# Setup service account credentials. +export GOOGLE_APPLICATION_CREDENTIALS=${KOKORO_GFILE_DIR}/service-account.json +export GCLOUD_PROJECT=node-gcloud-ci + +cd $(dirname $0)/.. + +# Run a pre-test hook, if a pre-samples-test.sh is in the project +if [ -f .kokoro/pre-samples-test.sh ]; then + set +x + . .kokoro/pre-samples-test.sh + set -x +fi + +if [ -f samples/package.json ]; then + npm install + + # Install and link samples + cd samples/ + npm link ../ + npm install + cd .. + # If tests are running against main, configure FlakyBot + # to open issues on failures: + if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"continuous"* ]] || [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"nightly"* ]]; then + export MOCHA_REPORTER_OUTPUT=test_output_sponge_log.xml + export MOCHA_REPORTER=xunit + cleanup() { + chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot + $KOKORO_GFILE_DIR/linux_amd64/flakybot + } + trap cleanup EXIT HUP + fi + + npm run samples-test +fi + +# codecov combines coverage across integration and unit tests. Include +# the logic below for any environment you wish to collect coverage for: +COVERAGE_NODE=18 +if npx check-node-version@3.3.0 --silent --node $COVERAGE_NODE; then + NYC_BIN=./node_modules/nyc/bin/nyc.js + if [ -f "$NYC_BIN" ]; then + $NYC_BIN report || true + fi + bash $KOKORO_GFILE_DIR/codecov.sh +else + echo "coverage is only reported for Node $COVERAGE_NODE" +fi diff --git a/handwritten/firestore/.kokoro/system-test.sh b/handwritten/firestore/.kokoro/system-test.sh new file mode 100755 index 00000000000..f5569a51b35 --- /dev/null +++ b/handwritten/firestore/.kokoro/system-test.sh @@ -0,0 +1,61 @@ +#!/bin/bash + +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=/home/node/.npm-global + +# Setup service account credentials. +export GOOGLE_APPLICATION_CREDENTIALS=${KOKORO_GFILE_DIR}/service-account.json +export GCLOUD_PROJECT=node-gcloud-ci + +cd $(dirname $0)/.. + +# Run a pre-test hook, if a pre-system-test.sh is in the project +if [ -f .kokoro/pre-system-test.sh ]; then + set +x + . .kokoro/pre-system-test.sh + set -x +fi + +npm install + +# If tests are running against main, configure FlakyBot +# to open issues on failures: +if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"continuous"* ]] || [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"nightly"* ]]; then + export MOCHA_REPORTER_OUTPUT=test_output_sponge_log.xml + export MOCHA_REPORTER=xunit + cleanup() { + chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot + $KOKORO_GFILE_DIR/linux_amd64/flakybot + } + trap cleanup EXIT HUP +fi + +npm run system-test + +# codecov combines coverage across integration and unit tests. Include +# the logic below for any environment you wish to collect coverage for: +COVERAGE_NODE=18 +if npx check-node-version@3.3.0 --silent --node $COVERAGE_NODE; then + NYC_BIN=./node_modules/nyc/bin/nyc.js + if [ -f "$NYC_BIN" ]; then + $NYC_BIN report || true + fi + bash $KOKORO_GFILE_DIR/codecov.sh +else + echo "coverage is only reported for Node $COVERAGE_NODE" +fi diff --git a/handwritten/firestore/.kokoro/test.bat b/handwritten/firestore/.kokoro/test.bat new file mode 100644 index 00000000000..caf825656c2 --- /dev/null +++ b/handwritten/firestore/.kokoro/test.bat @@ -0,0 +1,33 @@ +@rem Copyright 2018 Google LLC. All rights reserved. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem http://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. + +@echo "Starting Windows build" + +cd /d %~dp0 +cd .. + +@rem npm path is not currently set in our image, we should fix this next time +@rem we upgrade Node.js in the image: +SET PATH=%PATH%;/cygdrive/c/Program Files/nodejs/npm + +call nvm use 18 +call which node + +call npm install || goto :error +call npm run test || goto :error + +goto :EOF + +:error +exit /b 1 diff --git a/handwritten/firestore/.kokoro/test.sh b/handwritten/firestore/.kokoro/test.sh new file mode 100755 index 00000000000..e1334dcaa5b --- /dev/null +++ b/handwritten/firestore/.kokoro/test.sh @@ -0,0 +1,48 @@ +#!/bin/bash + +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=/home/node/.npm-global + +cd $(dirname $0)/.. + +npm install +# If tests are running against main, configure FlakyBot +# to open issues on failures: +if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"continuous"* ]] || [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"nightly"* ]]; then + export MOCHA_REPORTER_OUTPUT=test_output_sponge_log.xml + export MOCHA_REPORTER=xunit + cleanup() { + chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot + $KOKORO_GFILE_DIR/linux_amd64/flakybot + } + trap cleanup EXIT HUP +fi +npm test + +# codecov combines coverage across integration and unit tests. Include +# the logic below for any environment you wish to collect coverage for: +COVERAGE_NODE=18 +if npx check-node-version@3.3.0 --silent --node $COVERAGE_NODE; then + NYC_BIN=./node_modules/nyc/bin/nyc.js + if [ -f "$NYC_BIN" ]; then + $NYC_BIN report || true + fi + bash $KOKORO_GFILE_DIR/codecov.sh +else + echo "coverage is only reported for Node $COVERAGE_NODE" +fi diff --git a/handwritten/firestore/.kokoro/trampoline.sh b/handwritten/firestore/.kokoro/trampoline.sh new file mode 100755 index 00000000000..ef9cb4a426d --- /dev/null +++ b/handwritten/firestore/.kokoro/trampoline.sh @@ -0,0 +1,48 @@ +#!/bin/bash +# Copyright 2017 Google Inc. + +# Auto-injected conditional check +# Check if the package directory has changes. If not, skip tests. +if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + # The package path is hardcoded during migration + RELATIVE_PKG_PATH="handwritten/firestore" + + echo "Checking for changes in ${RELATIVE_PKG_PATH}..." + + # Determine the diff range based on the CI system/event + # Safe default: HEAD~1..HEAD + DIFF_RANGE="HEAD~1..HEAD" + + if git diff --quiet "${DIFF_RANGE}" -- "${RELATIVE_PKG_PATH}"; then + echo "No changes detected in ${RELATIVE_PKG_PATH}. Skipping tests." + exit 0 + else + echo "Changes detected in ${RELATIVE_PKG_PATH}. Proceeding with tests." + fi +fi +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -eo pipefail + +# Always run the cleanup script, regardless of the success of bouncing into +# the container. +function cleanup() { + chmod +x ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh + ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh + echo "cleanup"; +} +trap cleanup EXIT + +$(dirname $0)/populate-secrets.sh # Secret Manager secrets. +python3 "${KOKORO_GFILE_DIR}/trampoline_v1.py" diff --git a/handwritten/firestore/.mocharc.js b/handwritten/firestore/.mocharc.js new file mode 100644 index 00000000000..2431859019f --- /dev/null +++ b/handwritten/firestore/.mocharc.js @@ -0,0 +1,29 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +const config = { + "enable-source-maps": true, + "throw-deprecation": true, + "timeout": 10000, + "recursive": true +} +if (process.env.MOCHA_THROW_DEPRECATION === 'false') { + delete config['throw-deprecation']; +} +if (process.env.MOCHA_REPORTER) { + config.reporter = process.env.MOCHA_REPORTER; +} +if (process.env.MOCHA_REPORTER_OUTPUT) { + config['reporter-option'] = `output=${process.env.MOCHA_REPORTER_OUTPUT}`; +} +module.exports = config diff --git a/handwritten/firestore/.nycrc b/handwritten/firestore/.nycrc new file mode 100644 index 00000000000..b18d5472b62 --- /dev/null +++ b/handwritten/firestore/.nycrc @@ -0,0 +1,24 @@ +{ + "report-dir": "./.coverage", + "reporter": ["text", "lcov"], + "exclude": [ + "**/*-test", + "**/.coverage", + "**/apis", + "**/benchmark", + "**/conformance", + "**/docs", + "**/samples", + "**/scripts", + "**/protos", + "**/test", + "**/*.d.ts", + ".jsdoc.js", + "**/.jsdoc.js", + "karma.conf.js", + "webpack-tests.config.js", + "webpack.config.js" + ], + "exclude-after-remap": false, + "all": true +} diff --git a/handwritten/firestore/.prettierignore b/handwritten/firestore/.prettierignore new file mode 100644 index 00000000000..9340ad9b86d --- /dev/null +++ b/handwritten/firestore/.prettierignore @@ -0,0 +1,6 @@ +**/node_modules +**/coverage +test/fixtures +build/ +docs/ +protos/ diff --git a/handwritten/firestore/.prettierrc.js b/handwritten/firestore/.prettierrc.js new file mode 100644 index 00000000000..d2eddc2ed89 --- /dev/null +++ b/handwritten/firestore/.prettierrc.js @@ -0,0 +1,17 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +module.exports = { + ...require('gts/.prettierrc.json') +} diff --git a/handwritten/firestore/.readme-partials.yaml b/handwritten/firestore/.readme-partials.yaml new file mode 100644 index 00000000000..60b13dae8cf --- /dev/null +++ b/handwritten/firestore/.readme-partials.yaml @@ -0,0 +1,66 @@ +introduction: |- + This is the Node.js Server SDK for [Google Cloud Firestore](https://firebase.google.com/docs/firestore/). Google Cloud Firestore is a NoSQL document database built for automatic scaling, high performance, and ease of application development. + + This Cloud Firestore Server SDK uses Google’s Cloud Identity and Access Management for authentication and should only be used in trusted environments. Your Cloud Identity credentials allow you bypass all access restrictions and provide read and write access to all data in your Cloud Firestore project. + + The Cloud Firestore Server SDKs are designed to manage the full set of data in your Cloud Firestore project and work best with reliable network connectivity. Data operations performed via these SDKs directly access the Cloud Firestore backend and all document reads and writes are optimized for high throughput. + + Applications that use Google's Server SDKs should not be used in end-user environments, such as on phones or on publicly hosted websites. If you are developing a Web or Node.js application that accesses Cloud Firestore on behalf of end users, use the firebase Client SDK. + + **Note:** This Cloud Firestore Server SDK does not support Firestore databases created in [Datastore mode](https://cloud.google.com/datastore/docs/firestore-or-datastore#in_datastore_mode). To access these databases, use the [Datastore SDK](https://www.npmjs.com/package/@google-cloud/datastore). + +body: |- + + ### Using the client library with Pipelines + + ```javascript + + const {Firestore} = require('@google-cloud/firestore'); + + // Require/import Pipelines from '@google-cloud/firestore/pipelines' + const {field} = require('@google-cloud/firestore/pipelines'); + + // Create a new client + const firestore = new Firestore({ + projectId: 'firestore-sdk-nightly', + databaseId: 'enterprise' + }); + + async function pipelinesQuickstart() { + // Obtain a collection reference. + const collection = firestore.collection('books'); + + // Enter new documents into the document. + await collection.add({ + "title": "Whispers of the Cobalt Sea", + "price": 12.99, + "author": "Elara Vance", + "yearPublished": 2023 + }); + await collection.add({ + "title": "The Antigravity Cat's Guide to Napping", + "price": 24.50, + "author": "Mittens the IV", + "yearPublished": 2026 + }); + console.log('Entered new documents into the collection.'); + + // Define a Pipeline query that selects books published this century, + // orders them by price, and computes a discounted price (20% off). + const pipeline = firestore.pipeline().collection('books') + .where(field('yearPublished').greaterThanOrEqual(2000)) + .sort(field('price').ascending()) + .select('title', 'author', field('price').multiply(0.8).as('discountedPrice')); + + // Execute the pipeline + const pipelineSnapshot = await pipeline.execute(); + console.log('Executed the Pipeline.'); + + console.log('Results:'); + pipelineSnapshot.results.forEach(pipelineResult=> { + console.log(pipelineResult.data()); + }); + } + pipelinesQuickstart(); + + ``` diff --git a/handwritten/firestore/.repo-metadata.json b/handwritten/firestore/.repo-metadata.json new file mode 100644 index 00000000000..c6bf8fe8cb8 --- /dev/null +++ b/handwritten/firestore/.repo-metadata.json @@ -0,0 +1,17 @@ +{ + "codeowner_team": "@googleapis/firestore-team @googleapis/cloud-sdk-nodejs-team", + "language": "nodejs", + "api_id": "firestore.googleapis.com", + "name_pretty": "Cloud Firestore", + "requires_billing ": false, + "default_version": "v1", + "product_documentation": "https://cloud.google.com/firestore", + "name": "firestore", + "issue_tracker": "https://issuetracker.google.com/savedsearches/5337669", + "distribution_name": "@google-cloud/firestore", + "repo": "googleapis/google-cloud-node", + "client_documentation": "https://cloud.google.com/nodejs/docs/reference/firestore/latest", + "release_level": "stable", + "api_shortname": "firestore", + "library_type": "GAPIC_COMBO" +} diff --git a/handwritten/firestore/.trampolinerc b/handwritten/firestore/.trampolinerc new file mode 100644 index 00000000000..2af668a017d --- /dev/null +++ b/handwritten/firestore/.trampolinerc @@ -0,0 +1,52 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Template for .trampolinerc + +# Add required env vars here. +required_envvars+=( +) + +# Add env vars which are passed down into the container here. +pass_down_envvars+=( + "AUTORELEASE_PR" + "VERSION" +) + +# Prevent unintentional override on the default image. +if [[ "${TRAMPOLINE_IMAGE_UPLOAD:-false}" == "true" ]] && \ + [[ -z "${TRAMPOLINE_IMAGE:-}" ]]; then + echo "Please set TRAMPOLINE_IMAGE if you want to upload the Docker image." + exit 1 +fi + +# Define the default value if it makes sense. +if [[ -z "${TRAMPOLINE_IMAGE_UPLOAD:-}" ]]; then + TRAMPOLINE_IMAGE_UPLOAD="" +fi + +if [[ -z "${TRAMPOLINE_IMAGE:-}" ]]; then + TRAMPOLINE_IMAGE="" +fi + +if [[ -z "${TRAMPOLINE_DOCKERFILE:-}" ]]; then + TRAMPOLINE_DOCKERFILE="" +fi + +if [[ -z "${TRAMPOLINE_BUILD_FILE:-}" ]]; then + TRAMPOLINE_BUILD_FILE="" +fi + +# Secret Manager secrets. +source ${PROJECT_ROOT}/handwritten/firestore/.kokoro/populate-secrets.sh diff --git a/handwritten/firestore/CHANGELOG.md b/handwritten/firestore/CHANGELOG.md new file mode 100644 index 00000000000..2b76943dc18 --- /dev/null +++ b/handwritten/firestore/CHANGELOG.md @@ -0,0 +1,1472 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/@google-cloud/firestore?activeTab=versions + +## [8.3.0](https://github.com/googleapis/nodejs-firestore/compare/v8.2.0...v8.3.0) (2026-02-02) + + +### Features + +* Add support for `regexFind` and `regexFindAll` ([#2474](https://github.com/googleapis/nodejs-firestore/issues/2474)) ([52800a2](https://github.com/googleapis/nodejs-firestore/commit/52800a2c6af9079277eba19f776880c85ae52380)) + +## [8.2.0](https://github.com/googleapis/nodejs-firestore/compare/v8.1.0...v8.2.0) (2026-01-09) + + +### Features + +* Pipelines preview ([#2450](https://github.com/googleapis/nodejs-firestore/issues/2450)) ([c80e618](https://github.com/googleapis/nodejs-firestore/commit/c80e6181709b72c943a445eb0a5a2fa63d2776dd)) + +## [8.1.0](https://github.com/googleapis/nodejs-firestore/compare/v8.0.0...v8.1.0) (2025-12-22) + + +### Features + +* [GAPIC] add Firestore CloneDatabase support ([a0c74b7](https://github.com/googleapis/nodejs-firestore/commit/a0c74b78a0a5896004126ba827a02f4c8d374fd0)) +* [GAPIC] add methods from gax to cache proto root and process custom error details ([a0c74b7](https://github.com/googleapis/nodejs-firestore/commit/a0c74b78a0a5896004126ba827a02f4c8d374fd0)) +* [GAPIC] add protobufjs 2023 edition support ([a0c74b7](https://github.com/googleapis/nodejs-firestore/commit/a0c74b78a0a5896004126ba827a02f4c8d374fd0)) +* [GAPIC] add request/response debug logging to gapics, update templates to gax 5 and node 18 ([#1671](https://github.com/googleapis/nodejs-firestore/issues/1671)) ([a0c74b7](https://github.com/googleapis/nodejs-firestore/commit/a0c74b78a0a5896004126ba827a02f4c8d374fd0)) +* [GAPIC] add the UserCreds API ([a0c74b7](https://github.com/googleapis/nodejs-firestore/commit/a0c74b78a0a5896004126ba827a02f4c8d374fd0)) +* [GAPIC] await/catch promises, and update listOperationsAsync return type ([a0c74b7](https://github.com/googleapis/nodejs-firestore/commit/a0c74b78a0a5896004126ba827a02f4c8d374fd0)) +* [GAPIC] Expose tags field in Database and RestoreDatabaseRequest public protos ([a0c74b7](https://github.com/googleapis/nodejs-firestore/commit/a0c74b78a0a5896004126ba827a02f4c8d374fd0)) +* [GAPIC] new Firestore index modes and Database Editions ([a0c74b7](https://github.com/googleapis/nodejs-firestore/commit/a0c74b78a0a5896004126ba827a02f4c8d374fd0)) +* [GAPIC] publish the pipelines API to the stable branch ([a0c74b7](https://github.com/googleapis/nodejs-firestore/commit/a0c74b78a0a5896004126ba827a02f4c8d374fd0)) +* [GAPIC] selective gapic support for typescript generation ([a0c74b7](https://github.com/googleapis/nodejs-firestore/commit/a0c74b78a0a5896004126ba827a02f4c8d374fd0)) +* Adding gcp resource name span attribute ([#2454](https://github.com/googleapis/nodejs-firestore/issues/2454)) ([bc0c73d](https://github.com/googleapis/nodejs-firestore/commit/bc0c73db1fc840bf34115ffab20d7b48eb0a76e5)) + + +### Bug Fixes + +* [GAPIC] add json files to tsconfig templates ([#1692](https://github.com/googleapis/nodejs-firestore/issues/1692)) (ba6be1d) ([a0c74b7](https://github.com/googleapis/nodejs-firestore/commit/a0c74b78a0a5896004126ba827a02f4c8d374fd0)) +* [GAPIC] catch dangling promises ([a0c74b7](https://github.com/googleapis/nodejs-firestore/commit/a0c74b78a0a5896004126ba827a02f4c8d374fd0)) +* [GAPIC] distinguish plural and singular path templates ([a0c74b7](https://github.com/googleapis/nodejs-firestore/commit/a0c74b78a0a5896004126ba827a02f4c8d374fd0)) + +## [8.0.0](https://github.com/googleapis/nodejs-firestore/compare/v7.11.6...v8.0.0) (2025-10-29) + + +### ⚠ BREAKING CHANGES + +* Update WithFieldData and PartialWithFieldData to ignore methods on types ([#2294](https://github.com/googleapis/nodejs-firestore/issues/2294)) +* migrate to Node 18 ([#2399](https://github.com/googleapis/nodejs-firestore/issues/2399)) + +### Features + +* Support for index signatures in UpdateData<T> ([#1953](https://github.com/googleapis/nodejs-firestore/issues/1953)) ([afa206d](https://github.com/googleapis/nodejs-firestore/commit/afa206d17ce2d0905ce02e723c2c92bea368ba3a)) + + +### Bug Fixes + +* Update WithFieldData and PartialWithFieldData to ignore methods on types ([#2294](https://github.com/googleapis/nodejs-firestore/issues/2294)) ([481430f](https://github.com/googleapis/nodejs-firestore/commit/481430ffc12bdaf3e3a92aa89a2ce389756ce9da)) + + +### Miscellaneous Chores + +* Migrate to Node 18 ([#2399](https://github.com/googleapis/nodejs-firestore/issues/2399)) ([e5c3118](https://github.com/googleapis/nodejs-firestore/commit/e5c31184325b84ef8dcb456ec0a7a4807038c838)) + +## [7.11.6](https://github.com/googleapis/nodejs-firestore/compare/v7.11.5...v7.11.6) (2025-09-26) + + +### Bug Fixes + +* Pool.ts: add even more logging ([c508d1b](https://github.com/googleapis/nodejs-firestore/commit/c508d1bd653f5d2b9bbe78236fac15e999c27e69)) + +## [7.11.5](https://github.com/googleapis/nodejs-firestore/compare/v7.11.4...v7.11.5) (2025-09-22) + + +### Bug Fixes + +* Pool.ts: add more detailed logging for client garbage collection ([#2420](https://github.com/googleapis/nodejs-firestore/issues/2420)) ([1bbca46](https://github.com/googleapis/nodejs-firestore/commit/1bbca46ff2a6ea98b52a83ff7dae6092e69b044d)) + +## [7.11.4](https://github.com/googleapis/nodejs-firestore/compare/v7.11.3...v7.11.4) (2025-09-16) + + +### Bug Fixes + +* Improve debug logging for the internal client pool. Added client IDs to debug log statements for client management. ([99918f1](https://github.com/googleapis/nodejs-firestore/commit/99918f1794adee706c4f2685cd3f8aea6dff895e)) + +## [7.11.3](https://github.com/googleapis/nodejs-firestore/compare/v7.11.2...v7.11.3) (2025-07-09) + + +### Bug Fixes + +* Improve performance of the UTF-8 string comparison logic ([#2380](https://github.com/googleapis/nodejs-firestore/issues/2380)) ([bc6a03e](https://github.com/googleapis/nodejs-firestore/commit/bc6a03e2b44e740b32676d7d0bec07feaa509b5b)) + +## [7.11.2](https://github.com/googleapis/nodejs-firestore/compare/v7.11.1...v7.11.2) (2025-06-19) + + +### Bug Fixes + +* Firestore Client caching stub in bad state issue ([#2365](https://github.com/googleapis/nodejs-firestore/issues/2365)) ([04ad0a4](https://github.com/googleapis/nodejs-firestore/commit/04ad0a4c0fb370db8aeae87dc6ab8bd06eafedd4)) + +## [7.11.1](https://github.com/googleapis/nodejs-firestore/compare/v7.11.0...v7.11.1) (2025-05-02) + + +### Bug Fixes + +* Aggregate query readtime bug ([#2331](https://github.com/googleapis/nodejs-firestore/issues/2331)) ([9ac0394](https://github.com/googleapis/nodejs-firestore/commit/9ac0394df78619bf1d6b7907a364342796a4f0fb)) +* Bump default deadline on CreateDatabase and RestoreDatabase to 2 minutes ([#2274](https://github.com/googleapis/nodejs-firestore/issues/2274)) ([d559080](https://github.com/googleapis/nodejs-firestore/commit/d559080a0f436927108ec69c2910af4e8246a8b0)) +* Close default BulkWriter upon terminate. ([#2276](https://github.com/googleapis/nodejs-firestore/issues/2276)) ([1e714a8](https://github.com/googleapis/nodejs-firestore/commit/1e714a8b7952b65872e65533cfe74d303dfabe20)) +* Correctly escape field paths with multiple backslashes or backticks ([#2259](https://github.com/googleapis/nodejs-firestore/issues/2259)) ([#2261](https://github.com/googleapis/nodejs-firestore/issues/2261)) ([7056ba7](https://github.com/googleapis/nodejs-firestore/commit/7056ba76040b9369d86c57838ef938c9d9ef73d8)) +* Do not send page size with auto-paginate. Fixes warnings in listCollections and listDocuments. ([#2336](https://github.com/googleapis/nodejs-firestore/issues/2336)) ([844b4ca](https://github.com/googleapis/nodejs-firestore/commit/844b4ca9c209e649565d122940858409d808baa6)) +* Finalize fixing typings for headers in generator ([#2287](https://github.com/googleapis/nodejs-firestore/issues/2287)) ([c6c85b6](https://github.com/googleapis/nodejs-firestore/commit/c6c85b66a25b56bd23c19285302a740b0ca85d25)) +* Prevent crashes if an inactive stream receives an error. ([#2283](https://github.com/googleapis/nodejs-firestore/issues/2283)) ([f58fe79](https://github.com/googleapis/nodejs-firestore/commit/f58fe791c7afc59087e2555f7208cdb611470d80)) +* Remove unused "long" dependency from firestore proto ([#2324](https://github.com/googleapis/nodejs-firestore/issues/2324)) ([5937b93](https://github.com/googleapis/nodejs-firestore/commit/5937b93aa1aacd2f63bf1678ec569c504cf0b186)) +* Sort document reference by long type id ([#2257](https://github.com/googleapis/nodejs-firestore/issues/2257)) ([3fd0de9](https://github.com/googleapis/nodejs-firestore/commit/3fd0de93076adfe17aaae9e0a9b732bcae52d594)) +* Sort strings in UTF-8 encoded byte order ([#2275](https://github.com/googleapis/nodejs-firestore/issues/2275)) ([a2950e0](https://github.com/googleapis/nodejs-firestore/commit/a2950e0b6464012f0e6c5703d0d28c2175cd35a2)) +* Use lazy encoding for utf-8 encoded string comparison ([#2299](https://github.com/googleapis/nodejs-firestore/issues/2299)) ([e8777e1](https://github.com/googleapis/nodejs-firestore/commit/e8777e12db41096c3945afd3be7905c1c029493c)) + +## [7.11.0](https://github.com/googleapis/nodejs-firestore/compare/v7.10.0...v7.11.0) (2024-12-05) + + +### Features + +* [proto] add Database.CmekConfig and Database.cmek_config (information about CMEK enablement) ([2779896](https://github.com/googleapis/nodejs-firestore/commit/27798966c5d72616fc0cee109e1d28f693c9f5f1)) +* [proto] add Database.delete_time (the time a database was deleted, if it ever was) ([2779896](https://github.com/googleapis/nodejs-firestore/commit/27798966c5d72616fc0cee109e1d28f693c9f5f1)) +* [proto] add Database.previous_id (if a database was deleted, what ID it was using beforehand) ([2779896](https://github.com/googleapis/nodejs-firestore/commit/27798966c5d72616fc0cee109e1d28f693c9f5f1)) +* [proto] add Database.SourceInfo and Database.source_info (information about database provenance, specifically for restored databases) ([2779896](https://github.com/googleapis/nodejs-firestore/commit/27798966c5d72616fc0cee109e1d28f693c9f5f1)) +* [proto] allow specifying an encryption_config when restoring a database ([2779896](https://github.com/googleapis/nodejs-firestore/commit/27798966c5d72616fc0cee109e1d28f693c9f5f1)) +* Enable tracing via OpenTelemetry. ([#2218](https://github.com/googleapis/nodejs-firestore/issues/2218)) ([1ddb62e](https://github.com/googleapis/nodejs-firestore/commit/1ddb62ed67e93ca2c265556bb5e504d207a639a8)) +* Support `fire-admin` tag for Admin Node SDK ([#2238](https://github.com/googleapis/nodejs-firestore/issues/2238)) ([#2252](https://github.com/googleapis/nodejs-firestore/issues/2252)) ([1339dc2](https://github.com/googleapis/nodejs-firestore/commit/1339dc20e3ffc065f5f79a82baaa67deda76fb36)) + + +### Bug Fixes + +* Use correct limit when retrying a limit query stream with a cursor ([#2203](https://github.com/googleapis/nodejs-firestore/issues/2203)) ([ab94092](https://github.com/googleapis/nodejs-firestore/commit/ab94092c2375501dd2998a458fc8a449793c9e69)) + +## [7.10.0](https://github.com/googleapis/nodejs-firestore/compare/v7.9.0...v7.10.0) (2024-09-05) + + +### Features + +* Expose proto changes for the bulk delete api ([23ce891](https://github.com/googleapis/nodejs-firestore/commit/23ce89175ce315648ce9af3994cba0decc48ba47)) +* Expose the proto changes to support FindNearest.distance_result_field parameter and the FindNearest.distance_threshold parameter ([23ce891](https://github.com/googleapis/nodejs-firestore/commit/23ce89175ce315648ce9af3994cba0decc48ba47)) +* Return computed distance and set distance thresholds on VectorQueries ([#2090](https://github.com/googleapis/nodejs-firestore/issues/2090)) ([b5ca84f](https://github.com/googleapis/nodejs-firestore/commit/b5ca84f076ca0668e90ca3fc7dd878f732ccd956)) + +## [7.9.0](https://github.com/googleapis/nodejs-firestore/compare/v7.8.0...v7.9.0) (2024-06-25) + + +### Features + +* Update FirebaseFirestore.v1 and FirebaseFirestore.v1beta1 auto-gen types ([6732d4d](https://github.com/googleapis/nodejs-firestore/commit/6732d4da3c5ea851dccb0515757fbfb521f21410)) + +## [7.8.0](https://github.com/googleapis/nodejs-firestore/compare/v7.7.0...v7.8.0) (2024-05-28) + + +### Features + +* Query profiling for VectorQuery ([d406f14](https://github.com/googleapis/nodejs-firestore/commit/d406f14612a4890e405913aadc75c7ee22993f2b)) +* Update Nodejs generator to send API versions in headers for GAPICs ([#2041](https://github.com/googleapis/nodejs-firestore/issues/2041)) ([6dbe4b0](https://github.com/googleapis/nodejs-firestore/commit/6dbe4b0baac261f03f9032765b375938ce5e46d7)) + +## [7.7.0](https://github.com/googleapis/nodejs-firestore/compare/v7.6.0...v7.7.0) (2024-05-07) + + +### Features + +* Add several fields to manage state of database encryption update ([5811492](https://github.com/googleapis/nodejs-firestore/commit/5811492357c7b66324839c02bcbf45a5b6d6d7e7)) +* Lazy-started transactions ([#2017](https://github.com/googleapis/nodejs-firestore/issues/2017)) ([2c726a1](https://github.com/googleapis/nodejs-firestore/commit/2c726a176407c45f519846052469e1bbbbc24750)) + + +### Bug Fixes + +* Nonblocking rollback ([#2039](https://github.com/googleapis/nodejs-firestore/issues/2039)) ([52099c8](https://github.com/googleapis/nodejs-firestore/commit/52099c8eb8ce8aba0ab5aee9f3dd4c4a59c2afd4)) +* Upgrade the `google-gax` dependency version. ([#2040](https://github.com/googleapis/nodejs-firestore/issues/2040)) ([0b9efa6](https://github.com/googleapis/nodejs-firestore/commit/0b9efa6d5a3d46ad2f084aef58c529e710c7f596)) + +## [7.6.0](https://github.com/googleapis/nodejs-firestore/compare/v7.5.0...v7.6.0) (2024-04-02) + + +### Features + +* Vector Search ([#2006](https://github.com/googleapis/nodejs-firestore/issues/2006)) ([e906b42](https://github.com/googleapis/nodejs-firestore/commit/e906b4260da11fe5a1c34ae5f68d9f5717a99dab)) + +## [7.5.0](https://github.com/googleapis/nodejs-firestore/compare/v7.4.0...v7.5.0) (2024-03-25) + + +### Features + +* Protos and autogen client for vector ([#2027](https://github.com/googleapis/nodejs-firestore/issues/2027)) ([c65cef0](https://github.com/googleapis/nodejs-firestore/commit/c65cef04332e20be82129d0c49396485be683585)) +* Query Profile ([#2014](https://github.com/googleapis/nodejs-firestore/issues/2014)) ([9a45ec8](https://github.com/googleapis/nodejs-firestore/commit/9a45ec89fb3a8d9814bc186d7d494f5859946ffa)) + +## [7.4.0](https://github.com/googleapis/nodejs-firestore/compare/v7.3.1...v7.4.0) (2024-03-15) + + +### Features + +* A new message `Backup` is added ([#2021](https://github.com/googleapis/nodejs-firestore/issues/2021)) ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new message `BackupSchedule` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new message `CreateBackupScheduleRequest` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new message `DailyRecurrence` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new message `DeleteBackupRequest` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new message `DeleteBackupScheduleRequest` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new message `GetBackupRequest` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new message `GetBackupScheduleRequest` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new message `ListBackupSchedulesRequest` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new message `ListBackupSchedulesResponse` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new message `ListBackupsRequest` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new message `ListBackupsResponse` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new message `RestoreDatabaseMetadata` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new message `RestoreDatabaseRequest` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new message `UpdateBackupScheduleRequest` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new message `WeeklyRecurrence` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new method `CreateBackupSchedule` is added to service `FirestoreAdmin` ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new method `DeleteBackup` is added to service `FirestoreAdmin` ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new method `DeleteBackupSchedule` is added to service `FirestoreAdmin` ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new method `GetBackup` is added to service `FirestoreAdmin` ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new method `GetBackupSchedule` is added to service `FirestoreAdmin` ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new method `ListBackups` is added to service `FirestoreAdmin` ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new method `ListBackupSchedules` is added to service `FirestoreAdmin` ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new method `RestoreDatabase` is added to service `FirestoreAdmin` ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new method `UpdateBackupSchedule` is added to service `FirestoreAdmin` ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new resource_definition `firestore.googleapis.com/Backup` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* A new resource_definition `firestore.googleapis.com/BackupSchedule` is added ([6bced86](https://github.com/googleapis/nodejs-firestore/commit/6bced86eabd143947e94e83872f20d7ed9d964dc)) +* Add new types ExplainOptions, ExplainMetrics, PlanSummary, ExecutionStats ([#2013](https://github.com/googleapis/nodejs-firestore/issues/2013)) ([e598b9d](https://github.com/googleapis/nodejs-firestore/commit/e598b9daf628cbc54dc10dab80bb0f46e2a3e2a2)) + + +### Bug Fixes + +* ReadOnly transaction do not need to commit not rollback. ([#2007](https://github.com/googleapis/nodejs-firestore/issues/2007)) ([6a220a6](https://github.com/googleapis/nodejs-firestore/commit/6a220a6f6563903673066576f09ecf405c53f87b)) +* Update service definitions ([#2016](https://github.com/googleapis/nodejs-firestore/issues/2016)) ([ea4b6d0](https://github.com/googleapis/nodejs-firestore/commit/ea4b6d05383751f9a089958a20c1dd56419bc66d)) + +## [7.3.1](https://github.com/googleapis/nodejs-firestore/compare/v7.3.0...v7.3.1) (2024-03-04) + + +### Bug Fixes + +* Add client library version to headers ([#2003](https://github.com/googleapis/nodejs-firestore/issues/2003)) ([8799032](https://github.com/googleapis/nodejs-firestore/commit/8799032d8cc39adc774fe21b7eb70f96a3a18fda)) +* Add missing type for exposed database id ([#1996](https://github.com/googleapis/nodejs-firestore/issues/1996)) ([e967279](https://github.com/googleapis/nodejs-firestore/commit/e967279cfe532ae3375ae9dcb94f4a65af5ffb42)) +* Optimize Transaction PITR ([#2002](https://github.com/googleapis/nodejs-firestore/issues/2002)) ([2f08612](https://github.com/googleapis/nodejs-firestore/commit/2f0861296151f7b0094501e4a9ff6fc4154d52a4)) +* Revert changes to streaming retries ([d964a13](https://github.com/googleapis/nodejs-firestore/commit/d964a13818e6bc4be6547e88ffbe16be1a6ceeeb)) + +## [7.3.0](https://github.com/googleapis/nodejs-firestore/compare/v7.2.0...v7.3.0) (2024-01-31) + + +### Features + +* Expose the undeliverable_first_gen_event.proto ([b4f7d60](https://github.com/googleapis/nodejs-firestore/commit/b4f7d6015b50f1da6afeae0b4215be416596cc69)) + + +### Bug Fixes + +* Allow an explicit MustExist precondition for update ([#1985](https://github.com/googleapis/nodejs-firestore/issues/1985)) ([99d60a6](https://github.com/googleapis/nodejs-firestore/commit/99d60a6f87b70c942ac2bd9464cc6d64323f9dfb)) +* Fix redaction of credentials in Firestore settings ([#1989](https://github.com/googleapis/nodejs-firestore/issues/1989)) ([98e668b](https://github.com/googleapis/nodejs-firestore/commit/98e668bb9ce7feb090f65fc61d92af433bc23094)) +* Improve retry logic for streaming API calls ([b4f7d60](https://github.com/googleapis/nodejs-firestore/commit/b4f7d6015b50f1da6afeae0b4215be416596cc69)) +* Removed unsupported QueryMode, QueryPlan, and ResultSetStats protos ([b4f7d60](https://github.com/googleapis/nodejs-firestore/commit/b4f7d6015b50f1da6afeae0b4215be416596cc69)) + +## [7.2.0](https://github.com/googleapis/nodejs-firestore/compare/v7.1.1...v7.2.0) (2024-01-16) + + +### Features + +* Add new types QueryMode, QueryPlan, ResultSetStats ([#1911](https://github.com/googleapis/nodejs-firestore/issues/1911)) ([8f77b68](https://github.com/googleapis/nodejs-firestore/commit/8f77b68bf70b04a66e982067aa246de0596e4ea2)) +* Expose databaseId and projectId getter on Firestore class ([#1937](https://github.com/googleapis/nodejs-firestore/issues/1937)) ([d9c867f](https://github.com/googleapis/nodejs-firestore/commit/d9c867fc5048748e5af378fd8465303224668781)), closes [#1936](https://github.com/googleapis/nodejs-firestore/issues/1936) + + +### Bug Fixes + +* Make transaction rollback best effort. ([#1967](https://github.com/googleapis/nodejs-firestore/issues/1967)) ([1d76546](https://github.com/googleapis/nodejs-firestore/commit/1d76546a781527ef5b9085fc9f189c024355ae9f)) + +## [7.1.1](https://github.com/googleapis/nodejs-firestore/compare/v7.1.0...v7.1.1) (2023-11-20) + + +### Bug Fixes + +* Remove temporary header encoding workaround ([#1935](https://github.com/googleapis/nodejs-firestore/issues/1935)) ([8a4ae5b](https://github.com/googleapis/nodejs-firestore/commit/8a4ae5b07712588bd0deae917d9e17f34f1ebb60)) +* Update retry policy to not retry streams that have not made progress receiving documents ([170d05b](https://github.com/googleapis/nodejs-firestore/commit/170d05b1fa6c720d1109506ed3d3feb525c16efe)) + +## [7.1.0](https://github.com/googleapis/nodejs-firestore/compare/v7.0.0...v7.1.0) (2023-10-11) + + +### Features + +* Sum and Average aggregations ([#1873](https://github.com/googleapis/nodejs-firestore/issues/1873)) ([b9ea514](https://github.com/googleapis/nodejs-firestore/commit/b9ea5143f997dd217200ffa83ed481ad74f558e4)) + +## [7.0.0](https://github.com/googleapis/nodejs-firestore/compare/v6.8.0...v7.0.0) (2023-10-03) + + +### ⚠ BREAKING CHANGES + +* upgrade to Node 14 ([#1900](https://github.com/googleapis/nodejs-firestore/issues/1900)) +* Fix the UpdateData incorrect parameter type issue ([#1887](https://github.com/googleapis/nodejs-firestore/issues/1887)) + +### Features + +* Fix the UpdateData incorrect parameter type issue ([#1887](https://github.com/googleapis/nodejs-firestore/issues/1887)) ([0afadef](https://github.com/googleapis/nodejs-firestore/commit/0afadeff4706e7bff173d8eda7b9681498b570a8)) + + +### Bug Fixes + +* Remove DocumentReference from cursor ([#1882](https://github.com/googleapis/nodejs-firestore/issues/1882)) ([da4f8f8](https://github.com/googleapis/nodejs-firestore/commit/da4f8f8b6a35fa93aca0eddc96703d3321a998f6)) + + +### Miscellaneous Chores + +* Upgrade to Node 14 ([#1900](https://github.com/googleapis/nodejs-firestore/issues/1900)) ([1f5abb8](https://github.com/googleapis/nodejs-firestore/commit/1f5abb8fbef91e372313b2dbf4d51c7d03ce69b0)) + +## [6.8.0](https://github.com/googleapis/nodejs-firestore/compare/v6.7.0...v6.8.0) (2023-09-26) + + +### Features + +* Publish proto definitions for SUM/AVG in Firestore ([#1856](https://github.com/googleapis/nodejs-firestore/issues/1856)) ([ac35b37](https://github.com/googleapis/nodejs-firestore/commit/ac35b372faf32f093d83af18d487f1b3f23ee673)) + + +### Bug Fixes + +* **deps:** Use protobufjs v7.2.5 ([#1889](https://github.com/googleapis/nodejs-firestore/pull/1889)) +* Add tests for multiple inequality support ([#1878](https://github.com/googleapis/nodejs-firestore/issues/1878)) ([8e621d5](https://github.com/googleapis/nodejs-firestore/commit/8e621d580396b7e3bc7e42dad0c63f91e999411f)) + +## [6.7.0](https://github.com/googleapis/nodejs-firestore/compare/v6.6.1...v6.7.0) (2023-07-20) + + +### Features + +* Expose MultiDb ([#1857](https://github.com/googleapis/nodejs-firestore/issues/1857)) ([1e913db](https://github.com/googleapis/nodejs-firestore/commit/1e913dbec97a6ec9339f641e7590ac4d65c7fd17)) + + +### Bug Fixes + +* Resolving issues with MultiDb support ([#1864](https://github.com/googleapis/nodejs-firestore/issues/1864)) ([1af49c1](https://github.com/googleapis/nodejs-firestore/commit/1af49c1a852c6a89a7e21a9e749d667b3b728acf)) + +## [6.6.1](https://github.com/googleapis/nodejs-firestore/compare/v6.6.0...v6.6.1) (2023-06-01) + + +### Bug Fixes + +* Updated logging in the client pool and client factory to log information about the required transport and actual transport used. ([#1853](https://github.com/googleapis/nodejs-firestore/issues/1853)) ([fe03d02](https://github.com/googleapis/nodejs-firestore/commit/fe03d02efc0d8e4ca90daea97f9e3339074d415d)) + +## [6.6.0](https://github.com/googleapis/nodejs-firestore/compare/v6.5.0...v6.6.0) (2023-05-18) + + +### Features + +* Add ApiScope and COLLECTION_RECURSIVE query_scope for Firestore index ([#1849](https://github.com/googleapis/nodejs-firestore/issues/1849)) ([b671452](https://github.com/googleapis/nodejs-firestore/commit/b6714528956f3907b1ca4aded372592ef00d34d6)) +* Add bloom filter related proto fields ([#1843](https://github.com/googleapis/nodejs-firestore/issues/1843)) ([b64e0c1](https://github.com/googleapis/nodejs-firestore/commit/b64e0c15d0f824a688ff42a8ad940b520f87cf9b)) +* Add support for environment variable FIRESTORE_PREFER_REST ([#1848](https://github.com/googleapis/nodejs-firestore/issues/1848)) ([96b1d2a](https://github.com/googleapis/nodejs-firestore/commit/96b1d2ab3248f6c4bb70d1cf735aea827a2a13da)) + +## [6.5.0](https://github.com/googleapis/nodejs-firestore/compare/v6.4.3...v6.5.0) (2023-03-06) + + +### Features + +* OR Queries ([#1800](https://github.com/googleapis/nodejs-firestore/issues/1800)) ([983a477](https://github.com/googleapis/nodejs-firestore/commit/983a477a6c1a22e4efba0df07e750910028e0afb)) + + +### Bug Fixes + +* Enable REST numeric enums ([#1829](https://github.com/googleapis/nodejs-firestore/issues/1829)) ([3737696](https://github.com/googleapis/nodejs-firestore/commit/3737696791b3b77fe9b333323523d8a0abcf5f7b)) +* Update generated proto types; fix the update script ([#1825](https://github.com/googleapis/nodejs-firestore/issues/1825)) ([a7e4212](https://github.com/googleapis/nodejs-firestore/commit/a7e42123da1325f526fa5c3a62f1d3dc7a2569c3)) + +## [6.4.3](https://github.com/googleapis/nodejs-firestore/compare/v6.4.2...v6.4.3) (2023-02-16) + + +### Bug Fixes + +* **deps:** Use google-gax v3.5.3 ([#1818](https://github.com/googleapis/nodejs-firestore/issues/1818)) ([88981ad](https://github.com/googleapis/nodejs-firestore/commit/88981ad8749b0aa38dfe9bcdd4ca5e60d76c8776)) +* Emulator support for system tests. Run system tests against the emulator using: `yarn system-test:grpc:emulator` or `yarn system-test:rest:emulator` ([8aedc63](https://github.com/googleapis/nodejs-firestore/commit/8aedc63138827ea03a8dacae4e7bccdf048a2be7)) +* Update the depth validation used when writing documents, so that it matches the validation of the Firestore backend. ([789d9eb](https://github.com/googleapis/nodejs-firestore/commit/789d9eb7f54b5329b17ef759f29252d17da47e26)) + +## [6.4.2](https://github.com/googleapis/nodejs-firestore/compare/v6.4.1...v6.4.2) (2023-01-09) + + +### Bug Fixes + +* **deps:** Use google-gax v3.5.2 ([#1794](https://github.com/googleapis/nodejs-firestore/issues/1794)) ([b1a0313](https://github.com/googleapis/nodejs-firestore/commit/b1a0313498b0c3569bd74ce96fce80b8f9bee1a9)) +* Ensure that the client pool consistently uses gRPC clients after transitioning from REST ([3068361](https://github.com/googleapis/nodejs-firestore/commit/306836163ae01221aa9c0076c76093e727c74a08)) +* Fix duplicates in Query.stream() with back pressure ([#1806](https://github.com/googleapis/nodejs-firestore/issues/1806)) ([a5b680d](https://github.com/googleapis/nodejs-firestore/commit/a5b680da034d600babb9e3495fb8a7bf019d1315)) + +## [6.4.1](https://github.com/googleapis/nodejs-firestore/compare/v6.4.0...v6.4.1) (2022-10-17) + + +### Bug Fixes + +* Force use of http by the GAX module when using the GAX fallback and connecting to the emulator ([#1788](https://github.com/googleapis/nodejs-firestore/issues/1788)) ([50747ad](https://github.com/googleapis/nodejs-firestore/commit/50747ad52b19da9ed87282af98eadff660dffb75)) + +## [6.4.0](https://github.com/googleapis/nodejs-firestore/compare/v6.3.0...v6.4.0) (2022-10-07) + + +### Features + +* Add internal multi-db support ([#1761](https://github.com/googleapis/nodejs-firestore/issues/1761)) ([5ba8df0](https://github.com/googleapis/nodejs-firestore/commit/5ba8df011264b435b53499642e68afd73859f332)) +* COUNT Queries ([#1774](https://github.com/googleapis/nodejs-firestore/issues/1774)) ([bcaecb4](https://github.com/googleapis/nodejs-firestore/commit/bcaecb45b7911073bb968542df0267ba81d4462d)) + + +### Bug Fixes + +* Remove [@internal](https://github.com/internal) annotation from snapshot_ ([#1728](https://github.com/googleapis/nodejs-firestore/issues/1728)) ([983ab89](https://github.com/googleapis/nodejs-firestore/commit/983ab89387d8c5314680d1520c3bece011ee6a64)) + +## [6.3.0](https://github.com/googleapis/nodejs-firestore/compare/v6.2.0...v6.3.0) (2022-09-22) + + +### Features + +* Add aggregation query APIs ([#1765](https://github.com/googleapis/nodejs-firestore/issues/1765)) ([18be4d0](https://github.com/googleapis/nodejs-firestore/commit/18be4d0ca3a8e927a883ba6e41a43d19fb2af665)) + + +### Bug Fixes + +* Tests will now verify asynchronous termination of underlying steam, and fix related bug. ([#1772](https://github.com/googleapis/nodejs-firestore/issues/1772)) ([a1717ff](https://github.com/googleapis/nodejs-firestore/commit/a1717ff279f1ea9647e28b8e93539bcad9739af0)) + +## [6.2.0](https://github.com/googleapis/nodejs-firestore/compare/v6.1.0...v6.2.0) (2022-09-13) + + +### Features + +* Use REST ([#1698](https://github.com/googleapis/nodejs-firestore/issues/1698)) ([d85b0e9](https://github.com/googleapis/nodejs-firestore/commit/d85b0e93bcb4a5806490ee66a4443afd4a0a519a)) + + +### Bug Fixes + +* Minify proto JSON files ([#1771](https://github.com/googleapis/nodejs-firestore/issues/1771)) ([6393fe7](https://github.com/googleapis/nodejs-firestore/commit/6393fe704097a1214961fa30f01832a64dced775)) +* Remove hack in update.sh, and replace with existing pattern for protobuf dependencies. ([#1769](https://github.com/googleapis/nodejs-firestore/issues/1769)) ([6ba6751](https://github.com/googleapis/nodejs-firestore/commit/6ba67517123578a93bb3e0eeb771b610ac3ee397)) + +## [6.1.0](https://github.com/googleapis/nodejs-firestore/compare/v6.0.0...v6.1.0) (2022-09-07) + + +### Features + +* Accept google-gax instance as a parameter ([#1757](https://github.com/googleapis/nodejs-firestore/issues/1757)) ([ef59a22](https://github.com/googleapis/nodejs-firestore/commit/ef59a22a8abd894d4d3e8b05f075f510de26019f)) + + +### Bug Fixes + +* Better support for fallback mode ([#1756](https://github.com/googleapis/nodejs-firestore/issues/1756)) ([a029a6e](https://github.com/googleapis/nodejs-firestore/commit/a029a6e602ef5ed6553ecc7022623fcd81763c7e)) +* Don't allow serialization of firestore settings ([#1742](https://github.com/googleapis/nodejs-firestore/issues/1742)) ([fa0ad66](https://github.com/googleapis/nodejs-firestore/commit/fa0ad66bc7e4a0c46f1ae5ca10b2a6f3a528ab6f)) +* Pin Typescript to prevent new type checking. ([#1764](https://github.com/googleapis/nodejs-firestore/issues/1764)) ([dd01b27](https://github.com/googleapis/nodejs-firestore/commit/dd01b27022e35ddf6793d71451d0b86f549288fe)) +* Update GAX ([#1758](https://github.com/googleapis/nodejs-firestore/issues/1758)) ([1931415](https://github.com/googleapis/nodejs-firestore/commit/19314159a9907dfea8301b41d8050b0d2e783dd8)) +* Version 7 of protobufjs broke the update.sh script. Added path to built in protobuf. ([#1766](https://github.com/googleapis/nodejs-firestore/issues/1766)) ([40f1db3](https://github.com/googleapis/nodejs-firestore/commit/40f1db379ba01174471bbb91cdddc88f929c9b46)) + +## [6.0.0](https://github.com/googleapis/nodejs-firestore/compare/v5.0.2...v6.0.0) (2022-07-22) + + +### ⚠ BREAKING CHANGES + +* update library to use Node 12 (#1725) + +### Features + +* Enable RunQueryResponse.done ([#1712](https://github.com/googleapis/nodejs-firestore/issues/1712)) ([0cc549c](https://github.com/googleapis/nodejs-firestore/commit/0cc549c69ccc59e25f8347d6b236f8b9b04dc105)) +* Support Logical Termination on RunQueryResponse ([#1741](https://github.com/googleapis/nodejs-firestore/issues/1741)) ([07de28a](https://github.com/googleapis/nodejs-firestore/commit/07de28a04cdea27c5f859091aaf30d16bd8a8c3c)) +* support regapic LRO ([#1729](https://github.com/googleapis/nodejs-firestore/issues/1729)) ([b9d8fef](https://github.com/googleapis/nodejs-firestore/commit/b9d8fefc5f927d1f064a79ec0990d256803360cd)) +* update client libraries to support Database operations ([#1676](https://github.com/googleapis/nodejs-firestore/issues/1676)) ([533aade](https://github.com/googleapis/nodejs-firestore/commit/533aade3272f07b39bbad2c32a5d9669fde6de53)) + + +### Bug Fixes + +* change REST binding for ListDocuments to support root collection ([#1695](https://github.com/googleapis/nodejs-firestore/issues/1695)) ([6185f13](https://github.com/googleapis/nodejs-firestore/commit/6185f13070ff9dda91d7128e3b8a1db7f09914a8)) +* **deps:** update dependency protobufjs to v7 ([#1747](https://github.com/googleapis/nodejs-firestore/issues/1747)) ([4e8d33c](https://github.com/googleapis/nodejs-firestore/commit/4e8d33cce418dfb004725ce2271121fd1fdbd9b2)) +* split v1 and v1beta1 protos to improve startup time ([#1664](https://github.com/googleapis/nodejs-firestore/issues/1664)) ([f3729cf](https://github.com/googleapis/nodejs-firestore/commit/f3729cf49818b9b929a556e7a8e8a5588b5f2726)) + + +### Build System + +* update library to use Node 12 ([#1725](https://github.com/googleapis/nodejs-firestore/issues/1725)) ([0abbd21](https://github.com/googleapis/nodejs-firestore/commit/0abbd215d4574f238b40630361d0836432ead3af)) + +### [5.0.2](https://www.github.com/googleapis/nodejs-firestore/compare/v5.0.1...v5.0.2) (2022-01-07) + + +### Bug Fixes + +* remove serializer check from Query.isEqual() ([#1654](https://www.github.com/googleapis/nodejs-firestore/issues/1654)) ([f13da18](https://www.github.com/googleapis/nodejs-firestore/commit/f13da184bd2b4f9abfe920f6d9f7af8f2f6f37cb)) + +### [5.0.1](https://www.github.com/googleapis/nodejs-firestore/compare/v5.0.0...v5.0.1) (2021-12-02) + + +### Bug Fixes + +* save negative zero as doubleValue ([#1639](https://www.github.com/googleapis/nodejs-firestore/issues/1639)) ([a6ba5cc](https://www.github.com/googleapis/nodejs-firestore/commit/a6ba5ccf8b21dbe117e5d8ad5fc1e26d16ed0d1d)) + +## [5.0.0](https://www.github.com/googleapis/nodejs-firestore/compare/v4.15.1...v5.0.0) (2021-11-23) + + +### ⚠ BREAKING CHANGES + +* upgrade Typescript to v4.1.5 and add converter and typing upgrades (#1632) + +### Features + +* upgrade Typescript to v4.1.5 and add converter and typing upgrades ([#1632](https://www.github.com/googleapis/nodejs-firestore/issues/1632)) ([c293955](https://www.github.com/googleapis/nodejs-firestore/commit/c293955fecd19d12abcb9c441c39ef2664cb011b)) + +### [4.15.1](https://www.github.com/googleapis/nodejs-firestore/compare/v4.15.0...v4.15.1) (2021-09-03) + + +### Bug Fixes + +* **build:** migrate to main branch ([#1601](https://www.github.com/googleapis/nodejs-firestore/issues/1601)) ([6f16b9a](https://www.github.com/googleapis/nodejs-firestore/commit/6f16b9ab9e1365b99498e9df4d56a88db313f9a6)) + +## [4.15.0](https://www.github.com/googleapis/nodejs-firestore/compare/v4.14.2...v4.15.0) (2021-08-26) + + +### Features + +* turns on self-signed JWT feature flag ([#1593](https://www.github.com/googleapis/nodejs-firestore/issues/1593)) ([feee8cc](https://www.github.com/googleapis/nodejs-firestore/commit/feee8cc1b32ab04613f654806ca31477328059ff)) + + +### Bug Fixes + +* Handles identical document ids from different collections. ([#1599](https://www.github.com/googleapis/nodejs-firestore/issues/1599)) ([745b608](https://www.github.com/googleapis/nodejs-firestore/commit/745b608a7883a27ccb1c4d1f7800fdcc9a7917b1)) + +### [4.14.2](https://www.github.com/googleapis/nodejs-firestore/compare/v4.14.1...v4.14.2) (2021-08-17) + + +### Bug Fixes + +* **deps:** google-gax v2.24.1 ([#1588](https://www.github.com/googleapis/nodejs-firestore/issues/1588)) ([56150b6](https://www.github.com/googleapis/nodejs-firestore/commit/56150b62f55d765c0c221aed70b999477f867ace)) + +### [4.14.1](https://www.github.com/googleapis/nodejs-firestore/compare/v4.14.0...v4.14.1) (2021-08-02) + + +### Bug Fixes + +* avoid destructuring undefined timestamps ([#1575](https://www.github.com/googleapis/nodejs-firestore/issues/1575)) ([a61a24a](https://www.github.com/googleapis/nodejs-firestore/commit/a61a24a44e70a9693f552a3a39f4579d861fd77f)) + +## [4.14.0](https://www.github.com/googleapis/nodejs-firestore/compare/v4.13.2...v4.14.0) (2021-07-30) + + +### Features + +* add "NON_EMPTY_DEFAULT" FieldBehavior ([#1554](https://www.github.com/googleapis/nodejs-firestore/issues/1554)) ([8d9c503](https://www.github.com/googleapis/nodejs-firestore/commit/8d9c50381eedf6ee8043eed681d03b44262b9820)) +* allow UnhandledPromiseRejection errors in BulkWriter if no error handler is specified ([#1572](https://www.github.com/googleapis/nodejs-firestore/issues/1572)) ([e862ac8](https://www.github.com/googleapis/nodejs-firestore/commit/e862ac81cbb99287a226989b184fc2e683defa16)) + +### [4.13.2](https://www.github.com/googleapis/nodejs-firestore/compare/v4.13.1...v4.13.2) (2021-07-14) + + +### Bug Fixes + +* **deps:** google-gax v2.17.1 ([#1557](https://www.github.com/googleapis/nodejs-firestore/issues/1557)) ([866bd25](https://www.github.com/googleapis/nodejs-firestore/commit/866bd255d930850956609a0941d4010847c0d196)) +* lower batch size on BulkWriter retry to stay under throughput limits ([#1556](https://www.github.com/googleapis/nodejs-firestore/issues/1556)) ([f17a36e](https://www.github.com/googleapis/nodejs-firestore/commit/f17a36e3fa1ce532c1c68ed63ea1845408368469)) + +### [4.13.1](https://www.github.com/googleapis/nodejs-firestore/compare/v4.13.0...v4.13.1) (2021-07-01) + + +### Bug Fixes + +* lower batch size on BulkWriter retry ([#1549](https://www.github.com/googleapis/nodejs-firestore/issues/1549)) ([26d480b](https://www.github.com/googleapis/nodejs-firestore/commit/26d480b4a7fbeb26e99bb23d7aa1fbd4802b738a)) + +## [4.13.0](https://www.github.com/googleapis/nodejs-firestore/compare/v4.12.3...v4.13.0) (2021-06-29) + + +### Features + +* add read-only transactions ([#1541](https://www.github.com/googleapis/nodejs-firestore/issues/1541)) ([ca4241e](https://www.github.com/googleapis/nodejs-firestore/commit/ca4241eb3ee4abb8453b6da0911397187dc18dde)) +* retry BatchGetDocuments RPCs that fail with errors ([#1544](https://www.github.com/googleapis/nodejs-firestore/issues/1544)) ([b39dd3c](https://www.github.com/googleapis/nodejs-firestore/commit/b39dd3c65549fb1a651c1722d8ea2c038e152417)) + + +### Bug Fixes + +* **deps:** google-gax v2.17.0 with mTLS ([#1546](https://www.github.com/googleapis/nodejs-firestore/issues/1546)) ([a322345](https://www.github.com/googleapis/nodejs-firestore/commit/a32234510d487982b950c88575b9425c531c2d94)) +* make request optional in all cases ([#1536](https://www.github.com/googleapis/nodejs-firestore/issues/1536)) ([f6edfc1](https://www.github.com/googleapis/nodejs-firestore/commit/f6edfc181ca39cd307eab6d141db08f377d5cfdf)) + +### [4.12.3](https://www.github.com/googleapis/nodejs-firestore/compare/v4.12.2...v4.12.3) (2021-06-16) + + +### Bug Fixes + +* bulkWriter: ensure buffered batches are sent after flush ([#1535](https://www.github.com/googleapis/nodejs-firestore/issues/1535)) ([115a134](https://www.github.com/googleapis/nodejs-firestore/commit/115a13407b907887a930b4299ebed042532c3ec2)) +* GoogleAdsError missing using generator version after 1.3.0 ([#1526](https://www.github.com/googleapis/nodejs-firestore/issues/1526)) ([adfe68e](https://www.github.com/googleapis/nodejs-firestore/commit/adfe68e194d518369d5b4f89e9be89f948efbdbb)) + +### [4.12.2](https://www.github.com/googleapis/nodejs-firestore/compare/v4.12.1...v4.12.2) (2021-05-27) + + +### Bug Fixes + +* do not leak credentials in Firestore.toJSON() ([#1522](https://www.github.com/googleapis/nodejs-firestore/issues/1522)) ([791310f](https://www.github.com/googleapis/nodejs-firestore/commit/791310ff4b0a828ca6d1f5c0fa03a110972afb1f)) + +### [4.12.1](https://www.github.com/googleapis/nodejs-firestore/compare/v4.12.0...v4.12.1) (2021-05-27) + + +### Bug Fixes + +* do not load google-gax at client startup ([#1517](https://www.github.com/googleapis/nodejs-firestore/issues/1517)) ([2141b08](https://www.github.com/googleapis/nodejs-firestore/commit/2141b0879cbccb1354f9821edcc917b6aa4ff0ab)) +* recursive delete: backporting changes from Java ([#1514](https://www.github.com/googleapis/nodejs-firestore/issues/1514)) ([92ea651](https://www.github.com/googleapis/nodejs-firestore/commit/92ea651adc84ba854ae7cd203af231573f885307)) +* return results from getPartitions() in order ([#1521](https://www.github.com/googleapis/nodejs-firestore/issues/1521)) ([c8168a8](https://www.github.com/googleapis/nodejs-firestore/commit/c8168a83a864dd77f88b1743adcd3568671702fe)) + +## [4.12.0](https://www.github.com/googleapis/nodejs-firestore/compare/v4.11.1...v4.12.0) (2021-05-19) + + +### Features + +* add `gcf-owl-bot[bot]` to `ignoreAuthors` ([#1506](https://www.github.com/googleapis/nodejs-firestore/issues/1506)) ([6fa1d4d](https://www.github.com/googleapis/nodejs-firestore/commit/6fa1d4da627f17d76cf2d6109765862fd5083e03)) +* add Precondition.exists to delete() ([#1505](https://www.github.com/googleapis/nodejs-firestore/issues/1505)) ([28d645b](https://www.github.com/googleapis/nodejs-firestore/commit/28d645bd3e368abde592bfa2611de3378ca175a6)) + +### [4.11.1](https://www.github.com/googleapis/nodejs-firestore/compare/v4.11.0...v4.11.1) (2021-05-13) + + +### Bug Fixes + +* **deps:** require google-gax v2.12.0 ([#1497](https://www.github.com/googleapis/nodejs-firestore/issues/1497)) ([a8d5f0b](https://www.github.com/googleapis/nodejs-firestore/commit/a8d5f0b1e4503ef9f0d289dbf8ed67a30eb9ed4b)) + +## [4.11.0](https://www.github.com/googleapis/nodejs-firestore/compare/v4.10.1...v4.11.0) (2021-05-05) + + +### Features + +* add recursive delete to Firestore class ([#1494](https://www.github.com/googleapis/nodejs-firestore/issues/1494)) ([6f1e304](https://www.github.com/googleapis/nodejs-firestore/commit/6f1e3040800d0dcc5ed3f9f7cef16fe41804266a)) + +### [4.10.1](https://www.github.com/googleapis/nodejs-firestore/compare/v4.10.0...v4.10.1) (2021-04-28) + + +### Bug Fixes + +* type of QuerySnapshot.docChanges() should be generic ([#1484](https://www.github.com/googleapis/nodejs-firestore/issues/1484)) ([3ed1929](https://www.github.com/googleapis/nodejs-firestore/commit/3ed1929a06b4c019bbb0b1db3e1abcd62ee668d2)) + +## [4.10.0](https://www.github.com/googleapis/nodejs-firestore/compare/v4.9.9...v4.10.0) (2021-04-15) + + +### Features + +* add buffering layer to BulkWriter ([#1470](https://www.github.com/googleapis/nodejs-firestore/issues/1470)) ([9cc9548](https://www.github.com/googleapis/nodejs-firestore/commit/9cc954849c74199f01e52b24fc7ba045d5b56be4)) + + +### Bug Fixes + +* use BigInt when calculating nanos in Timestamp.fromMillis() ([#1468](https://www.github.com/googleapis/nodejs-firestore/issues/1468)) ([cf1949f](https://www.github.com/googleapis/nodejs-firestore/commit/cf1949f99f840d1e34edfa31a223418abdf48372)) + +### [4.9.9](https://www.github.com/googleapis/nodejs-firestore/compare/v4.9.8...v4.9.9) (2021-04-07) + + +### Bug Fixes + +* BulkWriter: apply rate limiter before sending batch ([#1451](https://www.github.com/googleapis/nodejs-firestore/issues/1451)) ([3a50f8b](https://www.github.com/googleapis/nodejs-firestore/commit/3a50f8b524a73d60c6034d4828682b9dc1b49d6e)) +* remove floating point rounding error in Timestamp.fromMillis() ([#1464](https://www.github.com/googleapis/nodejs-firestore/issues/1464)) ([97e7281](https://www.github.com/googleapis/nodejs-firestore/commit/97e728188a097760bd52099ec852a716a25b4745)) + +### [4.9.8](https://www.github.com/googleapis/nodejs-firestore/compare/v4.9.7...v4.9.8) (2021-03-15) + + +### Bug Fixes + +* BulkWriter: add backoff on retries ([#1447](https://www.github.com/googleapis/nodejs-firestore/issues/1447)) ([f483083](https://www.github.com/googleapis/nodejs-firestore/commit/f48308344a90d2da48af99a878f0384b7b93f704)) + +### [4.9.7](https://www.github.com/googleapis/nodejs-firestore/compare/v4.9.6...v4.9.7) (2021-03-09) + + +### Bug Fixes + +* export v1 and v1beta1 client class types correctly ([#1445](https://www.github.com/googleapis/nodejs-firestore/issues/1445)) ([6c9319e](https://www.github.com/googleapis/nodejs-firestore/commit/6c9319ed6e2ac0dfe0fcf45853f0b38dc0784686)) +* retry BulkWriter deletes that fail with RST_STREAM error ([#1442](https://www.github.com/googleapis/nodejs-firestore/issues/1442)) ([cccf48d](https://www.github.com/googleapis/nodejs-firestore/commit/cccf48de4963403a2e77ba241641a2b77fb993da)) + +### [4.9.6](https://www.github.com/googleapis/nodejs-firestore/compare/v4.9.5...v4.9.6) (2021-03-03) + + +### Bug Fixes + +* set default max ratelimiter throughput to 10k for BulkWriter ([#1439](https://www.github.com/googleapis/nodejs-firestore/issues/1439)) ([c06fb3c](https://www.github.com/googleapis/nodejs-firestore/commit/c06fb3cc32f94c9058ad8e484333e688967d5a8f)) + +### [4.9.5](https://www.github.com/googleapis/nodejs-firestore/compare/v4.9.4...v4.9.5) (2021-03-02) + + +### Bug Fixes + +* add typings to v1 and v1beta in firestore.d.ts ([#1433](https://www.github.com/googleapis/nodejs-firestore/issues/1433)) ([47238a9](https://www.github.com/googleapis/nodejs-firestore/commit/47238a926471dee8bdeaa38bcb5f772c7f20349f)) + +### [4.9.4](https://www.github.com/googleapis/nodejs-firestore/compare/v4.9.3...v4.9.4) (2021-02-15) + + +### Bug Fixes + +* update "protobufjs" to be a dependency ([#1425](https://www.github.com/googleapis/nodejs-firestore/issues/1425)) ([d960fbb](https://www.github.com/googleapis/nodejs-firestore/commit/d960fbb5ca20a7eb9594e8c0b2dfabdb0cb473e3)) + +### [4.9.3](https://www.github.com/googleapis/nodejs-firestore/compare/v4.9.2...v4.9.3) (2021-02-09) + + +### Bug Fixes + +* use `Array.isArray` instead of an `instanceof` check ([#1417](https://www.github.com/googleapis/nodejs-firestore/issues/1417)) ([4a8c3cf](https://www.github.com/googleapis/nodejs-firestore/commit/4a8c3cfcaf57ed600da094ab0275a5f32fb1ea30)) + +### [4.9.2](https://www.github.com/googleapis/nodejs-firestore/compare/v4.9.1...v4.9.2) (2021-02-05) + + +### Bug Fixes + +* support byte values in Bundles ([#1395](https://www.github.com/googleapis/nodejs-firestore/issues/1395)) ([8cf53a9](https://www.github.com/googleapis/nodejs-firestore/commit/8cf53a92dc13324562ca1a1e841312e43f5c383e)) + +### [4.9.1](https://www.github.com/googleapis/nodejs-firestore/compare/v4.9.0...v4.9.1) (2021-01-26) + + +### Bug Fixes + +* handle ignoreUndefinedProperties in set(merge: true) ([#1396](https://www.github.com/googleapis/nodejs-firestore/issues/1396)) ([d870c9d](https://www.github.com/googleapis/nodejs-firestore/commit/d870c9de75a2c67ffc48d1205a5929df4c57f3cb)) + +## [4.9.0](https://www.github.com/googleapis/nodejs-firestore/compare/v4.8.1...v4.9.0) (2021-01-25) + + +### Features + +* add support for applying default converter in withConverter() ([#1394](https://www.github.com/googleapis/nodejs-firestore/issues/1394)) ([ab057f7](https://www.github.com/googleapis/nodejs-firestore/commit/ab057f7b362a2929ebffa19e570d3e9cd23bc964)) +* adds UNORDERED_LIST type ([#1382](https://www.github.com/googleapis/nodejs-firestore/issues/1382)) ([5b43e7b](https://www.github.com/googleapis/nodejs-firestore/commit/5b43e7bcb2ea9c014587c84164f9ba8a0ed05397)) +* introduces style enumeration ([#1388](https://www.github.com/googleapis/nodejs-firestore/issues/1388)) ([eb1b4dc](https://www.github.com/googleapis/nodejs-firestore/commit/eb1b4dccf52b09ce395ba2ceabe02e84ee8e4dfd)) + +### [4.8.1](https://www.github.com/googleapis/nodejs-firestore/compare/v4.8.0...v4.8.1) (2020-12-16) + + +### Bug Fixes + +* release clients that received a RST_STREAM error ([#1380](https://www.github.com/googleapis/nodejs-firestore/issues/1380)) ([0296dd6](https://www.github.com/googleapis/nodejs-firestore/commit/0296dd65d135f5b809547c69dec03dcc8f4bd071)) + +## [4.8.0](https://www.github.com/googleapis/nodejs-firestore/compare/v4.7.2...v4.8.0) (2020-12-03) + + +### Features + +* Add support to build Firestore bundles ([#1365](https://www.github.com/googleapis/nodejs-firestore/issues/1365)) ([bae82dd](https://www.github.com/googleapis/nodejs-firestore/commit/bae82dd4438ac03107c221c62dbce8cf6d20a4b1)) + + +### Bug Fixes + +* stop using GRPC channels after RST_STREAM ([#1373](https://www.github.com/googleapis/nodejs-firestore/issues/1373)) ([504bb5f](https://www.github.com/googleapis/nodejs-firestore/commit/504bb5f34159238cd9bed3645591e6c6c810452b)) + +### [4.7.2](https://www.github.com/googleapis/nodejs-firestore/compare/v4.7.1...v4.7.2) (2020-11-25) + + +### Bug Fixes + +* **browser:** check for fetch on window ([#1368](https://www.github.com/googleapis/nodejs-firestore/issues/1368)) ([3cd29d2](https://www.github.com/googleapis/nodejs-firestore/commit/3cd29d22073cff8d0ca072057c63dfe0a2144841)) + +### [4.7.1](https://www.github.com/googleapis/nodejs-firestore/compare/v4.7.0...v4.7.1) (2020-11-10) + + +### Bug Fixes + +* do not modify options object, use defaultScopes ([#1360](https://www.github.com/googleapis/nodejs-firestore/issues/1360)) ([bd40d3a](https://www.github.com/googleapis/nodejs-firestore/commit/bd40d3ae73cfd0a8e2503fca8d0aa28cb3bbcb86)) +* ignore 'undefined' in update() with UpdateMap ([#1363](https://www.github.com/googleapis/nodejs-firestore/issues/1363)) ([9bad804](https://www.github.com/googleapis/nodejs-firestore/commit/9bad804205ab886c1a80351a8e7a7726e3d242ec)) +* remove unneeded async signature from BulkWriter.sendBatch() ([#1361](https://www.github.com/googleapis/nodejs-firestore/issues/1361)) ([b5cf449](https://www.github.com/googleapis/nodejs-firestore/commit/b5cf4499724ff41e626a69f2db66be22167a7223)) + +## [4.7.0](https://www.github.com/googleapis/nodejs-firestore/compare/v4.6.1...v4.7.0) (2020-11-05) + + +### Features + +* add ability to specify custom headers for individual RPC types ([#1355](https://www.github.com/googleapis/nodejs-firestore/issues/1355)) ([0900379](https://www.github.com/googleapis/nodejs-firestore/commit/0900379e9853a8c2c7c36418dce8beb7ce966889)) + +### [4.6.1](https://www.github.com/googleapis/nodejs-firestore/compare/v4.6.0...v4.6.1) (2020-11-03) + + +### Bug Fixes + +* create new batch for writes to the same doc ([#1352](https://www.github.com/googleapis/nodejs-firestore/issues/1352)) ([bd5adc3](https://www.github.com/googleapis/nodejs-firestore/commit/bd5adc35ea1f662ee762ac8b9048556e78a54f35)) + +## [4.6.0](https://www.github.com/googleapis/nodejs-firestore/compare/v4.5.0...v4.6.0) (2020-11-03) + + +### Features + +* add onWriteError() and onWriteResult() handlers to BulkWriter ([#1315](https://www.github.com/googleapis/nodejs-firestore/issues/1315)) ([a173f4d](https://www.github.com/googleapis/nodejs-firestore/commit/a173f4defab7a6e750907fcb86431c56fcb3d4cf)) + + +### Bug Fixes + +* retry transactions that fail with expired transaction IDs ([#1347](https://www.github.com/googleapis/nodejs-firestore/issues/1347)) ([a18ab50](https://www.github.com/googleapis/nodejs-firestore/commit/a18ab50f3304f1154caaaab9768b736bdb3d8442)) + +## [4.5.0](https://www.github.com/googleapis/nodejs-firestore/compare/v4.4.0...v4.5.0) (2020-10-26) + + +### Features + +* add implicit ordering for startAt(DocumentReference) calls ([#1328](https://www.github.com/googleapis/nodejs-firestore/issues/1328)) ([e9afa38](https://www.github.com/googleapis/nodejs-firestore/commit/e9afa38592b3cc324a8d4685244ee4b249eeedfc)) +* add support for Partition API ([#1320](https://www.github.com/googleapis/nodejs-firestore/issues/1320)) ([51961c3](https://www.github.com/googleapis/nodejs-firestore/commit/51961c3b39ff9c532214eb783458f83da98eb485)) + + +### Bug Fixes + +* retry PartitionQuery for INTERNAL and DEADLINE_EXCEEDED ([#1336](https://www.github.com/googleapis/nodejs-firestore/issues/1336)) ([fdf5462](https://www.github.com/googleapis/nodejs-firestore/commit/fdf5462917e322cc04bf47ebc337d5a76a4a8b18)) +* simplify BulkWriter logic ([#1321](https://www.github.com/googleapis/nodejs-firestore/issues/1321)) ([b493baf](https://www.github.com/googleapis/nodejs-firestore/commit/b493baf44e729fa584b29881ef83f7821967a97b)) +* speed up listDocuments pagination ([#1344](https://www.github.com/googleapis/nodejs-firestore/issues/1344)) ([498301d](https://www.github.com/googleapis/nodejs-firestore/commit/498301dc06bdd5a1eccaadd7ffb1b470749488f7)) +* Update getAll example in documentation ([#1326](https://www.github.com/googleapis/nodejs-firestore/issues/1326)) ([721fce0](https://www.github.com/googleapis/nodejs-firestore/commit/721fce02440fde39e8a5c2d379b2254079e15201)) +* update required field to implement NodeJS.Timeout ([#1338](https://www.github.com/googleapis/nodejs-firestore/issues/1338)) ([6b7371b](https://www.github.com/googleapis/nodejs-firestore/commit/6b7371b4511a7cf039f85519a9d4b8be1bff8930)) +* **firestore/v1:** give PartitionQuery retry/timeout config ([#1334](https://www.github.com/googleapis/nodejs-firestore/issues/1334)) ([39a30c2](https://www.github.com/googleapis/nodejs-firestore/commit/39a30c24a54078e53ad9c746ee8ae5a4a9471349)) + +## [4.4.0](https://www.github.com/googleapis/nodejs-firestore/compare/v4.3.0...v4.4.0) (2020-09-29) + + +### Features + +* add starting/max rates to BulkWriterOptions ([#1305](https://www.github.com/googleapis/nodejs-firestore/issues/1305)) ([57dcf1c](https://www.github.com/googleapis/nodejs-firestore/commit/57dcf1c42b406a15ecb960059d67d99a97d42547)) + + +## [4.3.0](https://www.github.com/googleapis/nodejs-firestore/compare/v4.2.0...v4.3.0) (2020-09-22) + + +### Features + +* add support for != and not-in queries ([#1292](https://www.github.com/googleapis/nodejs-firestore/issues/1292)) ([786e52f](https://www.github.com/googleapis/nodejs-firestore/commit/786e52f8c8b7b9c6b84ffc988190470a063d5855)) + + +### Bug Fixes + +* add capacity logging to RateLimiter ([#1287](https://www.github.com/googleapis/nodejs-firestore/issues/1287)) ([befe625](https://www.github.com/googleapis/nodejs-firestore/commit/befe625f35b7c96e9a90399a1ca71a8a049224ad)) +* allow `setLogFunction(null)` ([#1304](https://www.github.com/googleapis/nodejs-firestore/issues/1304)) ([20b1226](https://www.github.com/googleapis/nodejs-firestore/commit/20b122695843bffc106f73c92e112144f0b96070)) +* bulkWriter: writing to the same document does not create a new batch ([#1298](https://www.github.com/googleapis/nodejs-firestore/issues/1298)) ([6243d62](https://www.github.com/googleapis/nodejs-firestore/commit/6243d625481e8f9a852b4a3bf8d77ca9cbca4dd3)) +* change typings for select() to return `Query` ([#1303](https://www.github.com/googleapis/nodejs-firestore/issues/1303)) ([b678857](https://www.github.com/googleapis/nodejs-firestore/commit/b678857afcdf14be5d645d7552e5f4aa4183b037)) +* correct BulkWriter types in firestore.d.ts ([#1284](https://www.github.com/googleapis/nodejs-firestore/issues/1284)) ([382128b](https://www.github.com/googleapis/nodejs-firestore/commit/382128b83de01cc0f88110393a1271b8d768509e)) + +## [4.2.0](https://www.github.com/googleapis/nodejs-firestore/compare/v4.1.2...v4.2.0) (2020-07-31) + + +### Features + +* allow `Settings.host` to be used when `Settings.servicePath` is set ([#1275](https://www.github.com/googleapis/nodejs-firestore/issues/1275)) ([34d6728](https://www.github.com/googleapis/nodejs-firestore/commit/34d672870f9a4673e990176e4453c4202a1386f9)) + +### [4.1.2](https://www.github.com/googleapis/nodejs-firestore/compare/v4.1.1...v4.1.2) (2020-07-24) + + +### Bug Fixes + +* add Firestore.bulkWriter to firestore.d.ts ([#1272](https://www.github.com/googleapis/nodejs-firestore/issues/1272)) ([5e7e627](https://www.github.com/googleapis/nodejs-firestore/commit/5e7e62712ab049ce1adcb26213dd13964939bf65)) + +### [4.1.1](https://www.github.com/googleapis/nodejs-firestore/compare/v4.1.0...v4.1.1) (2020-07-09) + + +### Bug Fixes + +* typeo in nodejs .gitattribute ([#1257](https://www.github.com/googleapis/nodejs-firestore/issues/1257)) ([2664878](https://www.github.com/googleapis/nodejs-firestore/commit/2664878c0f71d83b0d9e5475d31a9daec1a34eaa)) + +## [4.1.0](https://www.github.com/googleapis/nodejs-firestore/compare/v4.0.0...v4.1.0) (2020-07-08) + + +### Features + +* Added `Firestore.bulkWriter()`, which performs large scale writes in parallel. By default, BulkWriter throttles writes according to the "500/50/5" rule and retries writes that fail due to contention. ([#1252](https://www.github.com/googleapis/nodejs-firestore/issues/1252)) ([d0c6c4b](https://www.github.com/googleapis/nodejs-firestore/commit/d0c6c4b116e096a1bb59c89de26cedb8cf5f1224)) + +## [4.0.0](https://www.github.com/googleapis/nodejs-firestore/compare/v3.8.6...v4.0.0) (2020-06-24) + + +### ⚠ BREAKING CHANGES + +* drop Node 8 support (#1006) +* `FirestoreDataConverter.fromFirestore()` is now called with a `QueryDocumentSnapshot` instead of `DocumentData` (#965) + +### Features + +* add support for serialization to BigInt `(via settings({useBigInt: true})` (#1016) +* add support for set() with SetOptions when using `FirestoreDataConverter` (#1087) +* retry CommitRequests that fail with UNAVAILABLE (#1235) + +### Bug Fix +- remove fallback code that periodically invoked CommitRequests inside Transactions on GCF (#1112) +- fixes an error that prevented Firestore from connecting to the Emulator if multiple versions of `@grpc/grpc-js` are installed (#1233) + + +### [3.8.6](https://www.github.com/googleapis/nodejs-firestore/compare/v3.8.5...v3.8.6) (2020-06-19) + + +### Bug Fixes + +* reject all promises with errors ([#1224](https://www.github.com/googleapis/nodejs-firestore/issues/1224)) ([9118521](https://www.github.com/googleapis/nodejs-firestore/commit/9118521a0382fd2d484803a89e590c1bf6d2a3c6)) +* restart onSnapshot() listeners that stop receiving updates ([#1220](https://www.github.com/googleapis/nodejs-firestore/issues/1220)) ([49ca641](https://www.github.com/googleapis/nodejs-firestore/commit/49ca641ca5d813923b3d4efd113bfc5aecd32437)) + +### [3.8.5](https://www.github.com/googleapis/nodejs-firestore/compare/v3.8.4...v3.8.5) (2020-06-10) + + +### Bug Fixes + +* fix flaky BulkWriter test ([#1115](https://www.github.com/googleapis/nodejs-firestore/issues/1115)) ([9a24cc0](https://www.github.com/googleapis/nodejs-firestore/commit/9a24cc0c6ee68c1dee7ec64d89dfa7c88375f88d)) +* retry ABORTED for non-transactional commits ([#1111](https://www.github.com/googleapis/nodejs-firestore/issues/1111)) ([f175236](https://www.github.com/googleapis/nodejs-firestore/commit/f175236bde2f64365f140b14641f848bd4eb34d9)) +* retry Query streams ([#1116](https://www.github.com/googleapis/nodejs-firestore/issues/1116)) ([d7574ea](https://www.github.com/googleapis/nodejs-firestore/commit/d7574ea4ecd807d501243f8435903cfa385bb630)) + +### [3.8.4](https://www.github.com/googleapis/nodejs-firestore/compare/v3.8.3...v3.8.4) (2020-06-01) + + +### Bug Fixes + +* send Authentication header with every emulator request ([#1105](https://www.github.com/googleapis/nodejs-firestore/issues/1105)) ([83f617c](https://www.github.com/googleapis/nodejs-firestore/commit/83f617c753dbcad58eb91be585fd9fcb10480099)) + +### [3.8.3](https://www.github.com/googleapis/nodejs-firestore/compare/v3.8.2...v3.8.3) (2020-05-31) + + +### Bug Fixes + +* return null for 'parent' call on root collection ([#1099](https://www.github.com/googleapis/nodejs-firestore/issues/1099)) ([c5c0b15](https://www.github.com/googleapis/nodejs-firestore/commit/c5c0b157bf32466875ace690216a99371d31b461)) + +### [3.8.2](https://www.github.com/googleapis/nodejs-firestore/compare/v3.8.1...v3.8.2) (2020-05-30) + + +### Bug Fixes + +* authenticate as admin user when ssl:false is set ([#1095](https://www.github.com/googleapis/nodejs-firestore/issues/1095)) ([a178556](https://www.github.com/googleapis/nodejs-firestore/commit/a17855634542bce798f1ffe50d72775647990616)), closes [/github.com/firebase/firebase-js-sdk/issues/3105#issuecomment-635541894](https://www.github.com/googleapis//github.com/firebase/firebase-js-sdk/issues/3105/issues/issuecomment-635541894) + +### [3.8.1](https://www.github.com/googleapis/nodejs-firestore/compare/v3.8.0...v3.8.1) (2020-05-27) + + +### Bug Fixes + +* Add tests to check fields used in whereIn should be equality filters ([#1081](https://www.github.com/googleapis/nodejs-firestore/issues/1081)) ([3153dd2](https://www.github.com/googleapis/nodejs-firestore/commit/3153dd296891a983b3a0e78354df3fe106ad44a2)) +* capture error stacks across async calls ([#1088](https://www.github.com/googleapis/nodejs-firestore/issues/1088)) ([7acdd7e](https://www.github.com/googleapis/nodejs-firestore/commit/7acdd7e9e0877fd6dbb50539a0a3c1537d30904a)) + +## [3.8.0](https://www.github.com/googleapis/nodejs-firestore/compare/v3.7.5...v3.8.0) (2020-05-13) + + +### Features + +* add ignoreUndefinedProperties option ([#1062](https://www.github.com/googleapis/nodejs-firestore/issues/1062)) ([de733c8](https://www.github.com/googleapis/nodejs-firestore/commit/de733c821152a32893e7fccf30cdf96a2f8050eb)) + + +### Bug Fixes + +* prepare sources for BulkWriter ([#1051](https://www.github.com/googleapis/nodejs-firestore/issues/1051)) ([8c52d47](https://www.github.com/googleapis/nodejs-firestore/commit/8c52d475ae486e2998220947a0b0441d4a95ab49)) +* allow running source with ts-node ([#1074](https://www.github.com/googleapis/nodejs-firestore/issues/1074)) ([f66a089](https://www.github.com/googleapis/nodejs-firestore/commit/f66a08978f11915d8662f964867a966ff75f6e96)) +* remove type dependency on Moment ([#1063](https://www.github.com/googleapis/nodejs-firestore/issues/1063)) ([30008b0](https://www.github.com/googleapis/nodejs-firestore/commit/30008b093a9872e34a83209e94de3dca09e89fe7)) + +### [3.7.5](https://www.github.com/googleapis/nodejs-firestore/compare/v3.7.4...v3.7.5) (2020-04-25) + + +### Bug Fixes + +* return errors from Query.stream() ([#1046](https://www.github.com/googleapis/nodejs-firestore/issues/1046)) ([4b65fca](https://www.github.com/googleapis/nodejs-firestore/commit/4b65fca3d7aa9618ff944c02f059d08f39b4cac3)) + +### [3.7.4](https://www.github.com/googleapis/nodejs-firestore/compare/v3.7.3...v3.7.4) (2020-04-09) + + +### Bug Fixes + +* validate nested arrays in FieldValue ([#1003](https://www.github.com/googleapis/nodejs-firestore/issues/1003)) ([3497691](https://www.github.com/googleapis/nodejs-firestore/commit/3497691754d8b3b0b17385c34362f74ab8a84feb)) + +### [3.7.3](https://www.github.com/googleapis/nodejs-firestore/compare/v3.7.2...v3.7.3) (2020-03-31) + + +### Bug Fixes + +* support array of references for IN queries ([#993](https://www.github.com/googleapis/nodejs-firestore/issues/993)) ([a6d8fe0](https://www.github.com/googleapis/nodejs-firestore/commit/a6d8fe061fcfe0fde7a4fa023b2ec454e2adb432)) + +### [3.7.2](https://www.github.com/googleapis/nodejs-firestore/compare/v3.7.1...v3.7.2) (2020-03-25) + + +### Bug Fixes + +* fix flaky contention test ([#979](https://www.github.com/googleapis/nodejs-firestore/issues/979)) ([f294998](https://www.github.com/googleapis/nodejs-firestore/commit/f294998daab77a0a51c81265945e28eec34db186)) +* fix: use Random Number from `crypto` to generate AutoId ([05b3363](https://www.github.com/googleapis/nodejs-firestore/commit/ce6ea390f2fffcbe796ba1c5b040ee02452e287a)) + +### [3.7.1](https://www.github.com/googleapis/nodejs-firestore/compare/v3.7.0...v3.7.1) (2020-03-16) + + +### Bug Fixes + +* support Query.stream() as first client operation ([#971](https://www.github.com/googleapis/nodejs-firestore/issues/971)) ([a48017c](https://www.github.com/googleapis/nodejs-firestore/commit/a48017c16dbf7819ea45ea2577365b52721c2475)) + +## [3.7.0](https://www.github.com/googleapis/nodejs-firestore/compare/v3.6.0...v3.7.0) (2020-03-11) + + +### Features + +* **deps:** update to TypeScript 3.8 ([#962](https://www.github.com/googleapis/nodejs-firestore/issues/962)) ([12982cd](https://www.github.com/googleapis/nodejs-firestore/commit/12982cd9ef6b418b6bc9fa303bb804255b9c906a)) +* add support for Query.limitToLast() ([#954](https://www.github.com/googleapis/nodejs-firestore/issues/954)) ([c89546f](https://www.github.com/googleapis/nodejs-firestore/commit/c89546f5ae83da3845076aeeffcda75f9b208f5c)) + +## [3.6.0](https://www.github.com/googleapis/nodejs-firestore/compare/v3.5.1...v3.6.0) (2020-03-09) + + +### Features + +* base transaction retries on error codes ([#953](https://www.github.com/googleapis/nodejs-firestore/issues/953)) ([4a30820](https://www.github.com/googleapis/nodejs-firestore/commit/4a30820876db2ec925efd0ac04482fe9c6882813)) +* deferred client initialization ([#956](https://www.github.com/googleapis/nodejs-firestore/issues/956)) ([301a7e2](https://www.github.com/googleapis/nodejs-firestore/commit/301a7e2870529fc8b14c91ac08c942dececcc3d6)) +* implement Timestamp.valueOf() ([#947](https://www.github.com/googleapis/nodejs-firestore/issues/947)) ([24a96c6](https://www.github.com/googleapis/nodejs-firestore/commit/24a96c65ecbc4df0fc69b9a7f64e9e508fea89b9)), closes [#944](https://www.github.com/googleapis/nodejs-firestore/issues/944) + +### [3.5.1](https://www.github.com/googleapis/nodejs-firestore/compare/v3.5.0...v3.5.1) (2020-02-19) + + +### Bug Fixes + +* collectionReference.add() validation ([#925](https://www.github.com/googleapis/nodejs-firestore/issues/925)) ([19c2c75](https://www.github.com/googleapis/nodejs-firestore/commit/19c2c75d86c3aab967d21da16598016185ae360b)) +* pass x-goog-request-params header for streaming calls ([#920](https://www.github.com/googleapis/nodejs-firestore/issues/920)) ([cfbe19e](https://www.github.com/googleapis/nodejs-firestore/commit/cfbe19ed4c3cc6bb9ffc7b352de901150b8b9dea)) +* propagate converter in QueryOptions.with() ([#931](https://www.github.com/googleapis/nodejs-firestore/issues/931)) ([e35a098](https://www.github.com/googleapis/nodejs-firestore/commit/e35a098621b872b85a3ab70c6592eba75a929de8)) +* wait for operations to complete before deleting clients ([#915](https://www.github.com/googleapis/nodejs-firestore/issues/915)) ([1e5d63f](https://www.github.com/googleapis/nodejs-firestore/commit/1e5d63fbc39d9c3e6883e79a55e8a26634cd30c5)) + +## [3.5.0](https://www.github.com/googleapis/nodejs-firestore/compare/v3.4.1...v3.5.0) (2020-02-07) + + +### Features + +* add google-gax status to exports ([#912](https://www.github.com/googleapis/nodejs-firestore/issues/912)) ([7d97384](https://www.github.com/googleapis/nodejs-firestore/commit/7d9738456525b99507b8819d86a8634b0a1d04c3)) + + +### Bug Fixes + +* add missing generics on query ([#917](https://www.github.com/googleapis/nodejs-firestore/issues/917)) ([c5b9442](https://www.github.com/googleapis/nodejs-firestore/commit/c5b9442e6620e59e5563ffaf210ad493ec5ed9b2)) +* better parameter naming in path template helpers ([aac02f4](https://www.github.com/googleapis/nodejs-firestore/commit/aac02f463ba13c385a6dc5a4d96e281e0801cc93)) +* retry streaming methods if initial write errored ([#897](https://www.github.com/googleapis/nodejs-firestore/issues/897)) ([2ec0489](https://www.github.com/googleapis/nodejs-firestore/commit/2ec0489127faea88dca95e6dc169efe6e55d330d)) + +### [3.4.1](https://www.github.com/googleapis/nodejs-firestore/compare/v3.4.0...v3.4.1) (2020-01-22) + + +### Bug Fixes + +* do not assume all custom objects have constructors ([#893](https://www.github.com/googleapis/nodejs-firestore/issues/893)) ([f668e8e](https://www.github.com/googleapis/nodejs-firestore/commit/f668e8e4880256223c41c2c3183434e81c7f7945)) + +## [3.4.0](https://www.github.com/googleapis/nodejs-firestore/compare/v3.3.4...v3.4.0) (2020-01-15) + + +### Features + +* support serialization of custom objects ([#828](https://www.github.com/googleapis/nodejs-firestore/issues/828)) ([94ddc89](https://www.github.com/googleapis/nodejs-firestore/commit/94ddc897400cafe5a1ee16f3ad0d285411bdd0b2)) +* support serialization of Moment.js types ([#879](https://www.github.com/googleapis/nodejs-firestore/issues/879)) ([9169fae](https://www.github.com/googleapis/nodejs-firestore/commit/9169fae692d219b5fb42004a4eb82e5a5919f087)) +* allow logging to be disabled ([#880](https://www.github.com/googleapis/nodejs-firestore/issues/880)) ([36d75f6](https://www.github.com/googleapis/nodejs-firestore/commit/36d75f6b75d7ede4656636f1d8bf770eb1cb3a80)) + + +### Bug Fixes + +* don't format log message if logging is disabled ([#874](https://www.github.com/googleapis/nodejs-firestore/issues/874)) ([b7b5fc9](https://www.github.com/googleapis/nodejs-firestore/commit/b7b5fc993d4cece92833c95487efe63320537058)) +* disable non-transactional retries for Code ABORTED ([#881](https://www.github.com/googleapis/nodejs-firestore/issues/881)) ([82273ec](https://www.github.com/googleapis/nodejs-firestore/commit/82273ec0035b2ddae94d8f12791f8a5c55b6560d)) +* manually retry ABORTED reads in transactions ([#883](https://www.github.com/googleapis/nodejs-firestore/issues/883)) ([7562033](https://www.github.com/googleapis/nodejs-firestore/commit/7562033876dc006e77d00b576b2541a7dfd30c66)) +* remove ticks from code comments ([#885](https://www.github.com/googleapis/nodejs-firestore/issues/885)) ([b2740ed](https://www.github.com/googleapis/nodejs-firestore/commit/b2740ed4fb0e7c34fd407e3de4f47f03067171cb)) + +### [3.3.4](https://www.github.com/googleapis/nodejs-firestore/compare/v3.3.3...v3.3.4) (2020-01-12) + + +### Bug Fixes + +* do not release client before retry ([#870](https://www.github.com/googleapis/nodejs-firestore/issues/870)) ([47f7ab5](https://www.github.com/googleapis/nodejs-firestore/commit/47f7ab52f9133064785754ee924d9f8736853eba)) +* proper routing headers ([43472f6](https://www.github.com/googleapis/nodejs-firestore/commit/43472f6bd51a22a5ee27d7fc0f88a9dd97c22336)) +* remove redundant log line ([#868](https://www.github.com/googleapis/nodejs-firestore/issues/868)) ([af3196f](https://www.github.com/googleapis/nodejs-firestore/commit/af3196fe8da2018e0a9842f4f62588ce2c740597)) + +### [3.3.3](https://www.github.com/googleapis/nodejs-firestore/compare/v3.3.2...v3.3.3) (2020-01-08) + + +### Bug Fixes + +* support Objects created with Object.create({}) ([#842](https://www.github.com/googleapis/nodejs-firestore/issues/842)) ([a85f0c3](https://www.github.com/googleapis/nodejs-firestore/commit/a85f0c32eca5d8cf677d621a8ff326623ad5266e)) +* use rejected Promise for terminate() ([#845](https://www.github.com/googleapis/nodejs-firestore/issues/845)) ([f2c4d91](https://www.github.com/googleapis/nodejs-firestore/commit/f2c4d911077c8e5b7713263fc8b2c21bbd50ca11)) + +### [3.3.2](https://www.github.com/googleapis/nodejs-firestore/compare/v3.3.1...v3.3.2) (2020-01-06) + + +### Bug Fixes + +* add quotes to field name to avoid ambiguity ([#860](https://www.github.com/googleapis/nodejs-firestore/issues/860)) ([8caee71](https://www.github.com/googleapis/nodejs-firestore/commit/8caee71f6105e82faf3f6334e69ed5890f977a3a)) + +### [3.3.1](https://www.github.com/googleapis/nodejs-firestore/compare/v3.3.0...v3.3.1) (2020-01-06) + + +### Bug Fixes + +* don't recreate instances when client is idle ([0aa2a8b](https://www.github.com/googleapis/nodejs-firestore/commit/0aa2a8b8d0c76e0cfc6d29c37d143cc9c0b45fec)) + +## [3.3.0](https://www.github.com/googleapis/nodejs-firestore/compare/v3.2.0...v3.3.0) (2020-01-03) + + +### Features + +* add Symbol.asyncInterator to Query.stream() ([#843](https://www.github.com/googleapis/nodejs-firestore/issues/843)) ([68795c4](https://www.github.com/googleapis/nodejs-firestore/commit/68795c43ae9ef6b286650228746c7c16f59347f7)) +* use GAX retry config for streams ([#847](https://www.github.com/googleapis/nodejs-firestore/issues/847)) ([218a4c6](https://www.github.com/googleapis/nodejs-firestore/commit/218a4c65afcc55158aac45b98a4ccb28b88c00a1)) + + +### Bug Fixes + +* increase test timeout ([#846](https://www.github.com/googleapis/nodejs-firestore/issues/846)) ([b94c367](https://www.github.com/googleapis/nodejs-firestore/commit/b94c367e9655f8a6a3553610ebc655877be502ec)) +* retry writes that fail with status code ABORTED ([#854](https://www.github.com/googleapis/nodejs-firestore/issues/854)) ([96f085f](https://www.github.com/googleapis/nodejs-firestore/commit/96f085f3df7c8e6e20dbffb14ebf6ebb533fc036)) + +## [3.2.0](https://www.github.com/googleapis/nodejs-firestore/compare/v3.1.0...v3.2.0) (2019-12-30) + + +### Features + +* allow specifying how many idle GRPC channels to keep ([#837](https://www.github.com/googleapis/nodejs-firestore/issues/837)) ([37e93da](https://www.github.com/googleapis/nodejs-firestore/commit/37e93da689f985b6b0f30645435b12179513eb64)) + + +### Bug Fixes + +* reduce overhead for listDocuments()/listCollections() ([#838](https://www.github.com/googleapis/nodejs-firestore/issues/838)) ([5c870e6](https://www.github.com/googleapis/nodejs-firestore/commit/5c870e615e4774d3d50fc33c17b5da45dcacea4f)) + +## [3.1.0](https://www.github.com/googleapis/nodejs-firestore/compare/v3.0.0...v3.1.0) (2019-12-19) + + +### Features + +* add ability to close channels ([#824](https://www.github.com/googleapis/nodejs-firestore/issues/824)) ([9ef582a](https://www.github.com/googleapis/nodejs-firestore/commit/9ef582aa0508a3d02fb036f741c8c51e5ff4307c)) + + +### Bug Fixes + +* **deps:** update dependency deep-equal to v2 ([#821](https://www.github.com/googleapis/nodejs-firestore/issues/821)) ([25472e1](https://www.github.com/googleapis/nodejs-firestore/commit/25472e11a0e1a4a5e1931b1652d125f9c8cabf11)) + +## [3.0.0](https://www.github.com/googleapis/nodejs-firestore/compare/v2.6.1...v3.0.0) (2019-12-15) + + +### ⚠ BREAKING CHANGES + +* convert Gapic client to TypeScript (#805) +* remove deprecated timestampInSnapshots setting (#808) + +### Features + +* convert Gapic client to TypeScript ([#805](https://www.github.com/googleapis/nodejs-firestore/issues/805)) ([5000b2d](https://www.github.com/googleapis/nodejs-firestore/commit/5000b2d4b5c528b66c5a71db343c0e4163d5d8f7)) +* remove deprecated timestampInSnapshots setting ([#808](https://www.github.com/googleapis/nodejs-firestore/issues/808)) ([f37fffc](https://www.github.com/googleapis/nodejs-firestore/commit/f37fffc44fb1ddc8177bd24dfb44d830221e2479)) + + +### Bug Fixes + +* close GRPC channel when we dispose of clients ([#779](https://www.github.com/googleapis/nodejs-firestore/issues/779)) ([22ef0d0](https://www.github.com/googleapis/nodejs-firestore/commit/22ef0d0229569f0d97ff908b5866264a8de2ca78)) + +### [2.6.1](https://www.github.com/googleapis/nodejs-firestore/compare/v2.6.0...v2.6.1) (2019-12-05) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([0d4e558](https://www.github.com/googleapis/nodejs-firestore/commit/0d4e558be4111b3524aa3b855b14e63cb486d2c8)) +* **docs:** snippets are now replaced in jsdoc comments ([#795](https://www.github.com/googleapis/nodejs-firestore/issues/795)) ([396bebb](https://www.github.com/googleapis/nodejs-firestore/commit/396bebbe21b4df16b3017d144fd9e505eb99feda)) + +## [2.6.0](https://www.github.com/googleapis/nodejs-firestore/compare/v2.5.0...v2.6.0) (2019-11-01) + + +### Features + +* add IN queries support ([#715](https://www.github.com/googleapis/nodejs-firestore/issues/715)) ([00bdf8f](https://www.github.com/googleapis/nodejs-firestore/commit/00bdf8ff81f658c4534adea8d2010a1f68195f45)) + +## [2.5.0](https://www.github.com/googleapis/nodejs-firestore/compare/v2.4.0...v2.5.0) (2019-10-22) + + +### Features + +* introduces ARRAY_CONTAINS_ANY and IN to operator enum ([2c8869d](https://www.github.com/googleapis/nodejs-firestore/commit/2c8869d23ad1aef024273b640579624cde97849f)) + + +### Bug Fixes + +* **deps:** bump google-gax to 1.7.5 ([#786](https://www.github.com/googleapis/nodejs-firestore/issues/786)) ([e5763ba](https://www.github.com/googleapis/nodejs-firestore/commit/e5763baadf7cc424620913a09ca0ed6af4a0971a)) + +## [2.4.0](https://www.github.com/googleapis/nodejs-firestore/compare/v2.3.0...v2.4.0) (2019-10-03) + + +### Bug Fixes + +* provide custom error for FieldValue subclasses ([#771](https://www.github.com/googleapis/nodejs-firestore/issues/771)) ([29c3e9b](https://www.github.com/googleapis/nodejs-firestore/commit/29c3e9b)) +* use compatible version of google-gax ([b0c89c5](https://www.github.com/googleapis/nodejs-firestore/commit/b0c89c5)) + + +### Features + +* ability to specify the Collection Group query scope in the V1 Admin API ([#762](https://www.github.com/googleapis/nodejs-firestore/issues/762)) ([b16cd40](https://www.github.com/googleapis/nodejs-firestore/commit/b16cd40)) + +## [2.3.0](https://www.github.com/googleapis/nodejs-firestore/compare/v2.2.9...v2.3.0) (2019-09-09) + + +### Features + +* load protos from JSON, grpc-fallback support ([#749](https://www.github.com/googleapis/nodejs-firestore/issues/749)) ([6cb9d68](https://www.github.com/googleapis/nodejs-firestore/commit/6cb9d68)) + +### [2.2.9](https://www.github.com/googleapis/nodejs-firestore/compare/v2.2.8...v2.2.9) (2019-08-30) + + +### Bug Fixes + +* retrying 13 INTERNAL RPC errors ([#742](https://www.github.com/googleapis/nodejs-firestore/issues/742)) ([431edcb](https://www.github.com/googleapis/nodejs-firestore/commit/431edcb)) + +### [2.2.8](https://www.github.com/googleapis/nodejs-firestore/compare/v2.2.7...v2.2.8) (2019-08-22) + + +### Bug Fixes + +* serialization does not work with null objects ([#736](https://www.github.com/googleapis/nodejs-firestore/issues/736)) ([870d6a7](https://www.github.com/googleapis/nodejs-firestore/commit/870d6a7)) + +### [2.2.7](https://www.github.com/googleapis/nodejs-firestore/compare/v2.2.6...v2.2.7) (2019-08-16) + + +### Bug Fixes + +* **deps:** use the latest extend ([#728](https://www.github.com/googleapis/nodejs-firestore/issues/728)) ([425bf3d](https://www.github.com/googleapis/nodejs-firestore/commit/425bf3d)) +* add logging to client pool ([#733](https://www.github.com/googleapis/nodejs-firestore/issues/733)) ([a4efa09](https://www.github.com/googleapis/nodejs-firestore/commit/a4efa09)) + +### [2.2.6](https://www.github.com/googleapis/nodejs-firestore/compare/v2.2.5...v2.2.6) (2019-08-02) + + +### Bug Fixes + +* allow calls with no request, add JSON proto ([#725](https://www.github.com/googleapis/nodejs-firestore/issues/725)) ([8b0624b](https://www.github.com/googleapis/nodejs-firestore/commit/8b0624b)) + +### [2.2.5](https://www.github.com/googleapis/nodejs-firestore/compare/v2.2.4...v2.2.5) (2019-08-02) + + +### Bug Fixes + +* Better error for Collection Group Queries with documentId() cursors ([#720](https://www.github.com/googleapis/nodejs-firestore/issues/720)) ([169286d](https://www.github.com/googleapis/nodejs-firestore/commit/169286d)) + +### [2.2.4](https://www.github.com/googleapis/nodejs-firestore/compare/v2.2.3...v2.2.4) (2019-07-08) + + +### Bug Fixes + +* Don't re-open streams on 'error' and 'end' ([#713](https://www.github.com/googleapis/nodejs-firestore/issues/713)) ([104a965](https://www.github.com/googleapis/nodejs-firestore/commit/104a965)) + +### [2.2.3](https://www.github.com/googleapis/nodejs-firestore/compare/v2.2.2...v2.2.3) (2019-06-26) + + +### Bug Fixes + +* **docs:** link to reference docs section on googleapis.dev ([#701](https://www.github.com/googleapis/nodejs-firestore/issues/701)) ([d7c89a8](https://www.github.com/googleapis/nodejs-firestore/commit/d7c89a8)) +* Relax validation of FIRESTORE_EMULATOR_HOST in settings() ([#703](https://www.github.com/googleapis/nodejs-firestore/issues/703)) ([daff9de](https://www.github.com/googleapis/nodejs-firestore/commit/daff9de)) + +### [2.2.2](https://www.github.com/googleapis/nodejs-firestore/compare/v2.2.1...v2.2.2) (2019-06-25) + + +### Bug Fixes + +* Support non-ISO-8859-1 Collection Names in Queries ([fc6f839](https://www.github.com/googleapis/nodejs-firestore/commit/fc6f839)) +* Unset servicePath when FIRESTORE_EMULATOR_HOST is set ([#696](https://www.github.com/googleapis/nodejs-firestore/issues/696)) ([5a19931](https://www.github.com/googleapis/nodejs-firestore/commit/5a19931)) +* Use new stream rather than pipe ([#700](https://www.github.com/googleapis/nodejs-firestore/issues/700)) ([0370e03](https://www.github.com/googleapis/nodejs-firestore/commit/0370e03)) + +### [2.2.1](https://www.github.com/googleapis/nodejs-firestore/compare/v2.2.0...v2.2.1) (2019-06-14) + + +### Bug Fixes + +* **docs:** move to new client docs URL ([#689](https://www.github.com/googleapis/nodejs-firestore/issues/689)) ([58acc46](https://www.github.com/googleapis/nodejs-firestore/commit/58acc46)) + +## [2.2.0](https://www.github.com/googleapis/nodejs-firestore/compare/v2.1.1...v2.2.0) (2019-06-06) + + +### Bug Fixes + +* Split settings.host into servicePath and port ([#684](https://www.github.com/googleapis/nodejs-firestore/issues/684)) ([b2cbca5](https://www.github.com/googleapis/nodejs-firestore/commit/b2cbca5)) +* Store large numbers as doubles ([#683](https://www.github.com/googleapis/nodejs-firestore/issues/683)) ([607b3c0](https://www.github.com/googleapis/nodejs-firestore/commit/607b3c0)) + + +### Features + +* support apiEndpoint override in client constructor ([368bc5c](https://www.github.com/googleapis/nodejs-firestore/commit/368bc5c)) +* Support host, ssl and FIRESTORE_EMULATOR_HOST for endpoint configuration ([#680](https://www.github.com/googleapis/nodejs-firestore/issues/680)) ([d15f29d](https://www.github.com/googleapis/nodejs-firestore/commit/d15f29d)) + +## [2.1.1](https://www.github.com/googleapis/nodejs-firestore/compare/v2.1.0...v2.1.1) (2019-05-30) + + +### Dependencies +- deps: Pin @gprc/grpc-js to 0.4.0 ([#668](https://github.com/googleapis/nodejs-firestore/pull/668)) + + + ### Internal / Testing Changes +- build: remove verbose logging from test scripts ([#665](https://github.com/googleapis/nodejs-firestore/pull/665)) +- build: ignore proto files in test coverage ([#664](https://github.com/googleapis/nodejs-firestore/pull/664)) + +## [2.1.0](https://www.github.com/googleapis/nodejs-firestore/compare/v2.0.0...v2.1.0) (2019-05-28) + + +### Bug Fixes + +* Add overloads for doc() and doc(id:string) ([#662](https://www.github.com/googleapis/nodejs-firestore/issues/662)) ([cb189e9](https://www.github.com/googleapis/nodejs-firestore/commit/cb189e9)) +* retry on abort and limit retry count to 10 ([#655](https://www.github.com/googleapis/nodejs-firestore/issues/655)) ([9e97656](https://www.github.com/googleapis/nodejs-firestore/commit/9e97656)) + + +### Features + +* Support listDocuments()/listCollections() via the Firestore Emulator ([#654](https://www.github.com/googleapis/nodejs-firestore/issues/654)) ([eaf5a4e](https://www.github.com/googleapis/nodejs-firestore/commit/eaf5a4e)) + +## [2.0.0](https://www.github.com/googleapis/nodejs-firestore/compare/v1.3.0...v2.0.0) (2019-05-20) + + +### ⚠ BREAKING CHANGES + +* library now requires Node >= 8.13.0 +* **deprecation:** remove legacy support for array arguments (#625) +* **deprecation:** remove deprecated getCollections() (#624) +* upgrade engines field to >=8.10.0 (#608) + +### Bug Fixes + +* **deps:** update dependency google-gax to ^0.26.0 ([#606](https://www.github.com/googleapis/nodejs-firestore/issues/606)) ([a637a68](https://www.github.com/googleapis/nodejs-firestore/commit/a637a68)) +* Fix client pooling for long-lived listens ([#614](https://www.github.com/googleapis/nodejs-firestore/issues/614)) ([479bc9c](https://www.github.com/googleapis/nodejs-firestore/commit/479bc9c)), closes [firebase/firebase-admin-node#499](https://www.github.com/googleapis/nodejs-firestore/issues/499) [#256](https://www.github.com/googleapis/nodejs-firestore/issues/256) +* **deps:** update dependency google-gax to v1 ([#615](https://www.github.com/googleapis/nodejs-firestore/issues/615)) ([687a353](https://www.github.com/googleapis/nodejs-firestore/commit/687a353)) +* run the generator ([#616](https://www.github.com/googleapis/nodejs-firestore/issues/616)) ([92b0add](https://www.github.com/googleapis/nodejs-firestore/commit/92b0add)) +* **docs:** revert jsdoc and pin to 3.5.5 ([#627](https://www.github.com/googleapis/nodejs-firestore/issues/627)) ([e22f9c6](https://www.github.com/googleapis/nodejs-firestore/commit/e22f9c6)) +* Support more than 100 long-lived streams ([#623](https://www.github.com/googleapis/nodejs-firestore/issues/623)) ([9474e3f](https://www.github.com/googleapis/nodejs-firestore/commit/9474e3f)) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#608](https://www.github.com/googleapis/nodejs-firestore/issues/608)) ([32485f4](https://www.github.com/googleapis/nodejs-firestore/commit/32485f4)) +* upgrade engines field to >=8.13.0 ([#636](https://www.github.com/googleapis/nodejs-firestore/issues/636)) ([a5db7d8](https://www.github.com/googleapis/nodejs-firestore/commit/a5db7d8)) + + +### Code Refactoring + +* **deprecation:** remove deprecated getCollections() ([#624](https://www.github.com/googleapis/nodejs-firestore/issues/624)) ([43ac9c6](https://www.github.com/googleapis/nodejs-firestore/commit/43ac9c6)) +* **deprecation:** remove legacy support for array arguments ([#625](https://www.github.com/googleapis/nodejs-firestore/issues/625)) ([54dd405](https://www.github.com/googleapis/nodejs-firestore/commit/54dd405)) + +## v1.3.0 + +04-26-2019 16:54 PDT + +### New Features +- feature: Adding CollectionGroup queries ([#578](https://github.com/googleapis/nodejs-firestore/pull/578))([#595](https://github.com/googleapis/nodejs-firestore/pull/595)) + +### Dependencies +- chore(deps): update dependency nyc to v14 ([#600](https://github.com/googleapis/nodejs-firestore/pull/600)) +- chore(deps): update dependency typescript to ~3.4.0 +- docs: add .readme-metadata.json and generate new README.md + +### Documentation +- docs: Add example for Precondition ([#601](https://github.com/googleapis/nodejs-firestore/pull/601)) + +## v1.2.0 + +03-21-2019 14:17 PDT + +### New Features +- feature: Release the V1 Admin API ([#590](https://github.com/googleapis/nodejs-firestore/pull/590)) + The Firestore Node SDK now exposes the Firestore Admin API (via `v1.FirebaseAdminClient()`). + +### Implementation Changes +- deps/refactor: Removing @google-cloud/projectify ([#564](https://github.com/googleapis/nodejs-firestore/pull/564)) + +### Dependencies +- chore(deps): update dependency hard-rejection to v2 + +### Documentation +- fix(docs): add namespaces so docs are generated ([#591](https://github.com/googleapis/nodejs-firestore/pull/591)) +- docs: fix typo in doc strings ([#585](https://github.com/googleapis/nodejs-firestore/pull/585)) + +### Internal / Testing Changes +- chore: publish to npm using wombat ([#586](https://github.com/googleapis/nodejs-firestore/pull/586)) +- build: use per-repo publish token ([#582](https://github.com/googleapis/nodejs-firestore/pull/582)) +- refactor: update json import paths ([#580](https://github.com/googleapis/nodejs-firestore/pull/580)) + +## v1.1.0 + +03-10-2019 20:09 PDT + +### New Features +- feature: Added `FieldValue.increment()`, which can be used in `create()`, `update()` and `set(..., {merge:true})` to + increment or decrement numeric field values safely without transactions ([#444](https://github.com/googleapis/nodejs-firestore/pull/444)) + +### Implementation Changes +- fix: Allow async functions ([#576](https://github.com/googleapis/nodejs-firestore/pull/576)) +- fix: Don't call stream.end() on Watch ended by server ([#565](https://github.com/googleapis/nodejs-firestore/pull/565)) + +### Internal / Testing Changes +- refactor: async/await to test/order.ts ([#566](https://github.com/googleapis/nodejs-firestore/pull/566)) +- build: Add docuploader credentials to node publish jobs ([#572](https://github.com/googleapis/nodejs-firestore/pull/572)) +- build: update release config ([#570](https://github.com/googleapis/nodejs-firestore/pull/570)) +- build: use node10 to run samples-test, system-test etc ([#571](https://github.com/googleapis/nodejs-firestore/pull/571)) + +## v1.0.2 + +03-04-2019 13:32 PST + +### Implementation Changes + +- fix: throw on invalid credentials ([#548](https://github.com/googleapis/nodejs-firestore/pull/548)) + +### Dependencies + +- fix(deps): update dependency google-gax to ^0.25.0 ([#535](https://github.com/googleapis/nodejs-firestore/pull/535)) +- chore(deps): update dependency mocha to v6 +- chore(deps): update dependency duplexify to v4 ([#539](https://github.com/googleapis/nodejs-firestore/pull/539)) + +### Documentation + +- docs: update comments on protos ([#559](https://github.com/googleapis/nodejs-firestore/pull/559)) +- docs: update API doc comments ([#557](https://github.com/googleapis/nodejs-firestore/pull/557)) +- docs: update links in contrib guide ([#550](https://github.com/googleapis/nodejs-firestore/pull/550)) +- docs: add lint/fix example to contributing guide ([#541](https://github.com/googleapis/nodejs-firestore/pull/541)) +- docs: fix example comments ([#540](https://github.com/googleapis/nodejs-firestore/pull/540)) +- doc: show GA message in README.md ([#536](https://github.com/googleapis/nodejs-firestore/pull/536)) +- Add note about Datastore mode ([#552](https://github.com/googleapis/nodejs-firestore/pull/552)) +- chore: move CONTRIBUTING.md to root ([#543](https://github.com/googleapis/nodejs-firestore/pull/543)) +- docs: update contributing path in README ([#544](https://github.com/googleapis/nodejs-firestore/pull/544)) + +### Internal / Testing Changes + +- refactor(typescript): enable noImplicitAny ([#553](https://github.com/googleapis/nodejs-firestore/pull/553)) +- chore: update array types ([#555](https://github.com/googleapis/nodejs-firestore/pull/555)) +- Finish TypeScript Migration ([#512](https://github.com/googleapis/nodejs-firestore/pull/512)) +- refactor: improve generated code style. ([#538](https://github.com/googleapis/nodejs-firestore/pull/538)) +- Remove unhandled Promise rejection warning ([#556](https://github.com/googleapis/nodejs-firestore/pull/556)) +- build: use linkinator for docs test ([#549](https://github.com/googleapis/nodejs-firestore/pull/549)) +- build: create docs test npm scripts ([#547](https://github.com/googleapis/nodejs-firestore/pull/547)) +- build: test using @grpc/grpc-js in CI ([#546](https://github.com/googleapis/nodejs-firestore/pull/546)) + +## v1.0.1 + +01-29-2019 14:02 PST + +# Documentation + +- doc: update README.md to show this library as GA ([#532](https://github.com/googleapis/nodejs-firestore/pull/532)) +- fix(samples): constructor doesn't need project or cred options ([#533](https://github.com/googleapis/nodejs-firestore/pull/533)) + +## v1.0.0 + +01-29-2019 12:12 PST + +This is the Firestore Node.js Client Library GA release. + +## v0.21.0 + +01-25-2019 12:21 PST + +This release brings in google-gax update to 0.24.0 which had its dependency google-auth-library updated to 3.0.0^ that swaps out axios in favour of gaxios and addresses an issue using the library behind a proxy (https://github.com/googleapis/nodejs-firestore/issues/493). + +### Dependencies +- chore(deps): update dependency ts-node to v8 ([#526](https://github.com/googleapis/nodejs-firestore/pull/526)) +- fix(deps): update dependency google-gax to ^0.24.0 ([#529](https://github.com/googleapis/nodejs-firestore/pull/529)) + +### Documentation +- build: ignore googleapis.com in doc link check ([#527](https://github.com/googleapis/nodejs-firestore/pull/527)) +- docs: fix import links in the jsdocs ([#524](https://github.com/googleapis/nodejs-firestore/pull/524)) + +### Internal / Testing Changes +- chore: update year in the license headers. ([#523](https://github.com/googleapis/nodejs-firestore/pull/523)) + +## v0.20.0 + +01-16-2019 13:14 PST + +#### BREAKING: The `timestampsInSnapshots` default has changed to true. +The `timestampsInSnapshots` setting is now enabled by default so timestamp +fields read from a `DocumentSnapshot` will be returned as `Timestamp` objects +instead of `Date`. Any code expecting to receive a `Date` object must be +updated. + +#### DEPRECATED: `Firestore.v1beta1` replaced by `Firestore.v1` +If you are currently using `Firestore.v1beta1.FirestoreClient`, you must switch +to `Firestore.v1.FirestoreClient`. No other changes should be required as the +API is 100% identical. + +### Bug Fixes +- fix: getAll function signature to allow array destructuring ([#515](https://github.com/googleapis/nodejs-firestore/pull/515)) +- fix: update grpc retry config ([#464](https://github.com/googleapis/nodejs-firestore/pull/464)) + +### New Features +- feat: update to v1 protos ([#516](https://github.com/googleapis/nodejs-firestore/pull/516)) +- feat: add additional field transform types ([#521](https://github.com/googleapis/nodejs-firestore/pull/521)) + +### Dependencies +- fix(deps): update dependency google-gax to ^0.23.0 ([#518](https://github.com/googleapis/nodejs-firestore/pull/518)) + +### Documentation +- fix(docs): remove unused long running operations types +- docs: elaborate on QuerySnapshot.forEach ([#480](https://github.com/googleapis/nodejs-firestore/pull/480)) +- docs: update doc writetime ([#475](https://github.com/googleapis/nodejs-firestore/pull/475)) +- docs: Fix example for writeTime ([#474](https://github.com/googleapis/nodejs-firestore/pull/474)) +- chore: update license file ([#473](https://github.com/googleapis/nodejs-firestore/pull/473)) +- docs: update readme badges ([#470](https://github.com/googleapis/nodejs-firestore/pull/470)) + +### Internal / Testing Changes +- build: check broken links in generated docs ([#511](https://github.com/googleapis/nodejs-firestore/pull/511)) +- chore(build): inject yoshi automation key ([#492](https://github.com/googleapis/nodejs-firestore/pull/492)) +- chore: update nyc and eslint configs ([#491](https://github.com/googleapis/nodejs-firestore/pull/491)) +- chore: fix publish.sh permission +x ([#489](https://github.com/googleapis/nodejs-firestore/pull/489)) +- fix(build): fix Kokoro release script ([#488](https://github.com/googleapis/nodejs-firestore/pull/488)) +- build: add Kokoro configs for autorelease ([#487](https://github.com/googleapis/nodejs-firestore/pull/487)) +- chore: add synth.metadata ([#485](https://github.com/googleapis/nodejs-firestore/pull/485)) +- chore: always nyc report before calling codecov ([#482](https://github.com/googleapis/nodejs-firestore/pull/482)) +- chore: nyc ignore build/test by default ([#479](https://github.com/googleapis/nodejs-firestore/pull/479)) +- chore(build): update the prettier config ([#476](https://github.com/googleapis/nodejs-firestore/pull/476)) +- chore(deps): update dependency typescript to ~3.2.0 ([#467](https://github.com/googleapis/nodejs-firestore/pull/467)) +- fix(build): fix system key decryption ([#468](https://github.com/googleapis/nodejs-firestore/pull/468)) +- Adding array-contains to error message ([#465](https://github.com/googleapis/nodejs-firestore/pull/465)) + +## v0.17.0 + +### Implementation Changes +- Regenerate library with synth.py customizations ([#345](https://github.com/googleapis/nodejs-firestore/pull/345)) + - contains some documentation and internal timeout changes +- Converting backoff.js to TypeScript ([#328](https://github.com/googleapis/nodejs-firestore/pull/328)) +- Making .dotChanges a method ([#324](https://github.com/googleapis/nodejs-firestore/pull/324)) + +### Dependencies +- chore(deps): update dependency nyc to v13 ([#329](https://github.com/googleapis/nodejs-firestore/pull/329)) +- fix(deps): update dependency google-gax to ^0.19.0 ([#325](https://github.com/googleapis/nodejs-firestore/pull/325)) + +### Documentation +- Fix DocumentReference.get() docs ([#332](https://github.com/googleapis/nodejs-firestore/pull/332)) + +### Internal / Testing Changes +- Retry npm install in CI ([#341](https://github.com/googleapis/nodejs-firestore/pull/341)) +- make synth.py generate library to ./dev ([#337](https://github.com/googleapis/nodejs-firestore/pull/337)) +- Revert "Re-generate library using /synth.py ([#331](https://github.com/googleapis/nodejs-firestore/pull/331))" ([#334](https://github.com/googleapis/nodejs-firestore/pull/334)) +- Re-generate library using /synth.py ([#331](https://github.com/googleapis/nodejs-firestore/pull/331)) diff --git a/handwritten/firestore/CODE_OF_CONDUCT.md b/handwritten/firestore/CODE_OF_CONDUCT.md new file mode 100644 index 00000000000..2add2547a81 --- /dev/null +++ b/handwritten/firestore/CODE_OF_CONDUCT.md @@ -0,0 +1,94 @@ + +# Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of +experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, or to ban temporarily or permanently any +contributor for other behaviors that they deem inappropriate, threatening, +offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +This Code of Conduct also applies outside the project spaces when the Project +Steward has a reasonable belief that an individual's behavior may have a +negative impact on the project or its community. + +## Conflict Resolution + +We do not believe that all conflict is bad; healthy debate and disagreement +often yield positive results. However, it is never okay to be disrespectful or +to engage in behavior that violates the project’s code of conduct. + +If you see someone violating the code of conduct, you are encouraged to address +the behavior directly with those involved. Many issues can be resolved quickly +and easily, and this gives people more control over the outcome of their +dispute. If you are unable to resolve the matter for any reason, or if the +behavior is threatening or harassing, report it. We are dedicated to providing +an environment where participants feel welcome and safe. + +Reports should be directed to *googleapis-stewards@google.com*, the +Project Steward(s) for *Google Cloud Client Libraries*. It is the Project Steward’s duty to +receive and address reported violations of the code of conduct. They will then +work with a committee consisting of representatives from the Open Source +Programs Office and the Google Open Source Strategy team. If for any reason you +are uncomfortable reaching out to the Project Steward, please email +opensource@google.com. + +We will investigate every complaint, but you may not receive a direct response. +We will use our discretion in determining when and how to follow up on reported +incidents, which may range from not taking action to permanent expulsion from +the project and project-sponsored spaces. We will notify the accused of the +report and provide them an opportunity to discuss it before any action is taken. +The identity of the reporter will be omitted from the details of the report +supplied to the accused. In potentially harmful situations, such as ongoing +harassment or threats to anyone's safety, we may take action without notice. + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 1.4, +available at +https://www.contributor-covenant.org/version/1/4/code-of-conduct.html \ No newline at end of file diff --git a/handwritten/firestore/CONTRIBUTING.md b/handwritten/firestore/CONTRIBUTING.md new file mode 100644 index 00000000000..29f37109686 --- /dev/null +++ b/handwritten/firestore/CONTRIBUTING.md @@ -0,0 +1,75 @@ +# How to become a contributor and submit your own code + +**Table of contents** + +* [Contributor License Agreements](#contributor-license-agreements) +* [Contributing a patch](#contributing-a-patch) +* [Running the tests](#running-the-tests) +* [Releasing the library](#releasing-the-library) + +## Contributor License Agreements + +We'd love to accept your sample apps and patches! Before we can take them, we +have to jump a couple of legal hurdles. + +Please fill out either the individual or corporate Contributor License Agreement +(CLA). + + * If you are an individual writing original source code and you're sure you + own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). + * If you work for a company that wants to allow you to contribute your work, + then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). + +Follow either of the two links above to access the appropriate CLA and +instructions for how to sign and return it. Once we receive it, we'll be able to +accept your pull requests. + +## Contributing A Patch + +1. Submit an issue describing your proposed change to the repo in question. +1. The repo owner will respond to your issue promptly. +1. If your proposed change is accepted, and you haven't already done so, sign a + Contributor License Agreement (see details above). +1. Fork the desired repo, develop and test your code changes. +1. Ensure that your code adheres to the existing style in the code to which + you are contributing. +1. Ensure that your code has an appropriate set of tests which all pass. +1. Title your pull request following [Conventional Commits](https://www.conventionalcommits.org/) styling. +1. Submit a pull request. + +### Before you begin + +1. [Select or create a Cloud Platform project][projects]. +1. [Enable the Cloud Firestore API][enable_api]. +1. [Set up authentication with a service account][auth] so you can access the + API from your local workstation. + + +## Running the tests + +1. [Prepare your environment for Node.js setup][setup]. + +1. Install dependencies: + + npm install + +1. Run the tests: + + # Run unit tests. + npm test + + # Run sample integration tests. + npm run samples-test + + # Run all system tests. + npm run system-test + +1. Lint (and maybe fix) any changes: + + npm run fix + +[setup]: https://cloud.google.com/nodejs/docs/setup +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing +[enable_api]: https://console.cloud.google.com/flows/enableapi?apiid=firestore.googleapis.com +[auth]: https://cloud.google.com/docs/authentication/getting-started \ No newline at end of file diff --git a/handwritten/firestore/LICENSE b/handwritten/firestore/LICENSE new file mode 100644 index 00000000000..d6456956733 --- /dev/null +++ b/handwritten/firestore/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/handwritten/firestore/README.md b/handwritten/firestore/README.md new file mode 100644 index 00000000000..71227001057 --- /dev/null +++ b/handwritten/firestore/README.md @@ -0,0 +1,235 @@ +[//]: # "This README.md file is auto-generated, all changes to this file will be lost." +[//]: # "To regenerate it, use `python -m synthtool`." +Google Cloud Platform logo + +# [Cloud Firestore: Node.js Client](https://github.com/googleapis/nodejs-firestore) + +[![release level](https://img.shields.io/badge/release%20level-stable-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages) +[![npm version](https://img.shields.io/npm/v/@google-cloud/firestore.svg)](https://www.npmjs.com/package/@google-cloud/firestore) + + + + +This is the Node.js Server SDK for [Google Cloud Firestore](https://firebase.google.com/docs/firestore/). Google Cloud Firestore is a NoSQL document database built for automatic scaling, high performance, and ease of application development. + +This Cloud Firestore Server SDK uses Google’s Cloud Identity and Access Management for authentication and should only be used in trusted environments. Your Cloud Identity credentials allow you bypass all access restrictions and provide read and write access to all data in your Cloud Firestore project. + +The Cloud Firestore Server SDKs are designed to manage the full set of data in your Cloud Firestore project and work best with reliable network connectivity. Data operations performed via these SDKs directly access the Cloud Firestore backend and all document reads and writes are optimized for high throughput. + +Applications that use Google's Server SDKs should not be used in end-user environments, such as on phones or on publicly hosted websites. If you are developing a Web or Node.js application that accesses Cloud Firestore on behalf of end users, use the firebase Client SDK. + +**Note:** This Cloud Firestore Server SDK does not support Firestore databases created in [Datastore mode](https://cloud.google.com/datastore/docs/firestore-or-datastore#in_datastore_mode). To access these databases, use the [Datastore SDK](https://www.npmjs.com/package/@google-cloud/datastore). + + +A comprehensive list of changes in each version may be found in +[the CHANGELOG](https://github.com/googleapis/nodejs-firestore/blob/main/CHANGELOG.md). + +* [Cloud Firestore Node.js Client API Reference][client-docs] +* [Cloud Firestore Documentation][product-docs] +* [github.com/googleapis/nodejs-firestore](https://github.com/googleapis/nodejs-firestore) + +Read more about the client libraries for Cloud APIs, including the older +Google APIs Client Libraries, in [Client Libraries Explained][explained]. + +[explained]: https://cloud.google.com/apis/docs/client-libraries-explained + +**Table of contents:** + + +* [Quickstart](#quickstart) + * [Before you begin](#before-you-begin) + * [Installing the client library](#installing-the-client-library) + * [Using the client library](#using-the-client-library) +* [Samples](#samples) +* [Versioning](#versioning) +* [Contributing](#contributing) +* [License](#license) + +## Quickstart + +### Before you begin + +1. [Select or create a Cloud Platform project][projects]. +1. [Enable the Cloud Firestore API][enable_api]. +1. [Set up authentication][auth] so you can access the + API from your local workstation. + +### Installing the client library + +```bash +npm install @google-cloud/firestore +``` + + +### Using the client library + +```javascript +const {Firestore} = require('@google-cloud/firestore'); + +// Create a new client +const firestore = new Firestore(); + +async function quickstart() { + // Obtain a document reference. + const document = firestore.doc('posts/intro-to-firestore'); + + // Enter new data into the document. + await document.set({ + title: 'Welcome to Firestore', + body: 'Hello World', + }); + console.log('Entered new data into the document'); + + // Update an existing document. + await document.update({ + body: 'My first Firestore app', + }); + console.log('Updated an existing document'); + + // Read the document. + const doc = await document.get(); + console.log('Read the document'); + + // Delete the document. + await document.delete(); + console.log('Deleted the document'); +} +quickstart(); + +``` + +### Using the client library with Pipelines + +```javascript + +const {Firestore} = require('@google-cloud/firestore'); + +// Require/import Pipelines from '@google-cloud/firestore/pipelines' +const {field} = require('@google-cloud/firestore/pipelines'); + +// Create a new client +const firestore = new Firestore({ + projectId: 'firestore-sdk-nightly', + databaseId: 'enterprise' +}); + +async function pipelinesQuickstart() { + // Obtain a collection reference. + const collection = firestore.collection('books'); + + // Enter new documents into the document. + await collection.add({ + "title": "Whispers of the Cobalt Sea", + "price": 12.99, + "author": "Elara Vance", + "yearPublished": 2023 + }); + await collection.add({ + "title": "The Antigravity Cat's Guide to Napping", + "price": 24.50, + "author": "Mittens the IV", + "yearPublished": 2026 + }); + console.log('Entered new documents into the collection.'); + + // Define a Pipeline query that selects books published this century, + // orders them by price, and computes a discounted price (20% off). + const pipeline = firestore.pipeline().collection('books') + .where(field('yearPublished').greaterThanOrEqual(2000)) + .sort(field('price').ascending()) + .select('title', 'author', field('price').multiply(0.8).as('discountedPrice')); + + // Execute the pipeline + const pipelineSnapshot = await pipeline.execute(); + console.log('Executed the Pipeline.'); + + console.log('Results:'); + pipelineSnapshot.results.forEach(pipelineResult=> { + console.log(pipelineResult.data()); + }); +} +pipelinesQuickstart(); + +``` + + +## Samples + +Samples are in the [`samples/`](https://github.com/googleapis/nodejs-firestore/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample. + +| Sample | Source Code | Try it | +| --------------------------- | --------------------------------- | ------ | +| Limit-to-last-query | [source code](https://github.com/googleapis/nodejs-firestore/blob/main/samples/limit-to-last-query.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-firestore&page=editor&open_in_editor=samples/limit-to-last-query.js,samples/README.md) | +| Pipelines-quickstart | [source code](https://github.com/googleapis/nodejs-firestore/blob/main/samples/pipelines-quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-firestore&page=editor&open_in_editor=samples/pipelines-quickstart.js,samples/README.md) | +| Quickstart | [source code](https://github.com/googleapis/nodejs-firestore/blob/main/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-firestore&page=editor&open_in_editor=samples/quickstart.js,samples/README.md) | +| Solution-counters | [source code](https://github.com/googleapis/nodejs-firestore/blob/main/samples/solution-counters.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-firestore&page=editor&open_in_editor=samples/solution-counters.js,samples/README.md) | + + + +The [Cloud Firestore Node.js Client API Reference][client-docs] documentation +also contains samples. + +## Supported Node.js Versions + +Our client libraries follow the [Node.js release schedule](https://github.com/nodejs/release#release-schedule). +Libraries are compatible with all current _active_ and _maintenance_ versions of +Node.js. +If you are using an end-of-life version of Node.js, we recommend that you update +as soon as possible to an actively supported LTS version. + +Google's client libraries support legacy versions of Node.js runtimes on a +best-efforts basis with the following warnings: + +* Legacy versions are not tested in continuous integration. +* Some security patches and features cannot be backported. +* Dependencies cannot be kept up-to-date. + +Client libraries targeting some end-of-life versions of Node.js are available, and +can be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag). +The dist-tags follow the naming convention `legacy-(version)`. +For example, `npm install @google-cloud/firestore@legacy-8` installs client libraries +for versions compatible with Node.js 8. + +## Versioning + +This library follows [Semantic Versioning](http://semver.org/). + + + +This library is considered to be **stable**. The code surface will not change in backwards-incompatible ways +unless absolutely necessary (e.g. because of critical security issues) or with +an extensive deprecation period. Issues and requests against **stable** libraries +are addressed with the highest priority. + + + + + + +More Information: [Google Cloud Platform Launch Stages][launch_stages] + +[launch_stages]: https://cloud.google.com/terms/launch-stages + +## Contributing + +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/nodejs-firestore/blob/main/CONTRIBUTING.md). + +Please note that this `README.md`, the `samples/README.md`, +and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) +are generated from a central template. To edit one of these files, make an edit +to its templates in +[directory](https://github.com/googleapis/synthtool). + +## License + +Apache Version 2.0 + +See [LICENSE](https://github.com/googleapis/nodejs-firestore/blob/main/LICENSE) + +[client-docs]: https://cloud.google.com/nodejs/docs/reference/firestore/latest +[product-docs]: https://cloud.google.com/firestore +[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing +[enable_api]: https://console.cloud.google.com/flows/enableapi?apiid=firestore.googleapis.com +[auth]: https://cloud.google.com/docs/authentication/external/set-up-adc-local diff --git a/handwritten/firestore/api-report/firestore.api.md b/handwritten/firestore/api-report/firestore.api.md new file mode 100644 index 00000000000..73e85878b01 --- /dev/null +++ b/handwritten/firestore/api-report/firestore.api.md @@ -0,0 +1,2947 @@ +## API Report File for "@google-cloud/firestore" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { Duplex } from 'stream'; +import * as firestore from '@google-cloud/firestore'; +import { google } from '../protos/firestore_v1_proto_api'; +import { google as google_2 } from '../../protos/firestore_v1_proto_api'; +import { GoogleError } from 'google-gax'; +import * as proto from '../protos/firestore_v1_proto_api'; +import * as protos from '../../protos/firestore_v1_proto_api'; +import { Readable } from 'stream'; +import { Span as Span_2 } from '@opentelemetry/api'; + +// @beta +function abs(expr: Expression): FunctionExpression; + +// @beta +function abs(fieldName: string): FunctionExpression; + +// @beta +function add(first: Expression, second: Expression | unknown): FunctionExpression; + +// @beta +function add(fieldName: string, second: Expression | unknown): FunctionExpression; + +// @public +export class Aggregate { + constructor(alias: string, aggregateType: AggregateType, fieldPath?: (string | FieldPath) | undefined); + // (undocumented) + readonly aggregateType: AggregateType; + // (undocumented) + readonly alias: string; + // (undocumented) + readonly fieldPath?: (string | FieldPath) | undefined; + // @internal + toProto(): IAggregation; +} + +// @public +export class AggregateField implements firestore.AggregateField { + // (undocumented) + readonly aggregateType: AggregateType; + static average(field: string | FieldPath): AggregateField; + static count(): AggregateField; + // @internal + readonly _field?: string | FieldPath; + isEqual(other: AggregateField): boolean; + static sum(field: string | FieldPath): AggregateField; + readonly type = "AggregateField"; +} + +// @public +export type AggregateFieldType = ReturnType | ReturnType | ReturnType; + +// Warning: (ae-forgotten-export) The symbol "HasUserData" needs to be exported by the entry point index.d.ts +// +// @beta +class AggregateFunction implements AggregateFunction, HasUserData { + constructor(name: string, params: Expression[]); + as(name: string): AliasedAggregate; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + _createdFromLiteral: boolean; + // (undocumented) + expressionType: firestore.Pipelines.ExpressionType; + // (undocumented) + _protoValueType: "ProtoValue"; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "Serializer" needs to be exported by the entry point index.d.ts + // + // (undocumented) + _toProto(serializer: Serializer): api.IValue; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _validateUserData(ignoreUndefinedProperties: boolean): void; +} + +// @public +export class AggregateQuery implements firestore.AggregateQuery { + // @internal + constructor(_query: Query, _aggregates: AggregateSpecType); + explain(options?: firestore.ExplainOptions): Promise>>; + get(): Promise>; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "QuerySnapshotResponse" needs to be exported by the entry point index.d.ts + // + // @internal + _get(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions): Promise>>; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "QueryResponse" needs to be exported by the entry point index.d.ts + // + // @internal + _getResponse(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions): Promise>>; + isEqual(other: firestore.AggregateQuery): boolean; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + _pipeline(): Pipeline; + get query(): Query; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _stream(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions): Readable; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + toProto(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions): api.IRunAggregationQueryRequest; +} + +// @public +export class AggregateQuerySnapshot implements firestore.AggregateQuerySnapshot { + // @internal + constructor(_query: AggregateQuery, _readTime: Timestamp, _data: firestore.AggregateSpecData); + data(): firestore.AggregateSpecData; + isEqual(other: firestore.AggregateQuerySnapshot): boolean; + get query(): AggregateQuery; + get readTime(): Timestamp; +} + +// @public +export interface AggregateSpec { + // (undocumented) + [field: string]: AggregateFieldType; +} + +// @public +export type AggregateType = 'count' | 'avg' | 'sum'; + +// @beta +class AliasedAggregate implements AliasedAggregate, HasUserData { + constructor(_aggregate: AggregateFunction, _alias: string); + // (undocumented) + readonly _aggregate: AggregateFunction; + // (undocumented) + readonly _alias: string; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + _createdFromLiteral: boolean; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _validateUserData(ignoreUndefinedProperties: boolean): void; +} + +// @beta +class AliasedExpression implements firestore.Pipelines.Selectable, HasUserData { + constructor(_expr: Expression, _alias: string); + // (undocumented) + readonly _alias: string; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + _createdFromLiteral: boolean; + // (undocumented) + readonly _expr: Expression; + // (undocumented) + expressionType: firestore.Pipelines.ExpressionType; + // (undocumented) + selectable: true; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _validateUserData(ignoreUndefinedProperties: boolean): void; +} + +// @beta +function and(first: BooleanExpression, second: BooleanExpression, ...more: BooleanExpression[]): BooleanExpression; + +// @beta +function array(elements: unknown[]): FunctionExpression; + +// @beta +function arrayConcat(firstArray: Expression, secondArray: Expression | unknown[], ...otherArrays: Array): FunctionExpression; + +// @beta +function arrayConcat(firstArrayField: string, secondArray: Expression | unknown[], ...otherArrays: Array): FunctionExpression; + +// @beta +function arrayContains(array: Expression, element: Expression): BooleanExpression; + +// @beta +function arrayContains(array: Expression, element: unknown): BooleanExpression; + +// @beta +function arrayContains(fieldName: string, element: Expression): BooleanExpression; + +// @beta +function arrayContains(fieldName: string, element: unknown): BooleanExpression; + +// @beta +function arrayContainsAll(array: Expression, values: Array): BooleanExpression; + +// @beta +function arrayContainsAll(fieldName: string, values: Array): BooleanExpression; + +// @beta +function arrayContainsAll(array: Expression, arrayExpression: Expression): BooleanExpression; + +// @beta +function arrayContainsAll(fieldName: string, arrayExpression: Expression): BooleanExpression; + +// @beta +function arrayContainsAny(array: Expression, values: Array): BooleanExpression; + +// @beta +function arrayContainsAny(fieldName: string, values: Array): BooleanExpression; + +// @beta +function arrayContainsAny(array: Expression, values: Expression): BooleanExpression; + +// @beta +function arrayContainsAny(fieldName: string, values: Expression): BooleanExpression; + +// @beta +function arrayGet(arrayField: string, index: number): FunctionExpression; + +// @beta +function arrayGet(arrayField: string, indexExpr: Expression): FunctionExpression; + +// @beta +function arrayGet(arrayExpression: Expression, index: number): FunctionExpression; + +// @beta +function arrayGet(arrayExpression: Expression, indexExpr: Expression): FunctionExpression; + +// @beta +function arrayLength(fieldName: string): FunctionExpression; + +// @beta +function arrayLength(array: Expression): FunctionExpression; + +// @beta +function arrayReverse(fieldName: string): FunctionExpression; + +// @beta +function arrayReverse(arrayExpression: Expression): FunctionExpression; + +// @beta +function arraySum(fieldName: string): FunctionExpression; + +// @beta +function arraySum(expression: Expression): FunctionExpression; + +// @beta +function ascending(expr: Expression): Ordering; + +// @beta +function ascending(fieldName: string): Ordering; + +// @beta +function average(expression: Expression): AggregateFunction; + +// @beta +function average(fieldName: string): AggregateFunction; + +// @beta +abstract class BooleanExpression extends Expression implements firestore.Pipelines.BooleanExpression { + conditional(thenExpr: Expression, elseExpr: Expression): FunctionExpression; + countIf(): AggregateFunction; + // (undocumented) + abstract get _expr(): Expression; + ifError(catchValue: BooleanExpression): BooleanExpression; + ifError(catchValue: boolean): BooleanExpression; + ifError(catchValue: Expression): FunctionExpression; + ifError(catchValue: unknown): FunctionExpression; + not(): BooleanExpression; + // (undocumented) + _toProto(serializer: Serializer): api.IValue; + // (undocumented) + _validateUserData(ignoreUndefinedProperties: boolean): void; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class BulkWriter { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + constructor(firestore: Firestore, options?: firestore.BulkWriterOptions); + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + close(): Promise; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + create(documentRef: firestore.DocumentReference, data: firestore.WithFieldValue): Promise; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + delete(documentRef: firestore.DocumentReference, precondition?: firestore.Precondition): Promise; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + flush(): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + _getBufferedOperationsCount(): number; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + onWriteError(shouldRetryCallback: (error: BulkWriterError) => boolean): void; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + onWriteResult(successCallback: (documentRef: firestore.DocumentReference, result: WriteResult) => void): void; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "RateLimiter" needs to be exported by the entry point index.d.ts + // + // @internal + readonly _rateLimiter: RateLimiter; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "BulkCommitBatch" needs to be exported by the entry point index.d.ts + // Warning: (ae-forgotten-export) The symbol "BulkWriterOperation" needs to be exported by the entry point index.d.ts + // + // @internal + _sendFn(enqueueOnBatchCallback: (bulkCommitBatch: BulkCommitBatch) => void, op: BulkWriterOperation): void; + // (undocumented) + set(documentRef: firestore.DocumentReference, data: Partial, options: firestore.SetOptions): Promise; + // (undocumented) + set(documentRef: firestore.DocumentReference, data: AppModelType): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + _setMaxBatchSize(size: number): void; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + _setMaxPendingOpCount(newMax: number): void; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + update(documentRef: firestore.DocumentReference, dataOrField: firestore.UpdateData | string | FieldPath, ...preconditionOrValues: Array<{ + lastUpdateTime?: Timestamp; + } | unknown | string | FieldPath>): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _verifyNotClosed(): void; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class BulkWriterError extends Error { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + constructor( + code: GrpcStatus, + message: string, + documentRef: firestore.DocumentReference, + operationType: 'create' | 'set' | 'update' | 'delete', + failedAttempts: number); + readonly code: GrpcStatus; + readonly documentRef: firestore.DocumentReference; + readonly failedAttempts: number; + readonly message: string; + readonly operationType: 'create' | 'set' | 'update' | 'delete'; +} + +// @public +export class BundleBuilder { + constructor(bundleId: string); + // (undocumented) + add(documentSnapshot: DocumentSnapshot): BundleBuilder; + // (undocumented) + add(queryName: string, querySnapshot: QuerySnapshot): BundleBuilder; + // (undocumented) + build(): Buffer; + // (undocumented) + readonly bundleId: string; +} + +// @beta +function byteLength(expr: Expression): FunctionExpression; + +// @beta +function byteLength(fieldName: string): FunctionExpression; + +// @beta +function ceil(fieldName: string): FunctionExpression; + +// @beta +function ceil(expression: Expression): FunctionExpression; + +// @beta +function charLength(fieldName: string): FunctionExpression; + +// @beta +function charLength(stringExpression: Expression): FunctionExpression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class CollectionGroup extends Query implements firestore.CollectionGroup { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + constructor(firestore: Firestore, collectionId: string, converter: firestore.FirestoreDataConverter | undefined); + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + getPartitions(desiredPartitionCount: number): AsyncIterable>; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + withConverter(converter: firestore.FirestoreDataConverter | null): CollectionGroup; +} + +// @beta +function collectionId(fieldName: string): FunctionExpression; + +// @beta +function collectionId(expression: Expression): FunctionExpression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@extends" is not defined in this configuration +// +// @public +export class CollectionReference extends Query implements firestore.CollectionReference { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "ResourcePath" needs to be exported by the entry point index.d.ts + constructor(firestore: Firestore, path: ResourcePath, converter?: firestore.FirestoreDataConverter); + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + add(data: firestore.WithFieldValue): Promise>; + // (undocumented) + doc(): DocumentReference; + // (undocumented) + doc(documentPath: string): DocumentReference; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get id(): string; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + isEqual(other: firestore.CollectionReference): boolean; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + listDocuments(): Promise>>; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get parent(): DocumentReference | null; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get path(): string; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + get _resourcePath(): ResourcePath; + // (undocumented) + withConverter(converter: firestore.FirestoreDataConverter): CollectionReference; + // (undocumented) + withConverter(converter: null): CollectionReference; +} + +// @beta +function concat(first: Expression, second: Expression | unknown, ...others: Array): FunctionExpression; + +// @beta +function concat(fieldName: string, second: Expression | unknown, ...others: Array): FunctionExpression; + +// @beta +function conditional(condition: BooleanExpression, thenExpr: Expression, elseExpr: Expression): FunctionExpression; + +// @beta +class Constant extends Expression { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@hideconstructor" is not defined in this configuration + constructor(value: unknown); + // (undocumented) + readonly expressionType: firestore.Pipelines.ExpressionType; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + static _fromProto(value: api.IValue): Constant; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _toProto(serializer: Serializer): api.IValue; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _validateUserData(ignoreUndefinedProperties: boolean): void; +} + +// @beta +function constant(value: number): Expression; + +// @beta +function constant(value: string): Expression; + +// @beta +function constant(value: boolean): BooleanExpression; + +// @beta +function constant(value: null): Expression; + +// @beta +function constant(value: firestore.GeoPoint): Expression; + +// @beta +function constant(value: firestore.Timestamp): Expression; + +// @beta +function constant(value: Date): Expression; + +// @beta +function constant(value: Buffer | Uint8Array): Expression; + +// @beta +function constant(value: firestore.DocumentReference): Expression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// +// @beta +function constant(value: api.IValue): Expression; + +// @beta +function constant(value: firestore.VectorValue): Expression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// +// @beta (undocumented) +function constant(value: unknown): Expression; + +// @beta +function cosineDistance(fieldName: string, vector: number[] | VectorValue): FunctionExpression; + +// @beta +function cosineDistance(fieldName: string, vectorExpression: Expression): FunctionExpression; + +// @beta +function cosineDistance(vectorExpression: Expression, vector: number[] | VectorValue): FunctionExpression; + +// @beta +function cosineDistance(vectorExpression: Expression, otherVectorExpression: Expression): FunctionExpression; + +// @beta +function count(expression: Expression): AggregateFunction; + +// @beta +function count(fieldName: string): AggregateFunction; + +// @beta +function countAll(): AggregateFunction; + +// @beta +function countDistinct(expr: Expression | string): AggregateFunction; + +// @beta +function countIf(booleanExpr: BooleanExpression): AggregateFunction; + +// @beta +function currentTimestamp(): FunctionExpression; + +// @public (undocumented) +export const DEFAULT_MAX_IDLE_CHANNELS = 1; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// +// @public +export const DEFAULT_MAX_TRANSACTION_ATTEMPTS = 5; + +// @beta +function descending(expr: Expression): Ordering; + +// @beta +function descending(fieldName: string): Ordering; + +// @beta +function divide(dividend: Expression, divisort: Expression): FunctionExpression; + +// @beta +function divide(dividend: Expression, divisor: unknown): FunctionExpression; + +// @beta +function divide(dividend: string, divisor: Expression): FunctionExpression; + +// @beta +function divide(dividend: string, divisor: unknown): FunctionExpression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class DocumentChange implements firestore.DocumentChange { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + constructor(type: DocumentChangeType, document: QueryDocumentSnapshot, oldIndex: number, newIndex: number); + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get doc(): QueryDocumentSnapshot; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + isEqual(other: firestore.DocumentChange): boolean; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get newIndex(): number; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get oldIndex(): number; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get type(): DocumentChangeType; +} + +// @public (undocumented) +export type DocumentChangeType = 'added' | 'removed' | 'modified'; + +// @beta +function documentId(documentPath: string | firestore.DocumentReference): FunctionExpression; + +// @beta +function documentId(documentPathExpr: Expression): FunctionExpression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// Warning: (ae-forgotten-export) The symbol "Serializable" needs to be exported by the entry point index.d.ts +// +// @public +export class DocumentReference implements Serializable, firestore.DocumentReference { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + constructor(_firestore: Firestore, + _path: ResourcePath, + _converter?: firestore.FirestoreDataConverter); + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + collection(collectionPath: string): CollectionReference; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + readonly _converter: firestore.FirestoreDataConverter; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + create(data: firestore.WithFieldValue): Promise; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + delete(precondition?: firestore.Precondition): Promise; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get firestore(): Firestore; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + // + // @internal + get formattedName(): string; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + get(): Promise>; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get id(): string; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + isEqual(other: firestore.DocumentReference): boolean; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + listCollections(): Promise>; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + onSnapshot(onNext: (snapshot: firestore.DocumentSnapshot) => void, onError?: (error: Error) => void): () => void; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + get parent(): CollectionReference; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get path(): string; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + readonly _path: ResourcePath; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + get _resourcePath(): ResourcePath; + // (undocumented) + set(data: firestore.PartialWithFieldValue, options: firestore.SetOptions): Promise; + // (undocumented) + set(data: firestore.WithFieldValue): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + toProto(): api.IValue; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + update(dataOrField: firestore.UpdateData | string | firestore.FieldPath, ...preconditionOrValues: Array): Promise; + // (undocumented) + withConverter(converter: firestore.FirestoreDataConverter | null): DocumentReference; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class DocumentSnapshot implements firestore.DocumentSnapshot { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + constructor(ref: DocumentReference, + _fieldsProto?: ApiMapValue | undefined, readTime?: Timestamp, createTime?: Timestamp, updateTime?: Timestamp); + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get createTime(): Timestamp | undefined; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + data(): AppModelType | undefined; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get exists(): boolean; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "ApiMapValue" needs to be exported by the entry point index.d.ts + // + // @internal (undocumented) + readonly _fieldsProto?: ApiMapValue | undefined; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + static fromObject(ref: DocumentReference, obj: firestore.DocumentData): DocumentSnapshot; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "UpdateMap" needs to be exported by the entry point index.d.ts + // + // @internal + static fromUpdateMap(ref: firestore.DocumentReference, data: UpdateMap): DocumentSnapshot; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + get(field: string | FieldPath): any; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get id(): string; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + isEqual(other: firestore.DocumentSnapshot): boolean; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + protoField(field: string | FieldPath): api.IValue | undefined; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get readTime(): Timestamp; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get ref(): DocumentReference; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + toDocumentProto(): api.IDocument; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + toWriteProto(): api.IWrite; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get updateTime(): Timestamp | undefined; +} + +// @beta +function dotProduct(fieldName: string, vector: number[] | VectorValue): FunctionExpression; + +// @beta +function dotProduct(fieldName: string, vectorExpression: Expression): FunctionExpression; + +// @beta +function dotProduct(vectorExpression: Expression, vector: number[] | VectorValue): FunctionExpression; + +// @beta +function dotProduct(vectorExpression: Expression, otherVectorExpression: Expression): FunctionExpression; + +// @beta +function endsWith(fieldName: string, suffix: string): BooleanExpression; + +// @beta +function endsWith(fieldName: string, suffix: Expression): BooleanExpression; + +// @beta +function endsWith(stringExpression: Expression, suffix: string): BooleanExpression; + +// @beta +function endsWith(stringExpression: Expression, suffix: Expression): BooleanExpression; + +// @beta +function equal(left: Expression, right: Expression): BooleanExpression; + +// @beta +function equal(expression: Expression, value: unknown): BooleanExpression; + +// @beta +function equal(fieldName: string, expression: Expression): BooleanExpression; + +// @beta +function equal(fieldName: string, value: unknown): BooleanExpression; + +// @beta +function equalAny(expression: Expression, values: Array): BooleanExpression; + +// @beta +function equalAny(expression: Expression, arrayExpression: Expression): BooleanExpression; + +// @beta +function equalAny(fieldName: string, values: Array): BooleanExpression; + +// @beta +function equalAny(fieldName: string, arrayExpression: Expression): BooleanExpression; + +// @beta +function euclideanDistance(fieldName: string, vector: number[] | VectorValue): FunctionExpression; + +// @beta +function euclideanDistance(fieldName: string, vectorExpression: Expression): FunctionExpression; + +// @beta +function euclideanDistance(vectorExpression: Expression, vector: number[] | VectorValue): FunctionExpression; + +// @beta +function euclideanDistance(vectorExpression: Expression, otherVectorExpression: Expression): FunctionExpression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class ExecutionStats implements firestore.ExecutionStats { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + constructor(resultsReturned: number, executionDuration: firestore.Duration, readOperations: number, debugStats: Record); + // (undocumented) + readonly debugStats: Record; + // (undocumented) + readonly executionDuration: firestore.Duration; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + static _fromProto(stats: IExecutionStats | null | undefined, serializer: Serializer): ExecutionStats | null; + // (undocumented) + readonly readOperations: number; + // (undocumented) + readonly resultsReturned: number; +} + +// @beta +function exists(value: Expression): BooleanExpression; + +// @beta +function exists(fieldName: string): BooleanExpression; + +// @beta +function exp(expression: Expression): FunctionExpression; + +// @beta +function exp(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class ExplainMetrics implements firestore.ExplainMetrics { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + constructor(planSummary: PlanSummary, executionStats: ExecutionStats | null); + // (undocumented) + readonly executionStats: ExecutionStats | null; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + static _fromProto(metrics: IExplainMetrics, serializer: Serializer): ExplainMetrics; + // (undocumented) + readonly planSummary: PlanSummary; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class ExplainResults implements firestore.ExplainResults { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + constructor(metrics: ExplainMetrics, snapshot: T | null); + // (undocumented) + readonly metrics: ExplainMetrics; + // (undocumented) + readonly snapshot: T | null; +} + +// @beta +abstract class Expression implements firestore.Pipelines.Expression, HasUserData { + abs(): FunctionExpression; + add(second: firestore.Pipelines.Expression | unknown, ...others: Array): FunctionExpression; + arrayConcat(secondArray: Expression | unknown[], ...otherArrays: Array): FunctionExpression; + arrayContains(expression: Expression): BooleanExpression; + arrayContains(value: unknown): BooleanExpression; + arrayContainsAll(values: Array): BooleanExpression; + arrayContainsAll(arrayExpression: Expression): BooleanExpression; + arrayContainsAny(values: Array): BooleanExpression; + arrayContainsAny(arrayExpression: Expression): BooleanExpression; + arrayGet(index: number): FunctionExpression; + arrayGet(indexExpr: Expression): FunctionExpression; + arrayLength(): FunctionExpression; + arrayReverse(): FunctionExpression; + arraySum(): FunctionExpression; + as(name: string): AliasedExpression; + asBoolean(): BooleanExpression; + ascending(): Ordering; + average(): AggregateFunction; + byteLength(): FunctionExpression; + ceil(): FunctionExpression; + charLength(): FunctionExpression; + collectionId(): FunctionExpression; + concat(second: Expression | unknown, ...others: Array): FunctionExpression; + cosineDistance(vectorExpression: Expression): FunctionExpression; + cosineDistance(vector: firestore.VectorValue | number[]): FunctionExpression; + count(): AggregateFunction; + countDistinct(): AggregateFunction; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + _createdFromLiteral: boolean; + descending(): Ordering; + divide(divisor: Expression): FunctionExpression; + divide(divisor: number): FunctionExpression; + documentId(): FunctionExpression; + dotProduct(vectorExpression: Expression): FunctionExpression; + dotProduct(vector: firestore.VectorValue | number[]): FunctionExpression; + endsWith(suffix: string): BooleanExpression; + endsWith(suffix: Expression): BooleanExpression; + equal(expression: Expression): BooleanExpression; + equal(value: unknown): BooleanExpression; + equalAny(values: Array): BooleanExpression; + equalAny(arrayExpression: Expression): BooleanExpression; + euclideanDistance(vectorExpression: Expression): FunctionExpression; + euclideanDistance(vector: firestore.VectorValue | number[]): FunctionExpression; + exists(): BooleanExpression; + exp(): FunctionExpression; + // (undocumented) + abstract expressionType: firestore.Pipelines.ExpressionType; + floor(): FunctionExpression; + greaterThan(expression: Expression): BooleanExpression; + greaterThan(value: unknown): BooleanExpression; + greaterThanOrEqual(expression: Expression): BooleanExpression; + greaterThanOrEqual(value: unknown): BooleanExpression; + ifAbsent(elseValue: unknown): Expression; + ifAbsent(elseExpression: unknown): Expression; + ifError(catchExpr: Expression): FunctionExpression; + ifError(catchValue: unknown): FunctionExpression; + isAbsent(): BooleanExpression; + isError(): BooleanExpression; + isType(type: Type): BooleanExpression; + join(delimiterExpression: Expression): Expression; + join(delimiter: string): Expression; + length(): FunctionExpression; + lessThan(experession: Expression): BooleanExpression; + lessThan(value: unknown): BooleanExpression; + lessThanOrEqual(expression: Expression): BooleanExpression; + lessThanOrEqual(value: unknown): BooleanExpression; + like(pattern: string): BooleanExpression; + like(pattern: Expression): BooleanExpression; + ln(): FunctionExpression; + log10(): FunctionExpression; + logicalMaximum(second: Expression | unknown, ...others: Array): FunctionExpression; + logicalMinimum(second: Expression | unknown, ...others: Array): FunctionExpression; + mapEntries(): FunctionExpression; + mapGet(subfield: string): FunctionExpression; + mapKeys(): FunctionExpression; + mapMerge(secondMap: Record | Expression, ...otherMaps: Array | Expression>): FunctionExpression; + mapRemove(key: string): FunctionExpression; + mapRemove(keyExpr: Expression): FunctionExpression; + mapSet(key: string | Expression, value: unknown, ...moreKeyValues: unknown[]): FunctionExpression; + mapValues(): FunctionExpression; + maximum(): AggregateFunction; + minimum(): AggregateFunction; + mod(expression: Expression): FunctionExpression; + mod(value: number): FunctionExpression; + multiply(second: Expression | number, ...others: Array): FunctionExpression; + notEqual(expression: Expression): BooleanExpression; + notEqual(value: unknown): BooleanExpression; + notEqualAny(values: Array): BooleanExpression; + notEqualAny(arrayExpression: Expression): BooleanExpression; + pow(exponent: Expression): FunctionExpression; + pow(exponent: number): FunctionExpression; + // (undocumented) + _protoValueType: "ProtoValue"; + regexContains(pattern: string): BooleanExpression; + regexContains(pattern: Expression): BooleanExpression; + regexFind(pattern: string): FunctionExpression; + regexFind(pattern: Expression): FunctionExpression; + regexFindAll(pattern: string): FunctionExpression; + regexFindAll(pattern: Expression): FunctionExpression; + regexMatch(pattern: string): BooleanExpression; + regexMatch(pattern: Expression): BooleanExpression; + reverse(): FunctionExpression; + round(): FunctionExpression; + round(decimalPlaces: number): FunctionExpression; + round(decimalPlaces: Expression): FunctionExpression; + split(delimiter: string): FunctionExpression; + split(delimiter: Expression): FunctionExpression; + sqrt(): FunctionExpression; + startsWith(prefix: string): BooleanExpression; + startsWith(prefix: Expression): BooleanExpression; + stringConcat(secondString: Expression | string, ...otherStrings: Array): FunctionExpression; + stringContains(substring: string): BooleanExpression; + stringContains(expr: Expression): BooleanExpression; + stringReverse(): FunctionExpression; + substring(position: number, length?: number): FunctionExpression; + substring(position: Expression, length?: Expression): FunctionExpression; + subtract(subtrahend: firestore.Pipelines.Expression): FunctionExpression; + subtract(subtrahend: number): FunctionExpression; + sum(): AggregateFunction; + timestampAdd(unit: Expression, amount: Expression): FunctionExpression; + timestampAdd(unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; + timestampSubtract(unit: Expression, amount: Expression): FunctionExpression; + timestampSubtract(unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; + timestampToUnixMicros(): FunctionExpression; + timestampToUnixMillis(): FunctionExpression; + timestampToUnixSeconds(): FunctionExpression; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + timestampTruncate(granularity: firestore.Pipelines.TimeGranularity, timezone?: string | Expression): FunctionExpression; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + timestampTruncate(granularity: Expression, timezone?: string | Expression): FunctionExpression; + toLower(): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + abstract _toProto(serializer: Serializer): api.IValue; + toUpper(): FunctionExpression; + trim(valueToTrim?: string | Expression | Uint8Array | Buffer): FunctionExpression; + trunc(): FunctionExpression; + trunc(decimalPlaces: number): FunctionExpression; + trunc(decimalPlaces: Expression): FunctionExpression; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + type(): FunctionExpression; + unixMicrosToTimestamp(): FunctionExpression; + unixMillisToTimestamp(): FunctionExpression; + unixSecondsToTimestamp(): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + abstract _validateUserData(ignoreUndefinedProperties: boolean): void; + vectorLength(): FunctionExpression; +} + +// @beta +class Field extends Expression implements firestore.Pipelines.Selectable { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@hideconstructor" is not defined in this configuration + constructor(fieldPath: FieldPath); + // (undocumented) + get _alias(): string; + // (undocumented) + get _expr(): Expression; + // (undocumented) + readonly expressionType: firestore.Pipelines.ExpressionType; + // (undocumented) + get fieldName(): string; + // (undocumented) + selectable: true; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _toProto(_: Serializer): api.IValue; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _validateUserData(_: boolean): void; +} + +// @beta +function field(field: string | firestore.FieldPath): Field; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// Warning: (ae-forgotten-export) The symbol "Path" needs to be exported by the entry point index.d.ts +// +// @public +export class FieldPath extends Path implements firestore.FieldPath { + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + constructor(...segments: string[]); + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal @override + construct(segments: string[]): FieldPath; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + static documentId(): FieldPath; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // + // @internal + static _emptyPath(): FieldPath; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // + // @internal @override + get formattedName(): string; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // + // @internal + static fromArgument(fieldPath: string | firestore.FieldPath): FieldPath; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + isEqual(other: FieldPath): boolean; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + get _minNumSegments(): number; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // + // @internal @override + split(fieldPath: string): string[]; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + toString(): string; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class FieldValue implements firestore.FieldValue { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + constructor(); + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + static arrayRemove(...elements: unknown[]): FieldValue; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + static arrayUnion(...elements: unknown[]): FieldValue; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + static delete(): FieldValue; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + static increment(n: number): FieldValue; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + isEqual(other: firestore.FieldValue): boolean; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + static serverTimestamp(): FieldValue; + static vector(values?: number[]): VectorValue; +} + +// @public +export abstract class Filter { + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + static and(...filters: Filter[]): Filter; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + static or(...filters: Filter[]): Filter; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + static where(fieldPath: string | firestore.FieldPath, opStr: firestore.WhereFilterOp, value: unknown): Filter; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +class Firestore implements firestore.Firestore { + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + constructor(settings?: firestore.Settings); + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + batch(): WriteBatch; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + bulkWriter(options?: firestore.BulkWriterOptions): BulkWriter; + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + bundle(name?: string): BundleBuilder; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + collection(collectionPath: string): CollectionReference; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + collectionGroup(collectionId: string): CollectionGroup; + get databaseId(): string; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _decrementBulkWritersCount(): void; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + doc(documentPath: string): DocumentReference; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + get formattedName(): string; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + getAll(...documentRefsOrReadOptions: Array | firestore.ReadOptions>): Promise>>; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _incrementBulkWritersCount(): void; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + initializeIfNeeded(requestTag: string): Promise; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + listCollections(): Promise; + // @beta + pipeline(): PipelineSource; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + get projectId(): string; + recursiveDelete(ref: firestore.CollectionReference | firestore.DocumentReference, bulkWriter?: BulkWriter): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _recursiveDelete(ref: firestore.CollectionReference | firestore.DocumentReference, maxPendingOps: number, minPendingOps: number, bulkWriter?: BulkWriter): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + registerListener(): void; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "FirestoreUnaryMethod" needs to be exported by the entry point index.d.ts + // + // @internal + request(methodName: FirestoreUnaryMethod, request: Req, requestTag: string, retryCodes?: number[]): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "FirestoreStreamingMethod" needs to be exported by the entry point index.d.ts + // + // @internal + requestStream(methodName: FirestoreStreamingMethod, bidrectional: boolean, request: {}, requestTag: string): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@template" is not defined in this configuration + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + runTransaction(updateFunction: (transaction: Transaction) => Promise, transactionOptions?: firestore.ReadWriteTransactionOptions | firestore.ReadOnlyTransactionOptions): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _serializer: Serializer | null; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + settings(settings: firestore.Settings): void; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _settings: firestore.Settings; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + snapshot_(documentName: string, readTime?: google.protobuf.ITimestamp, encoding?: 'protobufJS'): DocumentSnapshot; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + snapshot_(documentName: string, readTime: string, encoding: 'json'): DocumentSnapshot; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + snapshot_(document: api.IDocument, readTime: google.protobuf.ITimestamp, encoding?: 'protobufJS'): QueryDocumentSnapshot; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + snapshot_(document: { + [k: string]: unknown; + }, readTime: string, encoding: 'json'): QueryDocumentSnapshot; + terminate(): Promise; + toJSON(): object; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "TraceUtil" needs to be exported by the entry point index.d.ts + // + // @internal + _traceUtil: TraceUtil; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + unregisterListener(): void; +} +export { Firestore } +export default Firestore; + +// @beta +function floor(expr: Expression): FunctionExpression; + +// @beta +function floor(fieldName: string): FunctionExpression; + +// @beta +class FunctionExpression extends Expression { + constructor(_methodName: string, params: Expression[]); + // (undocumented) + readonly expressionType: firestore.Pipelines.ExpressionType; + // (undocumented) + _methodName: string; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _toProto(serializer: Serializer): api.IValue; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _validateUserData(ignoreUndefinedProperties: boolean): void; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class GeoPoint implements Serializable, firestore.GeoPoint { + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + constructor(latitude: number, longitude: number); + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + static fromProto(proto: google.type.ILatLng): GeoPoint; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + isEqual(other: firestore.GeoPoint): boolean; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get latitude(): number; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get longitude(): number; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + toProto(): api.IValue; +} + +// @beta +function greaterThan(left: Expression, right: Expression): BooleanExpression; + +// @beta +function greaterThan(expression: Expression, value: unknown): BooleanExpression; + +// @beta +function greaterThan(fieldName: string, expression: Expression): BooleanExpression; + +// @beta +function greaterThan(fieldName: string, value: unknown): BooleanExpression; + +// @beta +function greaterThanOrEqual(left: Expression, right: Expression): BooleanExpression; + +// @beta +function greaterThanOrEqual(expression: Expression, value: unknown): BooleanExpression; + +// @beta +function greaterThanOrEqual(fieldName: string, value: Expression): BooleanExpression; + +// @beta +function greaterThanOrEqual(fieldName: string, value: unknown): BooleanExpression; + +// @beta +function ifAbsent(ifExpr: Expression, elseExpr: Expression): Expression; + +// @beta +function ifAbsent(ifExpr: Expression, elseValue: unknown): Expression; + +// @beta +function ifAbsent(ifFieldName: string, elseExpr: Expression): Expression; + +// @beta +function ifAbsent(ifFieldName: string | Expression, elseValue: Expression | unknown): Expression; + +// @beta +function ifError(tryExpr: BooleanExpression, catchExpr: BooleanExpression): BooleanExpression; + +// @beta +function ifError(tryExpr: Expression, catchExpr: Expression): FunctionExpression; + +// @beta +function ifError(tryExpr: Expression, catchValue: unknown): FunctionExpression; + +// @beta +function isAbsent(value: Expression): BooleanExpression; + +// @beta +function isAbsent(field: string): BooleanExpression; + +// @beta +function isError(value: Expression): BooleanExpression; + +// @beta +function isType(fieldName: string, type: Type): BooleanExpression; + +// @beta +function isType(expression: Expression, type: Type): BooleanExpression; + +// @beta +function join(arrayFieldName: string, delimiter: string): Expression; + +// @beta +function join(arrayExpression: Expression, delimiterExpression: Expression): Expression; + +// @beta +function join(arrayExpression: Expression, delimiter: string): Expression; + +// @beta +function join(arrayFieldName: string, delimiterExpression: Expression): Expression; + +// @beta +function length_2(fieldName: string): FunctionExpression; + +// @beta +function length_2(expression: Expression): FunctionExpression; + +// @beta +function lessThan(left: Expression, right: Expression): BooleanExpression; + +// @beta +function lessThan(expression: Expression, value: unknown): BooleanExpression; + +// @beta +function lessThan(fieldName: string, expression: Expression): BooleanExpression; + +// @beta +function lessThan(fieldName: string, value: unknown): BooleanExpression; + +// @beta +function lessThanOrEqual(left: Expression, right: Expression): BooleanExpression; + +// @beta +function lessThanOrEqual(expression: Expression, value: unknown): BooleanExpression; + +// @beta +function lessThanOrEqual(fieldName: string, expression: Expression): BooleanExpression; + +// @beta +function lessThanOrEqual(fieldName: string, value: unknown): BooleanExpression; + +// @beta +function like(fieldName: string, pattern: string): BooleanExpression; + +// @beta +function like(fieldName: string, pattern: Expression): BooleanExpression; + +// @beta +function like(stringExpression: Expression, pattern: string): BooleanExpression; + +// @beta +function like(stringExpression: Expression, pattern: Expression): BooleanExpression; + +// @beta +function ln(fieldName: string): FunctionExpression; + +// @beta +function ln(expression: Expression): FunctionExpression; + +// @beta +function log10(fieldName: string): FunctionExpression; + +// @beta +function log10(expression: Expression): FunctionExpression; + +// @beta +function logicalMaximum(first: Expression, second: Expression | unknown, ...others: Array): FunctionExpression; + +// @beta +function logicalMaximum(fieldName: string, second: Expression | unknown, ...others: Array): FunctionExpression; + +// @beta +function logicalMinimum(first: Expression, second: Expression | unknown, ...others: Array): FunctionExpression; + +// @beta +function logicalMinimum(fieldName: string, second: Expression | unknown, ...others: Array): FunctionExpression; + +// @beta +function map(elements: Record): FunctionExpression; + +// @beta +function mapEntries(mapField: string): FunctionExpression; + +// @beta +function mapEntries(mapExpression: Expression): FunctionExpression; + +// @beta +function mapGet(fieldName: string, subField: string): FunctionExpression; + +// @beta +function mapGet(mapExpression: Expression, subField: string): FunctionExpression; + +// @beta +function mapKeys(mapField: string): FunctionExpression; + +// @beta +function mapKeys(mapExpression: Expression): FunctionExpression; + +// @beta +function mapMerge(mapField: string, secondMap: Record | Expression, ...otherMaps: Array | Expression>): FunctionExpression; + +// @beta +function mapMerge(firstMap: Record | Expression, secondMap: Record | Expression, ...otherMaps: Array | Expression>): FunctionExpression; + +// @beta +function mapRemove(mapField: string, key: string): FunctionExpression; + +// @beta +function mapRemove(mapExpr: Expression, key: string): FunctionExpression; + +// @beta +function mapRemove(mapField: string, keyExpr: Expression): FunctionExpression; + +// @beta +function mapRemove(mapExpr: Expression, keyExpr: Expression): FunctionExpression; + +// @beta +function mapSet(mapField: string, key: string | Expression, value: unknown, ...moreKeyValues: unknown[]): FunctionExpression; + +// @beta +function mapSet(mapExpression: Expression, key: string | Expression, value: unknown, ...moreKeyValues: unknown[]): FunctionExpression; + +// @beta +function mapValues(mapField: string): FunctionExpression; + +// @beta +function mapValues(mapExpression: Expression): FunctionExpression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// +// @public +export const MAX_REQUEST_RETRIES = 5; + +// @beta +function maximum(expression: Expression): AggregateFunction; + +// @beta +function maximum(fieldName: string): AggregateFunction; + +// @beta +function minimum(expression: Expression): AggregateFunction; + +// @beta +function minimum(fieldName: string): AggregateFunction; + +// @beta +function mod(left: Expression, right: Expression): FunctionExpression; + +// @beta +function mod(expression: Expression, value: unknown): FunctionExpression; + +// @beta +function mod(fieldName: string, expression: Expression): FunctionExpression; + +// @beta +function mod(fieldName: string, value: unknown): FunctionExpression; + +// @beta +function multiply(first: Expression, second: Expression | unknown): FunctionExpression; + +// @beta +function multiply(fieldName: string, second: Expression | unknown): FunctionExpression; + +// @beta +function not(booleanExpr: BooleanExpression): BooleanExpression; + +// @beta +function notEqual(left: Expression, right: Expression): BooleanExpression; + +// @beta +function notEqual(expression: Expression, value: unknown): BooleanExpression; + +// @beta +function notEqual(fieldName: string, expression: Expression): BooleanExpression; + +// @beta +function notEqual(fieldName: string, value: unknown): BooleanExpression; + +// @beta +function notEqualAny(element: Expression, values: Array): BooleanExpression; + +// @beta +function notEqualAny(fieldName: string, values: Array): BooleanExpression; + +// @beta +function notEqualAny(element: Expression, arrayExpression: Expression): BooleanExpression; + +// @beta +function notEqualAny(fieldName: string, arrayExpression: Expression): BooleanExpression; + +// @beta +function or(first: BooleanExpression, second: BooleanExpression, ...more: BooleanExpression[]): BooleanExpression; + +// @beta +class Ordering implements HasUserData { + constructor(expr: Expression, direction: 'ascending' | 'descending'); + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + _createdFromLiteral: boolean; + // (undocumented) + readonly direction: 'ascending' | 'descending'; + // (undocumented) + readonly expr: Expression; + // (undocumented) + _protoValueType: 'ProtoValue'; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _toProto(serializer: Serializer): api.IValue; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _validateUserData(ignoreUndefinedProperties: boolean): void; +} + +// @beta +class Pipeline implements firestore.Pipelines.Pipeline { + // Warning: (ae-forgotten-export) The symbol "Stage" needs to be exported by the entry point index.d.ts + constructor(db: Firestore, stages: Stage[]); + addFields(field: firestore.Pipelines.Selectable, ...additionalFields: firestore.Pipelines.Selectable[]): Pipeline; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + addFields(options: firestore.Pipelines.AddFieldsStageOptions): Pipeline; + aggregate(accumulator: firestore.Pipelines.AliasedAggregate, ...additionalAccumulators: firestore.Pipelines.AliasedAggregate[]): Pipeline; + aggregate(options: firestore.Pipelines.AggregateStageOptions): Pipeline; + distinct(group: string | firestore.Pipelines.Selectable, ...additionalGroups: Array): Pipeline; + distinct(options: firestore.Pipelines.DistinctStageOptions): Pipeline; + execute(pipelineExecuteOptions?: firestore.Pipelines.PipelineExecuteOptions): Promise; + // Warning: (ae-forgotten-export) The symbol "PipelineResponse" needs to be exported by the entry point index.d.ts + // + // (undocumented) + _execute(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, pipelineExecuteOptions?: firestore.Pipelines.PipelineExecuteOptions): Promise; + findNearest(options: firestore.Pipelines.FindNearestStageOptions): Pipeline; + limit(limit: number): Pipeline; + limit(options: firestore.Pipelines.LimitStageOptions): Pipeline; + offset(offset: number): Pipeline; + offset(options: firestore.Pipelines.OffsetStageOptions): Pipeline; + rawStage(name: string, params: unknown[], options?: { + [key: string]: Expression | unknown; + }): Pipeline; + removeFields(fieldValue: firestore.Pipelines.Field | string, ...additionalFields: Array): Pipeline; + removeFields(options: firestore.Pipelines.RemoveFieldsStageOptions): Pipeline; + replaceWith(fieldName: string): Pipeline; + replaceWith(expr: firestore.Pipelines.Expression): Pipeline; + replaceWith(options: firestore.Pipelines.ReplaceWithStageOptions): Pipeline; + sample(documents: number): Pipeline; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + sample(options: firestore.Pipelines.SampleStageOptions): Pipeline; + select(selection: firestore.Pipelines.Selectable | string, ...additionalSelections: Array): Pipeline; + select(options: firestore.Pipelines.SelectStageOptions): Pipeline; + sort(ordering: firestore.Pipelines.Ordering, ...additionalOrderings: firestore.Pipelines.Ordering[]): Pipeline; + sort(options: firestore.Pipelines.SortStageOptions): Pipeline; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + stream(): NodeJS.ReadableStream; + // (undocumented) + _toProto(): api.IPipeline; + // Warning: (ae-forgotten-export) The symbol "StructuredPipeline" needs to be exported by the entry point index.d.ts + // + // (undocumented) + _toStructuredPipeline(pipelineExecuteOptions?: firestore.Pipelines.PipelineExecuteOptions): StructuredPipeline; + union(other: firestore.Pipelines.Pipeline): Pipeline; + union(options: firestore.Pipelines.UnionStageOptions): Pipeline; + unnest(selectable: firestore.Pipelines.Selectable, indexField?: string): Pipeline; + unnest(options: firestore.Pipelines.UnnestStageOptions): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + _validateUserData | HasUserData[] | HasUserData>(_: string, val: T): T; + where(condition: firestore.Pipelines.BooleanExpression): Pipeline; + where(options: firestore.Pipelines.WhereStageOptions): Pipeline; +} + +// @beta +class PipelineResult implements firestore.Pipelines.PipelineResult { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + constructor(serializer: Serializer, + _fieldsProto: ApiMapValue, ref?: DocumentReference, readTime?: Timestamp, createTime?: Timestamp, updateTime?: Timestamp); + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + get createTime(): Timestamp | undefined; + // (undocumented) + readonly _createTime: Timestamp | undefined; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + data(): firestore.DocumentData; + // (undocumented) + readonly _executionTime: Timestamp | undefined; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + readonly _fieldsProto: ApiMapValue; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + get(fieldPath: string | FieldPath): any; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + get id(): string | undefined; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + isEqual(other: PipelineResult): boolean; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + protoField(field: string | FieldPath): api.IValue | undefined; + get ref(): DocumentReference | undefined; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + get updateTime(): Timestamp | undefined; + // (undocumented) + readonly _updateTime: Timestamp | undefined; +} + +declare namespace Pipelines { + export { + Pipeline, + PipelineResult, + PipelineSnapshot, + PipelineSource, + and, + arrayContains, + arrayContainsAny, + arrayReverse, + average, + equal, + ceil, + exp, + floor, + greaterThan, + like, + lessThan, + notEqual, + ascending, + not, + or, + regexContains, + regexMatch, + regexFind, + regexFindAll, + startsWith, + stringConcat, + subtract, + cosineDistance, + countDistinct, + dotProduct, + euclideanDistance, + mapGet, + mapEntries, + mapKeys, + mapSet, + mapValues, + lessThanOrEqual, + equalAny, + map, + array, + field, + xor, + AggregateFunction, + arrayGet, + add, + BooleanExpression, + Expression, + FunctionExpression, + minimum, + count, + countIf, + arrayLength, + stringContains, + charLength, + divide, + mod, + reverse, + trim, + toUpper, + toLower, + vectorLength, + exists, + isAbsent, + ifError, + isError, + substring, + documentId, + arrayContainsAll, + constant, + Field, + Constant, + sum, + maximum, + descending, + greaterThanOrEqual, + multiply, + conditional, + Ordering, + AliasedAggregate, + endsWith, + AliasedExpression, + mapMerge, + mapRemove, + byteLength, + logicalMaximum, + logicalMinimum, + notEqualAny, + countAll, + timestampAdd, + timestampSubtract, + timestampToUnixMicros, + timestampToUnixSeconds, + unixMicrosToTimestamp, + timestampToUnixMillis, + unixSecondsToTimestamp, + unixMillisToTimestamp, + pow, + collectionId, + length_2 as length, + ln, + round, + sqrt, + rand, + trunc, + stringReverse, + abs, + arraySum, + ifAbsent, + log10, + concat, + join, + currentTimestamp, + arrayConcat, + type, + isType, + Type, + timestampTruncate, + split + } +} +export { Pipelines } + +// @beta +class PipelineSnapshot implements firestore.Pipelines.PipelineSnapshot { + // Warning: (ae-forgotten-export) The symbol "ExplainStats" needs to be exported by the entry point index.d.ts + constructor(pipeline: Pipeline, results: PipelineResult[], executionTime?: Timestamp, explainStats?: ExplainStats); + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + get executionTime(): Timestamp; + get explainStats(): ExplainStats | undefined; + get pipeline(): Pipeline; + get results(): PipelineResult[]; +} + +// @beta +class PipelineSource implements firestore.Pipelines.PipelineSource { + constructor(db: Firestore); + collection(collection: string | firestore.CollectionReference): Pipeline; + collection(options: firestore.Pipelines.CollectionStageOptions): Pipeline; + collectionGroup(collectionId: string): Pipeline; + collectionGroup(options: firestore.Pipelines.CollectionGroupStageOptions): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@FirestoreError" is not defined in this configuration + createFrom(query: firestore.VectorQuery): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@FirestoreError" is not defined in this configuration + createFrom(query: firestore.Query): Pipeline; + database(): Pipeline; + database(options: firestore.Pipelines.DatabaseStageOptions): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@FirestoreError" is not defined in this configuration + documents(docs: Array): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@FirestoreError" is not defined in this configuration + documents(options: firestore.Pipelines.DocumentsStageOptions): Pipeline; + // (undocumented) + _validateReference(reference: firestore.CollectionReference | firestore.DocumentReference): reference is CollectionReference | DocumentReference; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class PlanSummary implements firestore.PlanSummary { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + constructor(indexesUsed: Record[]); + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + static _fromProto(plan: IPlanSummary | null | undefined, serializer: Serializer): PlanSummary; + // (undocumented) + readonly indexesUsed: Record[]; +} + +// @beta +function pow(base: Expression, exponent: Expression): FunctionExpression; + +// @beta +function pow(base: Expression, exponent: number): FunctionExpression; + +// @beta +function pow(base: string, exponent: Expression): FunctionExpression; + +// @beta +function pow(base: string, exponent: number): FunctionExpression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class Query implements firestore.Query { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + constructor( + _firestore: Firestore, + _queryOptions: QueryOptions); + aggregate(aggregateSpec: T): AggregateQuery; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + protected readonly _allowUndefined: boolean; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + comparator(): (s1: QueryDocumentSnapshot, s2: QueryDocumentSnapshot) => number; + count(): AggregateQuery<{ + count: firestore.AggregateField; + }, AppModelType, DbModelType>; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _createSnapshot(readTime: Timestamp, size: number, docs: () => Array>, changes: () => Array>): QuerySnapshot; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + endAt(...fieldValuesOrDocumentSnapshot: Array): Query; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + endBefore(...fieldValuesOrDocumentSnapshot: Array): Query; + explain(options?: firestore.ExplainOptions): Promise>>; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + explainStream(explainOptions?: firestore.ExplainOptions): NodeJS.ReadableStream; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (ae-forgotten-export) The symbol "FieldOrder" needs to be exported by the entry point index.d.ts + // + // @internal + static _extractFieldValues(documentSnapshot: DocumentSnapshot, fieldOrders: FieldOrder[]): unknown[]; + // @deprecated + findNearest(vectorField: string | firestore.FieldPath, queryVector: firestore.VectorValue | Array, options: { + limit: number; + distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; + }): VectorQuery; + findNearest(options: VectorQueryOptions): VectorQuery; + // (undocumented) + _findNearest(options: VectorQueryOptions): VectorQuery; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get firestore(): Firestore; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + readonly _firestore: Firestore; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + get(): Promise>; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _get(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions): Promise>>; + // (undocumented) + _getResponse(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions): Promise>>; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _hasRetryTimedOut(methodName: string, startTime: number): boolean; + _isCollectionGroupQuery(): boolean; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + isEqual(other: firestore.Query): boolean; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _isPermanentRpcError(err: GoogleError, methodName: string): boolean; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + limit(limit: number): Query; + limitToLast(limit: number): Query; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + offset(offset: number): Query; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + onSnapshot(onNext: (snapshot: QuerySnapshot) => void, onError?: (error: Error) => void): () => void; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + orderBy(fieldPath: string | firestore.FieldPath, directionStr?: firestore.OrderByDirection): Query; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "CompositeFilter" needs to be exported by the entry point index.d.ts + // + // @internal (undocumented) + _parseCompositeFilter(compositeFilterData: CompositeFilter): FilterInternal; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "UnaryFilter" needs to be exported by the entry point index.d.ts + // Warning: (ae-forgotten-export) The symbol "FieldFilterInternal" needs to be exported by the entry point index.d.ts + // + // @internal (undocumented) + _parseFieldFilter(fieldFilterData: UnaryFilter): FieldFilterInternal; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "FilterInternal" needs to be exported by the entry point index.d.ts + // + // @internal (undocumented) + _parseFilter(filter: Filter): FilterInternal; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + _pipeline(): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "QueryOptions" needs to be exported by the entry point index.d.ts + // + // @internal (undocumented) + readonly _queryOptions: QueryOptions; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "QueryUtil" needs to be exported by the entry point index.d.ts + // + // @internal (undocumented) + readonly _queryUtil: QueryUtil>; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + select(...fieldPaths: Array): Query; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + readonly _serializer: Serializer; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + startAfter(...fieldValuesOrDocumentSnapshot: Array): Query; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + startAt(...fieldValuesOrDocumentSnapshot: Array): Query; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + stream(): NodeJS.ReadableStream; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _stream(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions): NodeJS.ReadableStream; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _toBundledQuery(): protos.firestore.IBundledQuery; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + toProto(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions): api.IRunQueryRequest; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + where(fieldPath: string | FieldPath, opStr: firestore.WhereFilterOp, value: unknown): Query; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + where(filter: Filter): Query; + // (undocumented) + withConverter(converter: firestore.FirestoreDataConverter | null): Query; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@extends" is not defined in this configuration +// +// @public +export class QueryDocumentSnapshot extends DocumentSnapshot implements firestore.QueryDocumentSnapshot { + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + // + // @override + get createTime(): Timestamp; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // + // @override + data(): AppModelType; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + // + // @override + get updateTime(): Timestamp; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class QueryPartition implements firestore.QueryPartition { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + constructor(_firestore: Firestore, _collectionId: string, _converter: firestore.FirestoreDataConverter, _startAt: api.IValue[] | undefined, _endBefore: api.IValue[] | undefined); + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + get endBefore(): unknown[] | undefined; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + get startAt(): unknown[] | undefined; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + toQuery(): Query; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class QuerySnapshot implements firestore.QuerySnapshot { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + constructor(_query: Query, _readTime: Timestamp, _size: number, docs: () => Array>, changes: () => Array>); + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + docChanges(): Array>; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get docs(): Array>; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get empty(): boolean; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + forEach(callback: (result: firestore.QueryDocumentSnapshot) => void, thisArg?: unknown): void; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + isEqual(other: firestore.QuerySnapshot): boolean; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get query(): Query; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get readTime(): Timestamp; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get size(): number; +} + +// @beta +function rand(): FunctionExpression; + +// @beta +function regexContains(fieldName: string, pattern: string): BooleanExpression; + +// @beta +function regexContains(fieldName: string, pattern: Expression): BooleanExpression; + +// @beta +function regexContains(stringExpression: Expression, pattern: string): BooleanExpression; + +// @beta +function regexContains(stringExpression: Expression, pattern: Expression): BooleanExpression; + +// @beta +function regexFind(fieldName: string, pattern: string): FunctionExpression; + +// @beta +function regexFind(fieldName: string, pattern: Expression): FunctionExpression; + +// @beta +function regexFind(stringExpression: Expression, pattern: string): FunctionExpression; + +// @beta +function regexFind(stringExpression: Expression, pattern: Expression): FunctionExpression; + +// @beta +function regexFindAll(fieldName: string, pattern: string): FunctionExpression; + +// @beta +function regexFindAll(fieldName: string, pattern: Expression): FunctionExpression; + +// @beta +function regexFindAll(stringExpression: Expression, pattern: string): FunctionExpression; + +// @beta +function regexFindAll(stringExpression: Expression, pattern: Expression): FunctionExpression; + +// @beta +function regexMatch(fieldName: string, pattern: string): BooleanExpression; + +// @beta +function regexMatch(fieldName: string, pattern: Expression): BooleanExpression; + +// @beta +function regexMatch(stringExpression: Expression, pattern: string): BooleanExpression; + +// @beta +function regexMatch(stringExpression: Expression, pattern: Expression): BooleanExpression; + +// @beta +function reverse(stringExpression: Expression): FunctionExpression; + +// @beta +function reverse(field: string): FunctionExpression; + +// @beta +function round(fieldName: string): FunctionExpression; + +// @beta +function round(expression: Expression): FunctionExpression; + +// @beta +function round(fieldName: string, decimalPlaces: number | Expression): FunctionExpression; + +// @beta +function round(expression: Expression, decimalPlaces: number | Expression): FunctionExpression; + +// @public +export function setLogFunction(logger: ((msg: string) => void) | null): void; + +// @beta +function split(fieldName: string, delimiter: string): FunctionExpression; + +// @beta +function split(fieldName: string, delimiter: Expression): FunctionExpression; + +// @beta +function split(expression: Expression, delimiter: string): FunctionExpression; + +// @beta +function split(expression: Expression, delimiter: Expression): FunctionExpression; + +// @beta +function sqrt(expression: Expression): FunctionExpression; + +// @beta +function sqrt(fieldName: string): FunctionExpression; + +// @beta +function startsWith(fieldName: string, prefix: string): BooleanExpression; + +// @beta +function startsWith(fieldName: string, prefix: Expression): BooleanExpression; + +// @beta +function startsWith(stringExpression: Expression, prefix: string): BooleanExpression; + +// @beta +function startsWith(stringExpression: Expression, prefix: Expression): BooleanExpression; + +// @beta +function stringConcat(fieldName: string, secondString: Expression | string, ...otherStrings: Array): FunctionExpression; + +// @beta +function stringConcat(firstString: Expression, secondString: Expression | string, ...otherStrings: Array): FunctionExpression; + +// @beta +function stringContains(fieldName: string, substring: string): BooleanExpression; + +// @beta +function stringContains(fieldName: string, substring: Expression): BooleanExpression; + +// @beta +function stringContains(stringExpression: Expression, substring: string): BooleanExpression; + +// @beta +function stringContains(stringExpression: Expression, substring: Expression): BooleanExpression; + +// @beta +function stringReverse(stringExpression: Expression): FunctionExpression; + +// @beta +function stringReverse(field: string): FunctionExpression; + +// @beta +function substring(field: string, position: number, length?: number): FunctionExpression; + +// @beta +function substring(input: Expression, position: number, length?: number): FunctionExpression; + +// @beta +function substring(field: string, position: Expression, length?: Expression): FunctionExpression; + +// @beta +function substring(input: Expression, position: Expression, length?: Expression): FunctionExpression; + +// @beta +function subtract(minuend: Expression, subtrahend: Expression): FunctionExpression; + +// @beta +function subtract(minuend: Expression, subtrahend: unknown): FunctionExpression; + +// @beta +function subtract(minuendFieldName: string, subtrahend: Expression): FunctionExpression; + +// @beta +function subtract(minuendFieldName: string, subtrahend: unknown): FunctionExpression; + +// @beta +function sum(expression: Expression): AggregateFunction; + +// @beta +function sum(fieldName: string): AggregateFunction; + +// @public +export class Timestamp implements firestore.Timestamp { + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + constructor(seconds: number, nanoseconds: number); + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + static fromDate(date: Date): Timestamp; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + static fromMillis(milliseconds: number): Timestamp; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // + // @internal + static fromProto(timestamp: google.protobuf.ITimestamp): Timestamp; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + isEqual(other: firestore.Timestamp): boolean; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + get nanoseconds(): number; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + static now(): Timestamp; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + get seconds(): number; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + toDate(): Date; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + toMillis(): number; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // + // @internal + toProto(): api.IValue; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + valueOf(): string; +} + +// @beta +function timestampAdd(timestamp: Expression, unit: Expression, amount: Expression): FunctionExpression; + +// @beta +function timestampAdd(timestamp: Expression, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; + +// @beta +function timestampAdd(fieldName: string, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; + +// @beta +function timestampSubtract(timestamp: Expression, unit: Expression, amount: Expression): FunctionExpression; + +// @beta +function timestampSubtract(timestamp: Expression, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; + +// @beta +function timestampSubtract(fieldName: string, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; + +// @beta +function timestampToUnixMicros(expr: Expression): FunctionExpression; + +// @beta +function timestampToUnixMicros(fieldName: string): FunctionExpression; + +// @beta +function timestampToUnixMillis(expr: Expression): FunctionExpression; + +// @beta +function timestampToUnixMillis(fieldName: string): FunctionExpression; + +// @beta +function timestampToUnixSeconds(expr: Expression): FunctionExpression; + +// @beta +function timestampToUnixSeconds(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +// Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "Expression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "FunctionExpression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "Expression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "FunctionExpression" which is marked as @beta +// +// @public +function timestampTruncate(fieldName: string, granularity: firestore.Pipelines.TimeGranularity, timezone?: string | Expression): FunctionExpression; + +// Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +// Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "Expression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "FunctionExpression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "Expression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "FunctionExpression" which is marked as @beta +// +// @public +function timestampTruncate(fieldName: string, granularity: Expression, timezone?: string | Expression): FunctionExpression; + +// Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +// Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "Expression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "FunctionExpression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "Expression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "FunctionExpression" which is marked as @beta +// +// @public +function timestampTruncate(timestampExpression: Expression, granularity: firestore.Pipelines.TimeGranularity, timezone?: string | Expression): FunctionExpression; + +// Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +// Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "Expression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "FunctionExpression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "Expression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "FunctionExpression" which is marked as @beta +// +// @public +function timestampTruncate(timestampExpression: Expression, granularity: Expression, timezone?: string | Expression): FunctionExpression; + +// @beta +function toLower(fieldName: string): FunctionExpression; + +// @beta +function toLower(stringExpression: Expression): FunctionExpression; + +// @beta +function toUpper(fieldName: string): FunctionExpression; + +// @beta +function toUpper(stringExpression: Expression): FunctionExpression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class Transaction implements firestore.Transaction { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + constructor(firestore: Firestore, requestTag: string, transactionOptions?: firestore.ReadWriteTransactionOptions | firestore.ReadOnlyTransactionOptions); + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + commit(): Promise; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + create(documentRef: firestore.DocumentReference, data: firestore.WithFieldValue): Transaction; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + delete(documentRef: DocumentReference, precondition?: firestore.Precondition): this; + // Warning: (ae-incompatible-release-tags) The symbol "execute" is marked as @public, but its signature references "Pipeline" which is marked as @beta + // Warning: (ae-incompatible-release-tags) The symbol "execute" is marked as @public, but its signature references "PipelineSnapshot" which is marked as @beta + execute(pipeline: Pipeline): Promise; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + get(query: firestore.Query): Promise>; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + get(documentRef: firestore.DocumentReference): Promise>; + get(aggregateQuery: firestore.AggregateQuery): Promise>; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + getAll(...documentRefsOrReadOptions: Array | firestore.ReadOptions>): Promise>>; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + rollback(): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + runTransaction(updateFunction: (transaction: Transaction) => Promise): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + runTransactionOnce(updateFunction: (transaction: Transaction) => Promise): Promise; + // (undocumented) + set(documentRef: firestore.DocumentReference, data: firestore.PartialWithFieldValue, options: firestore.SetOptions): Transaction; + // (undocumented) + set(documentRef: firestore.DocumentReference, data: firestore.WithFieldValue): Transaction; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + update(documentRef: firestore.DocumentReference, dataOrField: firestore.UpdateData | string | firestore.FieldPath, ...preconditionOrValues: Array): Transaction; +} + +// @beta +function trim(fieldName: string, valueToTrim?: string | Expression): FunctionExpression; + +// @beta +function trim(stringExpression: Expression, valueToTrim?: string | Expression): FunctionExpression; + +// @beta +function trunc(fieldName: string): FunctionExpression; + +// @beta +function trunc(expression: Expression): FunctionExpression; + +// @beta +function trunc(fieldName: string, decimalPlaces: number | Expression): FunctionExpression; + +// @beta +function trunc(expression: Expression, decimalPlaces: number | Expression): FunctionExpression; + +// @beta +type Type = 'null' | 'array' | 'boolean' | 'bytes' | 'timestamp' | 'geo_point' | 'number' | 'int32' | 'int64' | 'float64' | 'decimal128' | 'map' | 'reference' | 'string' | 'vector' | 'max_key' | 'min_key' | 'object_id' | 'regex' | 'request_timestamp'; + +// Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +// Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +// +// @beta +function type(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +// Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +// +// @beta +function type(expression: Expression): FunctionExpression; + +// @beta +function unixMicrosToTimestamp(expr: Expression): FunctionExpression; + +// @beta +function unixMicrosToTimestamp(fieldName: string): FunctionExpression; + +// @beta +function unixMillisToTimestamp(expr: Expression): FunctionExpression; + +// @beta +function unixMillisToTimestamp(fieldName: string): FunctionExpression; + +// @beta +function unixSecondsToTimestamp(expr: Expression): FunctionExpression; + +// @beta +function unixSecondsToTimestamp(fieldName: string): FunctionExpression; + +// @beta +function vectorLength(vectorExpression: Expression): FunctionExpression; + +// @beta +function vectorLength(fieldName: string): FunctionExpression; + +// @public +export class VectorQuery implements firestore.VectorQuery { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + constructor(_query: Query, _options: VectorQueryOptions); + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _createSnapshot(readTime: Timestamp, size: number, docs: () => Array>, changes: () => Array>): VectorQuerySnapshot; + explain(options?: firestore.ExplainOptions): Promise>>; + get(): Promise>; + // (undocumented) + _getResponse(explainOptions?: firestore.ExplainOptions): Promise>>; + isEqual(other: firestore.VectorQuery): boolean; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + _pipeline(): Pipeline; + get query(): Query; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + readonly _queryUtil: QueryUtil>; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + startAfter(...fieldValuesOrDocumentSnapshot: Array): VectorQuery; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _stream(transactionId?: Uint8Array): NodeJS.ReadableStream; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + toProto(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions): api.IRunQueryRequest; +} + +// @public +export interface VectorQueryOptions { + distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; + distanceResultField?: string | firestore.FieldPath; + distanceThreshold?: number; + limit: number; + queryVector: firestore.VectorValue | Array; + vectorField: string | firestore.FieldPath; +} + +// @public +export class VectorQuerySnapshot implements firestore.VectorQuerySnapshot { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + constructor(_query: VectorQuery, _readTime: Timestamp, _size: number, docs: () => Array>, changes: () => Array>); + docChanges(): Array>; + get docs(): Array>; + get empty(): boolean; + forEach(callback: (result: firestore.QueryDocumentSnapshot) => void, thisArg?: unknown): void; + isEqual(other: firestore.VectorQuerySnapshot): boolean; + get query(): VectorQuery; + get readTime(): Timestamp; + get size(): number; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class VectorValue implements firestore.VectorValue { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + constructor(values: number[] | undefined); + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + static _fromProto(valueArray: api.IValue): VectorValue; + isEqual(other: VectorValue): boolean; + toArray(): number[]; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + _toProto(serializer: Serializer): api.IValue; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class WriteBatch implements firestore.WriteBatch { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + constructor(firestore: Firestore); + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + commit(): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // + // @internal + _commit(commitOptions?: { + transactionId?: Uint8Array; + requestTag?: string; + retryCodes?: number[]; + methodName?: FirestoreUnaryMethod; + }): Promise; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + create(documentRef: firestore.DocumentReference, data: firestore.WithFieldValue): WriteBatch; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + delete(documentRef: firestore.DocumentReference, precondition?: firestore.Precondition): WriteBatch; + // (undocumented) + protected readonly _firestore: Firestore; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + get isEmpty(): boolean; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + get _opCount(): number; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _reset(): void; + // (undocumented) + set(documentRef: firestore.DocumentReference, data: firestore.PartialWithFieldValue, options: firestore.SetOptions): WriteBatch; + // (undocumented) + set(documentRef: firestore.DocumentReference, data: firestore.WithFieldValue): WriteBatch; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + update(documentRef: firestore.DocumentReference, dataOrField: firestore.UpdateData | string | firestore.FieldPath, ...preconditionOrValues: Array<{ + lastUpdateTime?: firestore.Timestamp; + } | unknown | string | firestore.FieldPath>): WriteBatch; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class WriteResult implements firestore.WriteResult { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + constructor(_writeTime: Timestamp); + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + isEqual(other: firestore.WriteResult): boolean; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get writeTime(): Timestamp; +} + +// @beta +function xor(first: BooleanExpression, second: BooleanExpression, ...additionalConditions: BooleanExpression[]): BooleanExpression; + +// Warnings were encountered during analysis: +// +// build/types/src/bulk-writer.d.ts:49:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bulk-writer.d.ts:83:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bulk-writer.d.ts:146:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bulk-writer.d.ts:153:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bulk-writer.d.ts:160:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bulk-writer.d.ts:168:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bulk-writer.d.ts:183:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bulk-writer.d.ts:190:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bulk-writer.d.ts:199:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bulk-writer.d.ts:217:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bulk-writer.d.ts:229:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bulk-writer.d.ts:236:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bulk-writer.d.ts:490:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bulk-writer.d.ts:496:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bulk-writer.d.ts:503:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bulk-writer.d.ts:509:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bulk-writer.d.ts:516:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/bundle.d.ts:19:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/filter.d.ts:120:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/filter.d.ts:155:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/index.d.ts:299:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/index.d.ts:319:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/index.d.ts:326:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/index.d.ts:347:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/index.d.ts:354:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/index.d.ts:363:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/index.d.ts:371:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/index.d.ts:378:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/index.d.ts:387:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/index.d.ts:881:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/index.d.ts:900:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/index.d.ts:915:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/path.d.ts:29:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/path.d.ts:31:4 - (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// build/types/src/path.d.ts:146:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/path.d.ts:338:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/rate-limiter.d.ts:13:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/reference/aggregate-query.d.ts:86:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/reference/field-filter-internal.d.ts:24:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/reference/field-filter-internal.d.ts:26:4 - (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// build/types/src/reference/field-order.d.ts:22:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/reference/field-order.d.ts:24:4 - (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// build/types/src/reference/query-options.d.ts:27:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/reference/query.d.ts:441:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/reference/query.d.ts:452:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/reference/query.d.ts:454:15 - (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' +// build/types/src/reference/query.d.ts:456:15 - (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' +// build/types/src/reference/query.d.ts:460:24 - (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +// build/types/src/reference/query.d.ts:460:17 - (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +// build/types/src/reference/query.d.ts:473:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/reference/query.d.ts:660:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/reference/vector-query.d.ts:51:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/reference/vector-query.d.ts:56:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/reference/vector-query.d.ts:61:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/serializer.d.ts:30:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/serializer.d.ts:40:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/telemetry/trace-util.d.ts:67:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/write-batch.d.ts:85:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/types/src/write-batch.d.ts:108:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + +// (No @packageDocumentation comment for this package) + +``` diff --git a/handwritten/firestore/dev/.gitattributes b/handwritten/firestore/dev/.gitattributes new file mode 100644 index 00000000000..33739cb74e4 --- /dev/null +++ b/handwritten/firestore/dev/.gitattributes @@ -0,0 +1,4 @@ +*.ts text eol=lf +*.js text eol=lf +protos/* linguist-generated +**/api-extractor.json linguist-language=JSON-with-Comments diff --git a/handwritten/firestore/dev/.nycrc b/handwritten/firestore/dev/.nycrc new file mode 100644 index 00000000000..81a95fc94b0 --- /dev/null +++ b/handwritten/firestore/dev/.nycrc @@ -0,0 +1,24 @@ +{ + "report-dir": "./.coverage", + "reporter": ["text", "lcov"], + "exclude": [ + "**/*-test", + "**/.coverage", + "**/apis", + "**/benchmark", + "**/conformance", + "**/docs", + "**/samples", + "**/scripts", + "**/protos", + "**/test", + "**/*.d.ts", + ".jsdoc.js", + "**/.jsdoc.js", + "karma.conf.js", + "webpack-tests.config.js", + "webpack.config.js" + ], + "exclude-after-remap": false, + "all": true +} \ No newline at end of file diff --git a/handwritten/firestore/dev/.prettierignore b/handwritten/firestore/dev/.prettierignore new file mode 100644 index 00000000000..9340ad9b86d --- /dev/null +++ b/handwritten/firestore/dev/.prettierignore @@ -0,0 +1,6 @@ +**/node_modules +**/coverage +test/fixtures +build/ +docs/ +protos/ diff --git a/handwritten/firestore/dev/CODE_OF_CONDUCT.md b/handwritten/firestore/dev/CODE_OF_CONDUCT.md new file mode 100644 index 00000000000..2add2547a81 --- /dev/null +++ b/handwritten/firestore/dev/CODE_OF_CONDUCT.md @@ -0,0 +1,94 @@ + +# Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of +experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, or to ban temporarily or permanently any +contributor for other behaviors that they deem inappropriate, threatening, +offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +This Code of Conduct also applies outside the project spaces when the Project +Steward has a reasonable belief that an individual's behavior may have a +negative impact on the project or its community. + +## Conflict Resolution + +We do not believe that all conflict is bad; healthy debate and disagreement +often yield positive results. However, it is never okay to be disrespectful or +to engage in behavior that violates the project’s code of conduct. + +If you see someone violating the code of conduct, you are encouraged to address +the behavior directly with those involved. Many issues can be resolved quickly +and easily, and this gives people more control over the outcome of their +dispute. If you are unable to resolve the matter for any reason, or if the +behavior is threatening or harassing, report it. We are dedicated to providing +an environment where participants feel welcome and safe. + +Reports should be directed to *googleapis-stewards@google.com*, the +Project Steward(s) for *Google Cloud Client Libraries*. It is the Project Steward’s duty to +receive and address reported violations of the code of conduct. They will then +work with a committee consisting of representatives from the Open Source +Programs Office and the Google Open Source Strategy team. If for any reason you +are uncomfortable reaching out to the Project Steward, please email +opensource@google.com. + +We will investigate every complaint, but you may not receive a direct response. +We will use our discretion in determining when and how to follow up on reported +incidents, which may range from not taking action to permanent expulsion from +the project and project-sponsored spaces. We will notify the accused of the +report and provide them an opportunity to discuss it before any action is taken. +The identity of the reporter will be omitted from the details of the report +supplied to the accused. In potentially harmful situations, such as ongoing +harassment or threats to anyone's safety, we may take action without notice. + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 1.4, +available at +https://www.contributor-covenant.org/version/1/4/code-of-conduct.html \ No newline at end of file diff --git a/handwritten/firestore/dev/CONTRIBUTING.md b/handwritten/firestore/dev/CONTRIBUTING.md new file mode 100644 index 00000000000..c97e96eb4e4 --- /dev/null +++ b/handwritten/firestore/dev/CONTRIBUTING.md @@ -0,0 +1,76 @@ +# How to become a contributor and submit your own code + +**Table of contents** + +* [Contributor License Agreements](#contributor-license-agreements) +* [Contributing a patch](#contributing-a-patch) +* [Running the tests](#running-the-tests) +* [Releasing the library](#releasing-the-library) + +## Contributor License Agreements + +We'd love to accept your sample apps and patches! Before we can take them, we +have to jump a couple of legal hurdles. + +Please fill out either the individual or corporate Contributor License Agreement +(CLA). + + * If you are an individual writing original source code and you're sure you + own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). + * If you work for a company that wants to allow you to contribute your work, + then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). + +Follow either of the two links above to access the appropriate CLA and +instructions for how to sign and return it. Once we receive it, we'll be able to +accept your pull requests. + +## Contributing A Patch + +1. Submit an issue describing your proposed change to the repo in question. +1. The repo owner will respond to your issue promptly. +1. If your proposed change is accepted, and you haven't already done so, sign a + Contributor License Agreement (see details above). +1. Fork the desired repo, develop and test your code changes. +1. Ensure that your code adheres to the existing style in the code to which + you are contributing. +1. Ensure that your code has an appropriate set of tests which all pass. +1. Title your pull request following [Conventional Commits](https://www.conventionalcommits.org/) styling. +1. Submit a pull request. + +### Before you begin + +1. [Select or create a Cloud Platform project][projects]. +1. [Enable billing for your project][billing]. +1. [Enable the Firestore API][enable_api]. +1. [Set up authentication with a service account][auth] so you can access the + API from your local workstation. + + +## Running the tests + +1. [Prepare your environment for Node.js setup][setup]. + +1. Install dependencies: + + npm install + +1. Run the tests: + + # Run unit tests. + npm test + + # Run sample integration tests. + npm run samples-test + + # Run all system tests. + npm run system-test + +1. Lint (and maybe fix) any changes: + + npm run fix + +[setup]: https://cloud.google.com/nodejs/docs/setup +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing +[enable_api]: https://console.cloud.google.com/flows/enableapi?apiid=firestore.googleapis.com +[auth]: https://cloud.google.com/docs/authentication/getting-started \ No newline at end of file diff --git a/handwritten/firestore/dev/LICENSE b/handwritten/firestore/dev/LICENSE new file mode 100644 index 00000000000..d6456956733 --- /dev/null +++ b/handwritten/firestore/dev/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-all-transforms.json b/handwritten/firestore/dev/conformance/conformance-tests/create-all-transforms.json new file mode 100644 index 00000000000..63895999879 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-all-transforms.json @@ -0,0 +1,68 @@ +{ + "tests": [ + { + "description": "create: all transforms in a single call", + "comment": "A document can be created with any amount of transforms.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": \"ServerTimestamp\", \"c\": [\"ArrayUnion\", 1, 2, 3], \"d\": [\"ArrayRemove\", 4, 5, 6]}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "currentDocument": { + "exists": false + }, + "updateTransforms": [ + { + "fieldPath": "b", + "setToServerValue": "REQUEST_TIME" + }, + { + "fieldPath": "c", + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + }, + { + "fieldPath": "d", + "removeAllFromArray": { + "values": [ + { + "integerValue": "4" + }, + { + "integerValue": "5" + }, + { + "integerValue": "6" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove-multi.json b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove-multi.json new file mode 100644 index 00000000000..331a53bf9c8 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove-multi.json @@ -0,0 +1,64 @@ +{ + "tests": [ + { + "description": "create: multiple ArrayRemove fields", + "comment": "A document can have more than one ArrayRemove field.\nSince all the ArrayRemove fields are removed, the only field in the update is \"a\".", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": [\"ArrayRemove\", 1, 2, 3], \"c\": {\"d\": [\"ArrayRemove\", 4, 5, 6]}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "currentDocument": { + "exists": false + }, + "updateTransforms": [ + { + "fieldPath": "b", + "removeAllFromArray": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + }, + { + "fieldPath": "c.d", + "removeAllFromArray": { + "values": [ + { + "integerValue": "4" + }, + { + "integerValue": "5" + }, + { + "integerValue": "6" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove-nested.json new file mode 100644 index 00000000000..00c73d05ccf --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove-nested.json @@ -0,0 +1,48 @@ +{ + "tests": [ + { + "description": "create: nested ArrayRemove field", + "comment": "An ArrayRemove value can occur at any depth. In this case,\nthe transform applies to the field path \"b.c\". Since \"c\" is removed from the update,\n\"b\" becomes empty, so it is also removed from the update.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": {\"c\": [\"ArrayRemove\", 1, 2, 3]}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "currentDocument": { + "exists": false + }, + "updateTransforms": [ + { + "fieldPath": "b.c", + "removeAllFromArray": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove-noarray-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove-noarray-nested.json new file mode 100644 index 00000000000..7d530084d44 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove-noarray-nested.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "create: ArrayRemove cannot be anywhere inside an array value", + "comment": "There cannot be an array value anywhere on the path from the document\nroot to the ArrayRemove. Firestore transforms don't support array indexing.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, {\"b\": [\"ArrayRemove\", 1, 2, 3]}]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove-noarray.json b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove-noarray.json new file mode 100644 index 00000000000..99aea7e35cd --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove-noarray.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "create: ArrayRemove cannot be in an array value", + "comment": "ArrayRemove must be the value of a field. Firestore\ntransforms don't support array indexing.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, 2, [\"ArrayRemove\", 1, 2, 3]]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove-with-st.json b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove-with-st.json new file mode 100644 index 00000000000..56bdc435daf --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove-with-st.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "create: The ServerTimestamp sentinel cannot be in an ArrayUnion", + "comment": "The ServerTimestamp sentinel must be the value of a field. It may\nnot appear in an ArrayUnion.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [\"ArrayRemove\", 1, \"ServerTimestamp\", 3]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove.json b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove.json new file mode 100644 index 00000000000..646e259f6ff --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayremove.json @@ -0,0 +1,48 @@ +{ + "tests": [ + { + "description": "create: ArrayRemove with data", + "comment": "A key with ArrayRemove is removed from the data in the update \noperation. Instead it appears in a separate Transform operation.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": [\"ArrayRemove\", 1, 2, 3]}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "currentDocument": { + "exists": false + }, + "updateTransforms": [ + { + "fieldPath": "b", + "removeAllFromArray": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion-multi.json b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion-multi.json new file mode 100644 index 00000000000..5ba324f4297 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion-multi.json @@ -0,0 +1,64 @@ +{ + "tests": [ + { + "description": "create: multiple ArrayUnion fields", + "comment": "A document can have more than one ArrayUnion field.\nSince all the ArrayUnion fields are removed, the only field in the update is \"a\".", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": [\"ArrayUnion\", 1, 2, 3], \"c\": {\"d\": [\"ArrayUnion\", 4, 5, 6]}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "currentDocument": { + "exists": false + }, + "updateTransforms": [ + { + "fieldPath": "b", + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + }, + { + "fieldPath": "c.d", + "appendMissingElements": { + "values": [ + { + "integerValue": "4" + }, + { + "integerValue": "5" + }, + { + "integerValue": "6" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion-nested.json new file mode 100644 index 00000000000..2a215090045 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion-nested.json @@ -0,0 +1,48 @@ +{ + "tests": [ + { + "description": "create: nested ArrayUnion field", + "comment": "An ArrayUnion value can occur at any depth. In this case,\nthe transform applies to the field path \"b.c\". Since \"c\" is removed from the update,\n\"b\" becomes empty, so it is also removed from the update.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": {\"c\": [\"ArrayUnion\", 1, 2, 3]}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "currentDocument": { + "exists": false + }, + "updateTransforms": [ + { + "fieldPath": "b.c", + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion-noarray-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion-noarray-nested.json new file mode 100644 index 00000000000..b9ec5c01cbf --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion-noarray-nested.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "create: ArrayUnion cannot be anywhere inside an array value", + "comment": "There cannot be an array value anywhere on the path from the document\nroot to the ArrayUnion. Firestore transforms don't support array indexing.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, {\"b\": [\"ArrayUnion\", 1, 2, 3]}]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion-noarray.json b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion-noarray.json new file mode 100644 index 00000000000..1b85a93c45e --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion-noarray.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "create: ArrayUnion cannot be in an array value", + "comment": "ArrayUnion must be the value of a field. Firestore\ntransforms don't support array indexing.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, 2, [\"ArrayRemove\", 1, 2, 3]]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion-with-st.json b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion-with-st.json new file mode 100644 index 00000000000..2847f57490b --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion-with-st.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "create: The ServerTimestamp sentinel cannot be in an ArrayUnion", + "comment": "The ServerTimestamp sentinel must be the value of a field. It may\nnot appear in an ArrayUnion.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [\"ArrayUnion\", 1, \"ServerTimestamp\", 3]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion.json b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion.json new file mode 100644 index 00000000000..99a75feded0 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-arrayunion.json @@ -0,0 +1,48 @@ +{ + "tests": [ + { + "description": "create: ArrayUnion with data", + "comment": "A key with ArrayUnion is removed from the data in the update \noperation. Instead it appears in a separate Transform operation.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": [\"ArrayUnion\", 1, 2, 3]}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "currentDocument": { + "exists": false + }, + "updateTransforms": [ + { + "fieldPath": "b", + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-basic.json b/handwritten/firestore/dev/conformance/conformance-tests/create-basic.json new file mode 100644 index 00000000000..d67558ca13d --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-basic.json @@ -0,0 +1,30 @@ +{ + "tests": [ + { + "description": "create: basic", + "comment": "A simple call, resulting in a single update operation.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "currentDocument": { + "exists": false + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-complex.json b/handwritten/firestore/dev/conformance/conformance-tests/create-complex.json new file mode 100644 index 00000000000..a01b307f672 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-complex.json @@ -0,0 +1,63 @@ +{ + "tests": [ + { + "description": "create: complex", + "comment": "A call to a write method with complicated input data.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, 2.5], \"b\": {\"c\": [\"three\", {\"d\": true}]}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "arrayValue": { + "values": [ + { + "integerValue": "1" + }, + { + "doubleValue": 2.5 + } + ] + } + }, + "b": { + "mapValue": { + "fields": { + "c": { + "arrayValue": { + "values": [ + { + "stringValue": "three" + }, + { + "mapValue": { + "fields": { + "d": { + "booleanValue": true + } + } + } + } + ] + } + } + } + } + } + } + }, + "currentDocument": { + "exists": false + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-del-noarray-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/create-del-noarray-nested.json new file mode 100644 index 00000000000..34d8258e1b2 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-del-noarray-nested.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "create: Delete cannot be anywhere inside an array value", + "comment": "The Delete sentinel must be the value of a field. Deletes are implemented\nby turning the path to the Delete sentinel into a FieldPath, and FieldPaths do not support\narray indexing.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, {\"b\": \"Delete\"}]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-del-noarray.json b/handwritten/firestore/dev/conformance/conformance-tests/create-del-noarray.json new file mode 100644 index 00000000000..dde6b334b46 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-del-noarray.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "create: Delete cannot be in an array value", + "comment": "The Delete sentinel must be the value of a field. Deletes are\nimplemented by turning the path to the Delete sentinel into a FieldPath, and FieldPaths\ndo not support array indexing.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, 2, \"Delete\"]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-empty.json b/handwritten/firestore/dev/conformance/conformance-tests/create-empty.json new file mode 100644 index 00000000000..7d9f7f00987 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-empty.json @@ -0,0 +1,25 @@ +{ + "tests": [ + { + "description": "create: creating or setting an empty map", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": {} + }, + "currentDocument": { + "exists": false + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-nodel.json b/handwritten/firestore/dev/conformance/conformance-tests/create-nodel.json new file mode 100644 index 00000000000..dd8baaf227a --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-nodel.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "create: Delete cannot appear in data", + "comment": "The Delete sentinel cannot be used in Create, or in Set without a Merge option.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": \"Delete\"}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-nosplit.json b/handwritten/firestore/dev/conformance/conformance-tests/create-nosplit.json new file mode 100644 index 00000000000..8807af362e7 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-nosplit.json @@ -0,0 +1,39 @@ +{ + "tests": [ + { + "description": "create: don’t split on dots", + "comment": "Create and Set treat their map keys literally. They do not split on dots.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{ \"a.b\": { \"c.d\": 1 }, \"e\": 2 }", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a.b": { + "mapValue": { + "fields": { + "c.d": { + "integerValue": "1" + } + } + } + }, + "e": { + "integerValue": "2" + } + } + }, + "currentDocument": { + "exists": false + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-special-chars.json b/handwritten/firestore/dev/conformance/conformance-tests/create-special-chars.json new file mode 100644 index 00000000000..4080042000d --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-special-chars.json @@ -0,0 +1,39 @@ +{ + "tests": [ + { + "description": "create: non-alpha characters in map keys", + "comment": "Create and Set treat their map keys literally. They do not escape special characters.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{ \"*\": { \".\": 1 }, \"~\": 2 }", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "*": { + "mapValue": { + "fields": { + ".": { + "integerValue": "1" + } + } + } + }, + "~": { + "integerValue": "2" + } + } + }, + "currentDocument": { + "exists": false + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-st-alone.json b/handwritten/firestore/dev/conformance/conformance-tests/create-st-alone.json new file mode 100644 index 00000000000..177293906b4 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-st-alone.json @@ -0,0 +1,32 @@ +{ + "tests": [ + { + "description": "create: ServerTimestamp alone", + "comment": "If the only values in the input are ServerTimestamps, then no\nupdate operation should be produced.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": \"ServerTimestamp\"}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "currentDocument": { + "exists": false + }, + "update": { + "fields": {}, + "name": "projects/projectID/databases/(default)/documents/C/d" + }, + "updateTransforms": [ + { + "fieldPath": "a", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-st-multi.json b/handwritten/firestore/dev/conformance/conformance-tests/create-st-multi.json new file mode 100644 index 00000000000..41f3cd811cf --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-st-multi.json @@ -0,0 +1,40 @@ +{ + "tests": [ + { + "description": "create: multiple ServerTimestamp fields", + "comment": "A document can have more than one ServerTimestamp field.\nSince all the ServerTimestamp fields are removed, the only field in the update is \"a\".", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": \"ServerTimestamp\", \"c\": {\"d\": \"ServerTimestamp\"}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "currentDocument": { + "exists": false + }, + "updateTransforms": [ + { + "fieldPath": "b", + "setToServerValue": "REQUEST_TIME" + }, + { + "fieldPath": "c.d", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-st-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/create-st-nested.json new file mode 100644 index 00000000000..7316d916f42 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-st-nested.json @@ -0,0 +1,36 @@ +{ + "tests": [ + { + "description": "create: nested ServerTimestamp field", + "comment": "A ServerTimestamp value can occur at any depth. In this case,\nthe transform applies to the field path \"b.c\". Since \"c\" is removed from the update,\n\"b\" becomes empty, so it is also removed from the update.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": {\"c\": \"ServerTimestamp\"}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "currentDocument": { + "exists": false + }, + "updateTransforms": [ + { + "fieldPath": "b.c", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-st-noarray-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/create-st-noarray-nested.json new file mode 100644 index 00000000000..8660531dcc9 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-st-noarray-nested.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "create: ServerTimestamp cannot be anywhere inside an array value", + "comment": "There cannot be an array value anywhere on the path from the document\nroot to the ServerTimestamp sentinel. Firestore transforms don't support array indexing.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, {\"b\": \"ServerTimestamp\"}]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-st-noarray.json b/handwritten/firestore/dev/conformance/conformance-tests/create-st-noarray.json new file mode 100644 index 00000000000..31104f25613 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-st-noarray.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "create: ServerTimestamp cannot be in an array value", + "comment": "The ServerTimestamp sentinel must be the value of a field. Firestore\ntransforms don't support array indexing.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, 2, \"ServerTimestamp\"]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-st-with-empty-map.json b/handwritten/firestore/dev/conformance/conformance-tests/create-st-with-empty-map.json new file mode 100644 index 00000000000..b638a0c9db7 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-st-with-empty-map.json @@ -0,0 +1,44 @@ +{ + "tests": [ + { + "description": "create: ServerTimestamp beside an empty map", + "comment": "When a ServerTimestamp and a map both reside inside a map, the\nServerTimestamp should be stripped out but the empty map should remain.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": {\"b\": {}, \"c\": \"ServerTimestamp\"}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "mapValue": { + "fields": { + "b": { + "mapValue": { + "fields": {} + } + } + } + } + } + } + }, + "currentDocument": { + "exists": false + }, + "updateTransforms": [ + { + "fieldPath": "a.c", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/create-st.json b/handwritten/firestore/dev/conformance/conformance-tests/create-st.json new file mode 100644 index 00000000000..c4ad4be46b4 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/create-st.json @@ -0,0 +1,36 @@ +{ + "tests": [ + { + "description": "create: ServerTimestamp with data", + "comment": "A key with the special ServerTimestamp sentinel is removed from\nthe data in the update operation. Instead it appears in a separate Transform operation.\nNote that in these tests, the string \"ServerTimestamp\" should be replaced with the\nspecial ServerTimestamp value.", + "create": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": \"ServerTimestamp\"}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "currentDocument": { + "exists": false + }, + "updateTransforms": [ + { + "fieldPath": "b", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/delete-exists-precond.json b/handwritten/firestore/dev/conformance/conformance-tests/delete-exists-precond.json new file mode 100644 index 00000000000..174be0eccb0 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/delete-exists-precond.json @@ -0,0 +1,25 @@ +{ + "tests": [ + { + "description": "delete: delete with exists precondition", + "comment": "Delete supports an exists precondition.", + "delete": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "precondition": { + "exists": true + }, + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "delete": "projects/projectID/databases/(default)/documents/C/d", + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/delete-no-precond.json b/handwritten/firestore/dev/conformance/conformance-tests/delete-no-precond.json new file mode 100644 index 00000000000..96fcb39a598 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/delete-no-precond.json @@ -0,0 +1,19 @@ +{ + "tests": [ + { + "description": "delete: delete without precondition", + "comment": "An ordinary Delete call.", + "delete": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "delete": "projects/projectID/databases/(default)/documents/C/d" + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/delete-time-precond.json b/handwritten/firestore/dev/conformance/conformance-tests/delete-time-precond.json new file mode 100644 index 00000000000..160defb3fed --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/delete-time-precond.json @@ -0,0 +1,25 @@ +{ + "tests": [ + { + "description": "delete: delete with last-update-time precondition", + "comment": "Delete supports a last-update-time precondition.", + "delete": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "precondition": { + "updateTime": "1970-01-01T00:00:42Z" + }, + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "delete": "projects/projectID/databases/(default)/documents/C/d", + "currentDocument": { + "updateTime": "1970-01-01T00:00:42Z" + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/get-basic.json b/handwritten/firestore/dev/conformance/conformance-tests/get-basic.json new file mode 100644 index 00000000000..0a2cd2d4a1b --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/get-basic.json @@ -0,0 +1,14 @@ +{ + "tests": [ + { + "description": "get: get a document", + "comment": "A call to DocumentRef.Get", + "get": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "request": { + "name": "projects/projectID/databases/(default)/documents/C/d" + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/listen-add-mod-del-add.json b/handwritten/firestore/dev/conformance/conformance-tests/listen-add-mod-del-add.json new file mode 100644 index 00000000000..d05997332df --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/listen-add-mod-del-add.json @@ -0,0 +1,206 @@ +{ + "tests": [ + { + "description": "listen: add a doc, modify it, delete it, then add it again", + "comment": "Various changes to a single document.", + "listen": { + "responses": [ + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "targetChangeType": "CURRENT" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:01Z" + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:02Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:02Z" + } + }, + { + "documentDelete": { + "document": "projects/projectID/databases/(default)/documents/C/d1" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:03Z" + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:03Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:04Z" + } + } + ], + "snapshots": [ + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + } + ], + "changes": [ + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1 + } + ], + "readTime": "1970-01-01T00:00:01Z" + }, + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:02Z" + } + ], + "changes": [ + { + "kind": "MODIFIED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:02Z" + } + } + ], + "readTime": "1970-01-01T00:00:02Z" + }, + { + "changes": [ + { + "kind": "REMOVED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:02Z" + }, + "newIndex": -1 + } + ], + "readTime": "1970-01-01T00:00:03Z" + }, + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:03Z" + } + ], + "changes": [ + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:03Z" + }, + "oldIndex": -1 + } + ], + "readTime": "1970-01-01T00:00:04Z" + } + ] + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/listen-add-one.json b/handwritten/firestore/dev/conformance/conformance-tests/listen-add-one.json new file mode 100644 index 00000000000..8223180a876 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/listen-add-one.json @@ -0,0 +1,72 @@ +{ + "tests": [ + { + "description": "listen: add a doc", + "comment": "Snapshot with a single document.", + "listen": { + "responses": [ + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "targetChangeType": "CURRENT" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:02Z" + } + } + ], + "snapshots": [ + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + } + ], + "changes": [ + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1 + } + ], + "readTime": "1970-01-01T00:00:02Z" + } + ] + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/listen-add-three.json b/handwritten/firestore/dev/conformance/conformance-tests/listen-add-three.json new file mode 100644 index 00000000000..6ea117a7cc3 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/listen-add-three.json @@ -0,0 +1,156 @@ +{ + "tests": [ + { + "description": "listen: add three documents", + "comment": "A snapshot with three documents. The documents are sorted\nfirst by the \"a\" field, then by their path. The changes are ordered the same way.", + "listen": { + "responses": [ + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d3", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "targetChangeType": "CURRENT" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:02Z" + } + } + ], + "snapshots": [ + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + { + "name": "projects/projectID/databases/(default)/documents/C/d3", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + } + ], + "changes": [ + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1 + }, + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d3", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1, + "newIndex": 1 + }, + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1, + "newIndex": 2 + } + ], + "readTime": "1970-01-01T00:00:02Z" + } + ] + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/listen-doc-remove.json b/handwritten/firestore/dev/conformance/conformance-tests/listen-doc-remove.json new file mode 100644 index 00000000000..59af7d11a6e --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/listen-doc-remove.json @@ -0,0 +1,101 @@ +{ + "tests": [ + { + "description": "listen: DocumentRemove behaves like DocumentDelete", + "comment": "The DocumentRemove response behaves exactly like DocumentDelete.", + "listen": { + "responses": [ + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "targetChangeType": "CURRENT" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:01Z" + } + }, + { + "documentRemove": { + "document": "projects/projectID/databases/(default)/documents/C/d1" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:02Z" + } + } + ], + "snapshots": [ + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + } + ], + "changes": [ + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1 + } + ], + "readTime": "1970-01-01T00:00:01Z" + }, + { + "changes": [ + { + "kind": "REMOVED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "newIndex": -1 + } + ], + "readTime": "1970-01-01T00:00:02Z" + } + ] + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/listen-empty.json b/handwritten/firestore/dev/conformance/conformance-tests/listen-empty.json new file mode 100644 index 00000000000..734aa41f9ee --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/listen-empty.json @@ -0,0 +1,27 @@ +{ + "tests": [ + { + "description": "listen: no changes; empty snapshot", + "comment": "There are no changes, so the snapshot should be empty.", + "listen": { + "responses": [ + { + "targetChange": { + "targetChangeType": "CURRENT" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:01Z" + } + } + ], + "snapshots": [ + { + "readTime": "1970-01-01T00:00:01Z" + } + ] + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/listen-filter-nop.json b/handwritten/firestore/dev/conformance/conformance-tests/listen-filter-nop.json new file mode 100644 index 00000000000..a7c09e97d99 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/listen-filter-nop.json @@ -0,0 +1,203 @@ +{ + "tests": [ + { + "description": "listen: Filter response with same size is a no-op", + "comment": "A Filter response whose count matches the size of the current\nstate (docs in last snapshot + docs added - docs deleted) is a no-op.", + "listen": { + "responses": [ + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "targetChangeType": "CURRENT" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:01Z" + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d3", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "documentDelete": { + "document": "projects/projectID/databases/(default)/documents/C/d1" + } + }, + { + "filter": { + "count": 2 + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:02Z" + } + } + ], + "snapshots": [ + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + } + ], + "changes": [ + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1 + }, + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1, + "newIndex": 1 + } + ], + "readTime": "1970-01-01T00:00:01Z" + }, + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + { + "name": "projects/projectID/databases/(default)/documents/C/d3", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + } + ], + "changes": [ + { + "kind": "REMOVED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": 1, + "newIndex": -1 + }, + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d3", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1, + "newIndex": 1 + } + ], + "readTime": "1970-01-01T00:00:02Z" + } + ] + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/listen-multi-docs.json b/handwritten/firestore/dev/conformance/conformance-tests/listen-multi-docs.json new file mode 100644 index 00000000000..fe5b0f0bbf9 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/listen-multi-docs.json @@ -0,0 +1,414 @@ +{ + "tests": [ + { + "description": "listen: multiple documents, added, deleted and updated", + "comment": "Changes should be ordered with deletes first, then additions, then mods,\neach in query order.\nOld indices refer to the immediately previous state, not the previous snapshot", + "listen": { + "responses": [ + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d3", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d4", + "fields": { + "a": { + "integerValue": "2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "targetChangeType": "CURRENT" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:02Z" + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d5", + "fields": { + "a": { + "integerValue": "4" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "documentDelete": { + "document": "projects/projectID/databases/(default)/documents/C/d3" + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "-1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:03Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d6", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "documentDelete": { + "document": "projects/projectID/databases/(default)/documents/C/d2" + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d4", + "fields": { + "a": { + "integerValue": "-2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:03Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:04Z" + } + } + ], + "snapshots": [ + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + { + "name": "projects/projectID/databases/(default)/documents/C/d3", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + { + "name": "projects/projectID/databases/(default)/documents/C/d4", + "fields": { + "a": { + "integerValue": "2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + } + ], + "changes": [ + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1 + }, + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d3", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1, + "newIndex": 1 + }, + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d4", + "fields": { + "a": { + "integerValue": "2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1, + "newIndex": 2 + }, + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1, + "newIndex": 3 + } + ], + "readTime": "1970-01-01T00:00:02Z" + }, + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d4", + "fields": { + "a": { + "integerValue": "-2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:03Z" + }, + { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "-1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:03Z" + }, + { + "name": "projects/projectID/databases/(default)/documents/C/d6", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + { + "name": "projects/projectID/databases/(default)/documents/C/d5", + "fields": { + "a": { + "integerValue": "4" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + } + ], + "changes": [ + { + "kind": "REMOVED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "newIndex": -1 + }, + { + "kind": "REMOVED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d3", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "newIndex": -1 + }, + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d6", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1, + "newIndex": 2 + }, + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d5", + "fields": { + "a": { + "integerValue": "4" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1, + "newIndex": 3 + }, + { + "kind": "MODIFIED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d4", + "fields": { + "a": { + "integerValue": "-2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:03Z" + } + }, + { + "kind": "MODIFIED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "-1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:03Z" + }, + "oldIndex": 1, + "newIndex": 1 + } + ], + "readTime": "1970-01-01T00:00:04Z" + } + ] + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/listen-nocurrent.json b/handwritten/firestore/dev/conformance/conformance-tests/listen-nocurrent.json new file mode 100644 index 00000000000..158595e963d --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/listen-nocurrent.json @@ -0,0 +1,119 @@ +{ + "tests": [ + { + "description": "listen: no snapshot if we don't see CURRENT", + "comment": "If the watch state is not marked CURRENT, no snapshot is issued.", + "listen": { + "responses": [ + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:01Z" + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:02Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "targetChangeType": "CURRENT" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:02Z" + } + } + ], + "snapshots": [ + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:02Z" + } + ], + "changes": [ + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1 + }, + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:02Z" + }, + "oldIndex": -1, + "newIndex": 1 + } + ], + "readTime": "1970-01-01T00:00:02Z" + } + ] + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/listen-nomod.json b/handwritten/firestore/dev/conformance/conformance-tests/listen-nomod.json new file mode 100644 index 00000000000..0e454d51286 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/listen-nomod.json @@ -0,0 +1,123 @@ +{ + "tests": [ + { + "description": "listen: add a doc, then change it but without changing its update time", + "comment": "Document updates are recognized by a change in the update time, not the data.\nThis shouldn't actually happen. It is just a test of the update logic.", + "listen": { + "responses": [ + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "targetChangeType": "CURRENT" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:01Z" + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:02Z" + } + }, + { + "documentDelete": { + "document": "projects/projectID/databases/(default)/documents/C/d1" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:03Z" + } + } + ], + "snapshots": [ + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + } + ], + "changes": [ + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1 + } + ], + "readTime": "1970-01-01T00:00:01Z" + }, + { + "changes": [ + { + "kind": "REMOVED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "newIndex": -1 + } + ], + "readTime": "1970-01-01T00:00:03Z" + } + ] + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/listen-removed-target-ids.json b/handwritten/firestore/dev/conformance/conformance-tests/listen-removed-target-ids.json new file mode 100644 index 00000000000..57c91b7bd7f --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/listen-removed-target-ids.json @@ -0,0 +1,113 @@ +{ + "tests": [ + { + "description": "listen: DocumentChange with removed_target_id is like a delete.", + "comment": "A DocumentChange with the watch target ID in the removed_target_ids field is the\nsame as deleting a document.", + "listen": { + "responses": [ + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "targetChangeType": "CURRENT" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:01Z" + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "removedTargetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:02Z" + } + } + ], + "snapshots": [ + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + } + ], + "changes": [ + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1 + } + ], + "readTime": "1970-01-01T00:00:01Z" + }, + { + "changes": [ + { + "kind": "REMOVED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "newIndex": -1 + } + ], + "readTime": "1970-01-01T00:00:02Z" + } + ] + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/listen-reset.json b/handwritten/firestore/dev/conformance/conformance-tests/listen-reset.json new file mode 100644 index 00000000000..d988a1ba9bf --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/listen-reset.json @@ -0,0 +1,309 @@ +{ + "tests": [ + { + "description": "listen: RESET turns off CURRENT", + "comment": "A RESET message turns off the CURRENT state, and marks all documents as deleted.\n\nIf a document appeared on the stream but was never part of a snapshot (\"d3\" in this test), a reset\nwill make it disappear completely.\n\nFor a snapshot to happen at a NO_CHANGE reponse, we need to have both seen a CURRENT response, and\nhave a change from the previous snapshot. Here, after the reset, we see the same version of d2\nagain. That doesn't result in a snapshot.\n", + "listen": { + "responses": [ + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:02Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "targetChangeType": "CURRENT" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:01Z" + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d3", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:02Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "targetChangeType": "RESET" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:02Z" + } + }, + { + "targetChange": { + "targetChangeType": "CURRENT" + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:03Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:03Z" + } + }, + { + "targetChange": { + "targetChangeType": "RESET" + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:03Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "targetChangeType": "CURRENT" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:04Z" + } + }, + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d3", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:02Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:05Z" + } + } + ], + "snapshots": [ + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:02Z" + }, + { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + } + ], + "changes": [ + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "1" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:02Z" + }, + "oldIndex": -1 + }, + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1, + "newIndex": 1 + } + ], + "readTime": "1970-01-01T00:00:01Z" + }, + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:03Z" + } + ], + "changes": [ + { + "kind": "REMOVED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "2" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": 1, + "newIndex": -1 + }, + { + "kind": "MODIFIED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:03Z" + } + } + ], + "readTime": "1970-01-01T00:00:03Z" + }, + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d2", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:03Z" + }, + { + "name": "projects/projectID/databases/(default)/documents/C/d3", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:02Z" + } + ], + "changes": [ + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d3", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:02Z" + }, + "oldIndex": -1, + "newIndex": 1 + } + ], + "readTime": "1970-01-01T00:00:05Z" + } + ] + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/listen-target-add-nop.json b/handwritten/firestore/dev/conformance/conformance-tests/listen-target-add-nop.json new file mode 100644 index 00000000000..e864ea58221 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/listen-target-add-nop.json @@ -0,0 +1,81 @@ +{ + "tests": [ + { + "description": "listen: TargetChange_ADD is a no-op if it has the same target ID", + "comment": "A TargetChange_ADD response must have the same watch target ID.", + "listen": { + "responses": [ + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "targetChangeType": "CURRENT" + } + }, + { + "targetChange": { + "targetChangeType": "ADD", + "targetIds": [ + 1 + ], + "readTime": "1970-01-01T00:00:02Z" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:01Z" + } + } + ], + "snapshots": [ + { + "docs": [ + { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + } + ], + "changes": [ + { + "kind": "ADDED", + "doc": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "oldIndex": -1 + } + ], + "readTime": "1970-01-01T00:00:01Z" + } + ] + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/listen-target-add-wrong-id.json b/handwritten/firestore/dev/conformance/conformance-tests/listen-target-add-wrong-id.json new file mode 100644 index 00000000000..5bd295d5057 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/listen-target-add-wrong-id.json @@ -0,0 +1,49 @@ +{ + "tests": [ + { + "description": "listen: TargetChange_ADD is an error if it has a different target ID", + "comment": "A TargetChange_ADD response must have the same watch target ID.", + "listen": { + "responses": [ + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "targetChangeType": "CURRENT" + } + }, + { + "targetChange": { + "targetChangeType": "ADD", + "targetIds": [ + 2 + ], + "readTime": "1970-01-01T00:00:02Z" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:01Z" + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/listen-target-remove.json b/handwritten/firestore/dev/conformance/conformance-tests/listen-target-remove.json new file mode 100644 index 00000000000..2b11e280eb1 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/listen-target-remove.json @@ -0,0 +1,45 @@ +{ + "tests": [ + { + "description": "listen: TargetChange_REMOVE should not appear", + "comment": "A TargetChange_REMOVE response should never be sent.", + "listen": { + "responses": [ + { + "documentChange": { + "document": { + "name": "projects/projectID/databases/(default)/documents/C/d1", + "fields": { + "a": { + "integerValue": "3" + } + }, + "createTime": "1970-01-01T00:00:01Z", + "updateTime": "1970-01-01T00:00:01Z" + }, + "targetIds": [ + 1 + ] + } + }, + { + "targetChange": { + "targetChangeType": "CURRENT" + } + }, + { + "targetChange": { + "targetChangeType": "REMOVE" + } + }, + { + "targetChange": { + "readTime": "1970-01-01T00:00:01Z" + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-arrayremove-cursor.json b/handwritten/firestore/dev/conformance/conformance-tests/query-arrayremove-cursor.json new file mode 100644 index 00000000000..9e396b358cd --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-arrayremove-cursor.json @@ -0,0 +1,31 @@ +{ + "tests": [ + { + "description": "query: ArrayRemove in cursor method", + "comment": "ArrayRemove is not permitted in queries.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "asc" + } + }, + { + "endBefore": { + "jsonValues": [ + "[\"ArrayRemove\", 1, 2, 3]" + ] + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-arrayremove-where.json b/handwritten/firestore/dev/conformance/conformance-tests/query-arrayremove-where.json new file mode 100644 index 00000000000..c488bba85af --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-arrayremove-where.json @@ -0,0 +1,25 @@ +{ + "tests": [ + { + "description": "query: ArrayRemove in Where", + "comment": "ArrayRemove is not permitted in queries.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "where": { + "path": { + "field": [ + "a" + ] + }, + "op": "==", + "jsonValue": "[\"ArrayRemove\", 1, 2, 3]" + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-arrayunion-cursor.json b/handwritten/firestore/dev/conformance/conformance-tests/query-arrayunion-cursor.json new file mode 100644 index 00000000000..8259d31cc75 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-arrayunion-cursor.json @@ -0,0 +1,31 @@ +{ + "tests": [ + { + "description": "query: ArrayUnion in cursor method", + "comment": "ArrayUnion is not permitted in queries.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "asc" + } + }, + { + "endBefore": { + "jsonValues": [ + "[\"ArrayUnion\", 1, 2, 3]" + ] + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-arrayunion-where.json b/handwritten/firestore/dev/conformance/conformance-tests/query-arrayunion-where.json new file mode 100644 index 00000000000..9f298d84e02 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-arrayunion-where.json @@ -0,0 +1,25 @@ +{ + "tests": [ + { + "description": "query: ArrayUnion in Where", + "comment": "ArrayUnion is not permitted in queries.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "where": { + "path": { + "field": [ + "a" + ] + }, + "op": "==", + "jsonValue": "[\"ArrayUnion\", 1, 2, 3]" + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-bad-NaN.json b/handwritten/firestore/dev/conformance/conformance-tests/query-bad-NaN.json new file mode 100644 index 00000000000..47344309fe6 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-bad-NaN.json @@ -0,0 +1,25 @@ +{ + "tests": [ + { + "description": "query: where clause with non-== comparison with NaN", + "comment": "You can only compare NaN for equality.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "where": { + "path": { + "field": [ + "a" + ] + }, + "op": "\u003c", + "jsonValue": "\"NaN\"" + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-bad-null.json b/handwritten/firestore/dev/conformance/conformance-tests/query-bad-null.json new file mode 100644 index 00000000000..340afb9332d --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-bad-null.json @@ -0,0 +1,25 @@ +{ + "tests": [ + { + "description": "query: where clause with non-== comparison with Null", + "comment": "You can only compare Null for equality.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "where": { + "path": { + "field": [ + "a" + ] + }, + "op": "\u003e", + "jsonValue": "null" + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap-order.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap-order.json new file mode 100644 index 00000000000..89d2696dd49 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap-order.json @@ -0,0 +1,81 @@ +{ + "tests": [ + { + "description": "query: cursor methods with a document snapshot, existing orderBy", + "comment": "When a document snapshot is used, the client appends a __name__ order-by clause\nwith the direction of the last order-by clause.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "asc" + } + }, + { + "orderBy": { + "path": { + "field": [ + "b" + ] + }, + "direction": "desc" + } + }, + { + "startAfter": { + "docSnapshot": { + "path": "projects/projectID/databases/(default)/documents/C/D", + "jsonData": "{\"a\": 7, \"b\": 8}" + } + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "orderBy": [ + { + "field": { + "fieldPath": "a" + }, + "direction": "ASCENDING" + }, + { + "field": { + "fieldPath": "b" + }, + "direction": "DESCENDING" + }, + { + "field": { + "fieldPath": "__name__" + }, + "direction": "DESCENDING" + } + ], + "startAt": { + "values": [ + { + "integerValue": "7" + }, + { + "integerValue": "8" + }, + { + "referenceValue": "projects/projectID/databases/(default)/documents/C/D" + } + ] + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap-orderby-name.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap-orderby-name.json new file mode 100644 index 00000000000..189b302a0b7 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap-orderby-name.json @@ -0,0 +1,91 @@ +{ + "tests": [ + { + "description": "query: cursor method, doc snapshot, existing orderBy __name__", + "comment": "If there is an existing orderBy clause on __name__,\nno changes are made to the list of orderBy clauses.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "desc" + } + }, + { + "orderBy": { + "path": { + "field": [ + "__name__" + ] + }, + "direction": "asc" + } + }, + { + "startAt": { + "docSnapshot": { + "path": "projects/projectID/databases/(default)/documents/C/D", + "jsonData": "{\"a\": 7, \"b\": 8}" + } + } + }, + { + "endAt": { + "docSnapshot": { + "path": "projects/projectID/databases/(default)/documents/C/D", + "jsonData": "{\"a\": 7, \"b\": 8}" + } + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "orderBy": [ + { + "field": { + "fieldPath": "a" + }, + "direction": "DESCENDING" + }, + { + "field": { + "fieldPath": "__name__" + }, + "direction": "ASCENDING" + } + ], + "startAt": { + "values": [ + { + "integerValue": "7" + }, + { + "referenceValue": "projects/projectID/databases/(default)/documents/C/D" + } + ], + "before": true + }, + "endAt": { + "values": [ + { + "integerValue": "7" + }, + { + "referenceValue": "projects/projectID/databases/(default)/documents/C/D" + } + ] + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap-where-eq.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap-where-eq.json new file mode 100644 index 00000000000..41bc9bf1c07 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap-where-eq.json @@ -0,0 +1,65 @@ +{ + "tests": [ + { + "description": "query: cursor methods with a document snapshot and an equality where clause", + "comment": "A Where clause using equality doesn't change the implicit orderBy clauses.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "where": { + "path": { + "field": [ + "a" + ] + }, + "op": "==", + "jsonValue": "3" + } + }, + { + "endAt": { + "docSnapshot": { + "path": "projects/projectID/databases/(default)/documents/C/D", + "jsonData": "{\"a\": 7, \"b\": 8}" + } + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "where": { + "fieldFilter": { + "field": { + "fieldPath": "a" + }, + "op": "EQUAL", + "value": { + "integerValue": "3" + } + } + }, + "orderBy": [ + { + "field": { + "fieldPath": "__name__" + }, + "direction": "ASCENDING" + } + ], + "endAt": { + "values": [ + { + "referenceValue": "projects/projectID/databases/(default)/documents/C/D" + } + ] + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap-where-neq-orderby.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap-where-neq-orderby.json new file mode 100644 index 00000000000..ce99f786d39 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap-where-neq-orderby.json @@ -0,0 +1,85 @@ +{ + "tests": [ + { + "description": "query: cursor method, doc snapshot, inequality where clause, and existing orderBy clause", + "comment": "If there is an OrderBy clause, the inequality Where clause does\nnot result in a new OrderBy clause. We still add a __name__ OrderBy clause", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "desc" + } + }, + { + "where": { + "path": { + "field": [ + "a" + ] + }, + "op": "\u003c", + "jsonValue": "4" + } + }, + { + "startAt": { + "docSnapshot": { + "path": "projects/projectID/databases/(default)/documents/C/D", + "jsonData": "{\"a\": 7, \"b\": 8}" + } + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "where": { + "fieldFilter": { + "field": { + "fieldPath": "a" + }, + "op": "LESS_THAN", + "value": { + "integerValue": "4" + } + } + }, + "orderBy": [ + { + "field": { + "fieldPath": "a" + }, + "direction": "DESCENDING" + }, + { + "field": { + "fieldPath": "__name__" + }, + "direction": "DESCENDING" + } + ], + "startAt": { + "values": [ + { + "integerValue": "7" + }, + { + "referenceValue": "projects/projectID/databases/(default)/documents/C/D" + } + ], + "before": true + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap-where-neq.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap-where-neq.json new file mode 100644 index 00000000000..384bb7c2042 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap-where-neq.json @@ -0,0 +1,75 @@ +{ + "tests": [ + { + "description": "query: cursor method with a document snapshot and an inequality where clause", + "comment": "A Where clause with an inequality results in an OrderBy clause\non that clause's path, if there are no other OrderBy clauses.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "where": { + "path": { + "field": [ + "a" + ] + }, + "op": "\u003c=", + "jsonValue": "3" + } + }, + { + "endBefore": { + "docSnapshot": { + "path": "projects/projectID/databases/(default)/documents/C/D", + "jsonData": "{\"a\": 7, \"b\": 8}" + } + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "where": { + "fieldFilter": { + "field": { + "fieldPath": "a" + }, + "op": "LESS_THAN_OR_EQUAL", + "value": { + "integerValue": "3" + } + } + }, + "orderBy": [ + { + "field": { + "fieldPath": "a" + }, + "direction": "ASCENDING" + }, + { + "field": { + "fieldPath": "__name__" + }, + "direction": "ASCENDING" + } + ], + "endAt": { + "values": [ + { + "integerValue": "7" + }, + { + "referenceValue": "projects/projectID/databases/(default)/documents/C/D" + } + ], + "before": true + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap.json new file mode 100644 index 00000000000..ea84c01729e --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-docsnap.json @@ -0,0 +1,44 @@ +{ + "tests": [ + { + "description": "query: cursor methods with a document snapshot", + "comment": "When a document snapshot is used, the client appends a __name__ order-by clause.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "startAt": { + "docSnapshot": { + "path": "projects/projectID/databases/(default)/documents/C/D", + "jsonData": "{\"a\": 7, \"b\": 8}" + } + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "orderBy": [ + { + "field": { + "fieldPath": "__name__" + }, + "direction": "ASCENDING" + } + ], + "startAt": { + "values": [ + { + "referenceValue": "projects/projectID/databases/(default)/documents/C/D" + } + ], + "before": true + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-endbefore-empty-map.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-endbefore-empty-map.json new file mode 100644 index 00000000000..3d02cbca212 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-endbefore-empty-map.json @@ -0,0 +1,55 @@ +{ + "tests": [ + { + "description": "query: EndBefore with explicit empty map", + "comment": "Cursor methods are allowed to use empty maps with EndBefore. It should result in an empty map in the query.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "asc" + } + }, + { + "endBefore": { + "jsonValues": [ + "{}" + ] + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "orderBy": [ + { + "field": { + "fieldPath": "a" + }, + "direction": "ASCENDING" + } + ], + "endAt": { + "values": [ + { + "mapValue": { + "fields": {} + } + } + ], + "before": true + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-endbefore-empty.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-endbefore-empty.json new file mode 100644 index 00000000000..c491dcd7988 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-endbefore-empty.json @@ -0,0 +1,27 @@ +{ + "tests": [ + { + "description": "query: EndBefore with empty values", + "comment": "Cursor methods are not allowed to use empty values with EndBefore. It should result in an error.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "asc" + } + }, + { + "endBefore": {} + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-no-order.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-no-order.json new file mode 100644 index 00000000000..45823b22848 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-no-order.json @@ -0,0 +1,21 @@ +{ + "tests": [ + { + "description": "query: cursor method without orderBy", + "comment": "If a cursor method with a list of values is provided, there must be at least as many\nexplicit orderBy clauses as values.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "startAt": { + "jsonValues": [ + "2" + ] + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-startafter-docsnap.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-startafter-docsnap.json new file mode 100644 index 00000000000..9cc49e3a212 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-startafter-docsnap.json @@ -0,0 +1,59 @@ +{ + "tests": [ + { + "description": "query: StartAfter with document snapshot", + "comment": "Cursor methods are allowed to use document snapshots with start_after. It should result in the document's data in the query.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "asc" + } + }, + { + "startAt": { + "jsonValues": [ + "{\"a\": \"b\"}" + ] + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "orderBy": [ + { + "field": { + "fieldPath": "a" + }, + "direction": "ASCENDING" + } + ], + "startAt": { + "values": [ + { + "mapValue": { + "fields": { + "a": { + "stringValue": "b" + } + } + } + } + ], + "before": true + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-startat-empty-map.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-startat-empty-map.json new file mode 100644 index 00000000000..788588f7642 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-startat-empty-map.json @@ -0,0 +1,55 @@ +{ + "tests": [ + { + "description": "query: StartAt with explicit empty map", + "comment": "Cursor methods are allowed to use empty maps with StartAt. It should result in an empty map in the query.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "asc" + } + }, + { + "startAt": { + "jsonValues": [ + "{}" + ] + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "orderBy": [ + { + "field": { + "fieldPath": "a" + }, + "direction": "ASCENDING" + } + ], + "startAt": { + "values": [ + { + "mapValue": { + "fields": {} + } + } + ], + "before": true + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-startat-empty.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-startat-empty.json new file mode 100644 index 00000000000..c0c5a09801d --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-startat-empty.json @@ -0,0 +1,27 @@ +{ + "tests": [ + { + "description": "query: StartAt with empty values", + "comment": "Cursor methods are not allowed to use empty values with StartAt. It should result in an error.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "asc" + } + }, + { + "startAt": {} + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-vals-1a.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-vals-1a.json new file mode 100644 index 00000000000..038d177f153 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-vals-1a.json @@ -0,0 +1,68 @@ +{ + "tests": [ + { + "description": "query: StartAt/EndBefore with values", + "comment": "Cursor methods take the same number of values as there are OrderBy clauses.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "asc" + } + }, + { + "startAt": { + "jsonValues": [ + "7" + ] + } + }, + { + "endBefore": { + "jsonValues": [ + "9" + ] + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "orderBy": [ + { + "field": { + "fieldPath": "a" + }, + "direction": "ASCENDING" + } + ], + "startAt": { + "values": [ + { + "integerValue": "7" + } + ], + "before": true + }, + "endAt": { + "values": [ + { + "integerValue": "9" + } + ], + "before": true + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-vals-1b.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-vals-1b.json new file mode 100644 index 00000000000..089cff93bde --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-vals-1b.json @@ -0,0 +1,66 @@ +{ + "tests": [ + { + "description": "query: StartAfter/EndAt with values", + "comment": "Cursor methods take the same number of values as there are OrderBy clauses.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "asc" + } + }, + { + "startAfter": { + "jsonValues": [ + "7" + ] + } + }, + { + "endAt": { + "jsonValues": [ + "9" + ] + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "orderBy": [ + { + "field": { + "fieldPath": "a" + }, + "direction": "ASCENDING" + } + ], + "startAt": { + "values": [ + { + "integerValue": "7" + } + ] + }, + "endAt": { + "values": [ + { + "integerValue": "9" + } + ] + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-vals-2.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-vals-2.json new file mode 100644 index 00000000000..8554b436039 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-vals-2.json @@ -0,0 +1,91 @@ +{ + "tests": [ + { + "description": "query: Start/End with two values", + "comment": "Cursor methods take the same number of values as there are OrderBy clauses.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "asc" + } + }, + { + "orderBy": { + "path": { + "field": [ + "b" + ] + }, + "direction": "desc" + } + }, + { + "startAt": { + "jsonValues": [ + "7", + "8" + ] + } + }, + { + "endAt": { + "jsonValues": [ + "9", + "10" + ] + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "orderBy": [ + { + "field": { + "fieldPath": "a" + }, + "direction": "ASCENDING" + }, + { + "field": { + "fieldPath": "b" + }, + "direction": "DESCENDING" + } + ], + "startAt": { + "values": [ + { + "integerValue": "7" + }, + { + "integerValue": "8" + } + ], + "before": true + }, + "endAt": { + "values": [ + { + "integerValue": "9" + }, + { + "integerValue": "10" + } + ] + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-vals-docid.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-vals-docid.json new file mode 100644 index 00000000000..6492b3f1952 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-vals-docid.json @@ -0,0 +1,67 @@ +{ + "tests": [ + { + "description": "query: cursor methods with __name__", + "comment": "Cursor values corresponding to a __name__ field take the document path relative to the\nquery's collection.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "__name__" + ] + }, + "direction": "asc" + } + }, + { + "startAfter": { + "jsonValues": [ + "\"D1\"" + ] + } + }, + { + "endBefore": { + "jsonValues": [ + "\"D2\"" + ] + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "orderBy": [ + { + "field": { + "fieldPath": "__name__" + }, + "direction": "ASCENDING" + } + ], + "startAt": { + "values": [ + { + "referenceValue": "projects/projectID/databases/(default)/documents/C/D1" + } + ] + }, + "endAt": { + "values": [ + { + "referenceValue": "projects/projectID/databases/(default)/documents/C/D2" + } + ], + "before": true + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-vals-last-wins.json b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-vals-last-wins.json new file mode 100644 index 00000000000..4a46b2f789d --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-cursor-vals-last-wins.json @@ -0,0 +1,82 @@ +{ + "tests": [ + { + "description": "query: cursor methods, last one wins", + "comment": "When multiple Start* or End* calls occur, the values of the last one are used.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "asc" + } + }, + { + "startAfter": { + "jsonValues": [ + "1" + ] + } + }, + { + "startAt": { + "jsonValues": [ + "2" + ] + } + }, + { + "endAt": { + "jsonValues": [ + "3" + ] + } + }, + { + "endBefore": { + "jsonValues": [ + "4" + ] + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "orderBy": [ + { + "field": { + "fieldPath": "a" + }, + "direction": "ASCENDING" + } + ], + "startAt": { + "values": [ + { + "integerValue": "2" + } + ], + "before": true + }, + "endAt": { + "values": [ + { + "integerValue": "4" + } + ], + "before": true + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-del-cursor.json b/handwritten/firestore/dev/conformance/conformance-tests/query-del-cursor.json new file mode 100644 index 00000000000..921ace131d2 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-del-cursor.json @@ -0,0 +1,31 @@ +{ + "tests": [ + { + "description": "query: Delete in cursor method", + "comment": "Sentinel values are not permitted in queries.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "asc" + } + }, + { + "endBefore": { + "jsonValues": [ + "\"Delete\"" + ] + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-del-where.json b/handwritten/firestore/dev/conformance/conformance-tests/query-del-where.json new file mode 100644 index 00000000000..2075e357807 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-del-where.json @@ -0,0 +1,25 @@ +{ + "tests": [ + { + "description": "query: Delete in Where", + "comment": "Sentinel values are not permitted in queries.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "where": { + "path": { + "field": [ + "a" + ] + }, + "op": "==", + "jsonValue": "\"Delete\"" + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-invalid-operator.json b/handwritten/firestore/dev/conformance/conformance-tests/query-invalid-operator.json new file mode 100644 index 00000000000..0acfeae67ef --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-invalid-operator.json @@ -0,0 +1,25 @@ +{ + "tests": [ + { + "description": "query: invalid operator in Where clause", + "comment": "The |~| operator is not supported.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "where": { + "path": { + "field": [ + "a" + ] + }, + "op": "|~|", + "jsonValue": "4" + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-invalid-path-order.json b/handwritten/firestore/dev/conformance/conformance-tests/query-invalid-path-order.json new file mode 100644 index 00000000000..d0c5ba654f6 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-invalid-path-order.json @@ -0,0 +1,25 @@ +{ + "tests": [ + { + "description": "query: invalid path in OrderBy clause", + "comment": "The path has an empty component.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "*", + "" + ] + }, + "direction": "asc" + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-invalid-path-select.json b/handwritten/firestore/dev/conformance/conformance-tests/query-invalid-path-select.json new file mode 100644 index 00000000000..fa18f72817a --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-invalid-path-select.json @@ -0,0 +1,26 @@ +{ + "tests": [ + { + "description": "query: invalid path in Where clause", + "comment": "The path has an empty component.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "select": { + "fields": [ + { + "field": [ + "*", + "" + ] + } + ] + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-invalid-path-where.json b/handwritten/firestore/dev/conformance/conformance-tests/query-invalid-path-where.json new file mode 100644 index 00000000000..a5b2add3336 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-invalid-path-where.json @@ -0,0 +1,26 @@ +{ + "tests": [ + { + "description": "query: invalid path in Where clause", + "comment": "The path has an empty component.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "where": { + "path": { + "field": [ + "*", + "" + ] + }, + "op": "==", + "jsonValue": "4" + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-offset-limit-last-wins.json b/handwritten/firestore/dev/conformance/conformance-tests/query-offset-limit-last-wins.json new file mode 100644 index 00000000000..8788826081e --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-offset-limit-last-wins.json @@ -0,0 +1,34 @@ +{ + "tests": [ + { + "description": "query: multiple Offset and Limit clauses", + "comment": "With multiple Offset or Limit clauses, the last one wins.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "offset": 2 + }, + { + "limit": 3 + }, + { + "limit": 4 + }, + { + "offset": 5 + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "offset": 5, + "limit": 4 + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-offset-limit.json b/handwritten/firestore/dev/conformance/conformance-tests/query-offset-limit.json new file mode 100644 index 00000000000..3429dce0e89 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-offset-limit.json @@ -0,0 +1,28 @@ +{ + "tests": [ + { + "description": "query: Offset and Limit clauses", + "comment": "Offset and Limit clauses.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "offset": 2 + }, + { + "limit": 3 + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "offset": 2, + "limit": 3 + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-order.json b/handwritten/firestore/dev/conformance/conformance-tests/query-order.json new file mode 100644 index 00000000000..f6670f060db --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-order.json @@ -0,0 +1,54 @@ +{ + "tests": [ + { + "description": "query: basic OrderBy clauses", + "comment": "Multiple OrderBy clauses combine.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "b" + ] + }, + "direction": "asc" + } + }, + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "desc" + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "orderBy": [ + { + "field": { + "fieldPath": "b" + }, + "direction": "ASCENDING" + }, + { + "field": { + "fieldPath": "a" + }, + "direction": "DESCENDING" + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-select-empty.json b/handwritten/firestore/dev/conformance/conformance-tests/query-select-empty.json new file mode 100644 index 00000000000..8dda741a63e --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-select-empty.json @@ -0,0 +1,32 @@ +{ + "tests": [ + { + "description": "query: empty Select clause", + "comment": "An empty Select clause selects just the document ID.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "select": { + "fields": [] + } + } + ], + "query": { + "select": { + "fields": [ + { + "fieldPath": "__name__" + } + ] + }, + "from": [ + { + "collectionId": "C" + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-select-last-wins.json b/handwritten/firestore/dev/conformance/conformance-tests/query-select-last-wins.json new file mode 100644 index 00000000000..9df4d13d054 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-select-last-wins.json @@ -0,0 +1,54 @@ +{ + "tests": [ + { + "description": "query: two Select clauses", + "comment": "The last Select clause is the only one used.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "select": { + "fields": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + } + ] + } + }, + { + "select": { + "fields": [ + { + "field": [ + "c" + ] + } + ] + } + } + ], + "query": { + "select": { + "fields": [ + { + "fieldPath": "c" + } + ] + }, + "from": [ + { + "collectionId": "C" + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-select.json b/handwritten/firestore/dev/conformance/conformance-tests/query-select.json new file mode 100644 index 00000000000..cfaab8f1f55 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-select.json @@ -0,0 +1,46 @@ +{ + "tests": [ + { + "description": "query: Select clause with some fields", + "comment": "An ordinary Select clause.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "select": { + "fields": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + } + ] + } + } + ], + "query": { + "select": { + "fields": [ + { + "fieldPath": "a" + }, + { + "fieldPath": "b" + } + ] + }, + "from": [ + { + "collectionId": "C" + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-st-cursor.json b/handwritten/firestore/dev/conformance/conformance-tests/query-st-cursor.json new file mode 100644 index 00000000000..d42416ee1dd --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-st-cursor.json @@ -0,0 +1,31 @@ +{ + "tests": [ + { + "description": "query: ServerTimestamp in cursor method", + "comment": "Sentinel values are not permitted in queries.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "orderBy": { + "path": { + "field": [ + "a" + ] + }, + "direction": "asc" + } + }, + { + "endBefore": { + "jsonValues": [ + "\"ServerTimestamp\"" + ] + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-st-where.json b/handwritten/firestore/dev/conformance/conformance-tests/query-st-where.json new file mode 100644 index 00000000000..1584bb9b47b --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-st-where.json @@ -0,0 +1,25 @@ +{ + "tests": [ + { + "description": "query: ServerTimestamp in Where", + "comment": "Sentinel values are not permitted in queries.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "where": { + "path": { + "field": [ + "a" + ] + }, + "op": "==", + "jsonValue": "\"ServerTimestamp\"" + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-where-2.json b/handwritten/firestore/dev/conformance/conformance-tests/query-where-2.json new file mode 100644 index 00000000000..a78beb26464 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-where-2.json @@ -0,0 +1,71 @@ +{ + "tests": [ + { + "description": "query: two Where clauses", + "comment": "Multiple Where clauses are combined into a composite filter.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "where": { + "path": { + "field": [ + "a" + ] + }, + "op": "\u003e=", + "jsonValue": "5" + } + }, + { + "where": { + "path": { + "field": [ + "b" + ] + }, + "op": "\u003c", + "jsonValue": "\"foo\"" + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "where": { + "compositeFilter": { + "op": "AND", + "filters": [ + { + "fieldFilter": { + "field": { + "fieldPath": "a" + }, + "op": "GREATER_THAN_OR_EQUAL", + "value": { + "integerValue": "5" + } + } + }, + { + "fieldFilter": { + "field": { + "fieldPath": "b" + }, + "op": "LESS_THAN", + "value": { + "stringValue": "foo" + } + } + } + ] + } + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-where-NaN.json b/handwritten/firestore/dev/conformance/conformance-tests/query-where-NaN.json new file mode 100644 index 00000000000..c091fe5c091 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-where-NaN.json @@ -0,0 +1,39 @@ +{ + "tests": [ + { + "description": "query: a Where clause comparing to NaN", + "comment": "A Where clause that tests for equality with NaN results in a unary filter.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "where": { + "path": { + "field": [ + "a" + ] + }, + "op": "==", + "jsonValue": "\"NaN\"" + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "where": { + "unaryFilter": { + "op": "IS_NAN", + "field": { + "fieldPath": "a" + } + } + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-where-null.json b/handwritten/firestore/dev/conformance/conformance-tests/query-where-null.json new file mode 100644 index 00000000000..6862dd97f6c --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-where-null.json @@ -0,0 +1,39 @@ +{ + "tests": [ + { + "description": "query: a Where clause comparing to null", + "comment": "A Where clause that tests for equality with null results in a unary filter.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "where": { + "path": { + "field": [ + "a" + ] + }, + "op": "==", + "jsonValue": "null" + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "where": { + "unaryFilter": { + "op": "IS_NULL", + "field": { + "fieldPath": "a" + } + } + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-where.json b/handwritten/firestore/dev/conformance/conformance-tests/query-where.json new file mode 100644 index 00000000000..b132c3030f0 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-where.json @@ -0,0 +1,42 @@ +{ + "tests": [ + { + "description": "query: Where clause", + "comment": "A simple Where clause.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "where": { + "path": { + "field": [ + "a" + ] + }, + "op": "\u003e", + "jsonValue": "5" + } + } + ], + "query": { + "from": [ + { + "collectionId": "C" + } + ], + "where": { + "fieldFilter": { + "field": { + "fieldPath": "a" + }, + "op": "GREATER_THAN", + "value": { + "integerValue": "5" + } + } + } + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/query-wrong-collection.json b/handwritten/firestore/dev/conformance/conformance-tests/query-wrong-collection.json new file mode 100644 index 00000000000..6a677f53dec --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/query-wrong-collection.json @@ -0,0 +1,22 @@ +{ + "tests": [ + { + "description": "query: doc snapshot with wrong collection in cursor method", + "comment": "If a document snapshot is passed to a Start*/End* method, it must be in the\nsame collection as the query.", + "query": { + "collPath": "projects/projectID/databases/(default)/documents/C", + "clauses": [ + { + "endBefore": { + "docSnapshot": { + "path": "projects/projectID/databases/(default)/documents/C2/D", + "jsonData": "{\"a\": 7, \"b\": 8}" + } + } + } + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-all-transforms.json b/handwritten/firestore/dev/conformance/conformance-tests/set-all-transforms.json new file mode 100644 index 00000000000..a26b51b0071 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-all-transforms.json @@ -0,0 +1,65 @@ +{ + "tests": [ + { + "description": "set: all transforms in a single call", + "comment": "A document can be created with any amount of transforms.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": \"ServerTimestamp\", \"c\": [\"ArrayUnion\", 1, 2, 3], \"d\": [\"ArrayRemove\", 4, 5, 6]}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateTransforms": [ + { + "fieldPath": "b", + "setToServerValue": "REQUEST_TIME" + }, + { + "fieldPath": "c", + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + }, + { + "fieldPath": "d", + "removeAllFromArray": { + "values": [ + { + "integerValue": "4" + }, + { + "integerValue": "5" + }, + { + "integerValue": "6" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove-multi.json b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove-multi.json new file mode 100644 index 00000000000..dc2ace22f84 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove-multi.json @@ -0,0 +1,61 @@ +{ + "tests": [ + { + "description": "set: multiple ArrayRemove fields", + "comment": "A document can have more than one ArrayRemove field.\nSince all the ArrayRemove fields are removed, the only field in the update is \"a\".", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": [\"ArrayRemove\", 1, 2, 3], \"c\": {\"d\": [\"ArrayRemove\", 4, 5, 6]}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateTransforms": [ + { + "fieldPath": "b", + "removeAllFromArray": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + }, + { + "fieldPath": "c.d", + "removeAllFromArray": { + "values": [ + { + "integerValue": "4" + }, + { + "integerValue": "5" + }, + { + "integerValue": "6" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove-nested.json new file mode 100644 index 00000000000..1e25b8f26b3 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove-nested.json @@ -0,0 +1,45 @@ +{ + "tests": [ + { + "description": "set: nested ArrayRemove field", + "comment": "An ArrayRemove value can occur at any depth. In this case,\nthe transform applies to the field path \"b.c\". Since \"c\" is removed from the update,\n\"b\" becomes empty, so it is also removed from the update.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": {\"c\": [\"ArrayRemove\", 1, 2, 3]}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateTransforms": [ + { + "fieldPath": "b.c", + "removeAllFromArray": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove-noarray-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove-noarray-nested.json new file mode 100644 index 00000000000..96965faa660 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove-noarray-nested.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "set: ArrayRemove cannot be anywhere inside an array value", + "comment": "There cannot be an array value anywhere on the path from the document\nroot to the ArrayRemove. Firestore transforms don't support array indexing.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, {\"b\": [\"ArrayRemove\", 1, 2, 3]}]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove-noarray.json b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove-noarray.json new file mode 100644 index 00000000000..cd0e04468bd --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove-noarray.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "set: ArrayRemove cannot be in an array value", + "comment": "ArrayRemove must be the value of a field. Firestore\ntransforms don't support array indexing.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, 2, [\"ArrayRemove\", 1, 2, 3]]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove-with-st.json b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove-with-st.json new file mode 100644 index 00000000000..146e41fdf43 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove-with-st.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "set: The ServerTimestamp sentinel cannot be in an ArrayUnion", + "comment": "The ServerTimestamp sentinel must be the value of a field. It may\nnot appear in an ArrayUnion.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [\"ArrayRemove\", 1, \"ServerTimestamp\", 3]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove.json b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove.json new file mode 100644 index 00000000000..e0506b22be4 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayremove.json @@ -0,0 +1,45 @@ +{ + "tests": [ + { + "description": "set: ArrayRemove with data", + "comment": "A key with ArrayRemove is removed from the data in the update \noperation. Instead it appears in a separate Transform operation.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": [\"ArrayRemove\", 1, 2, 3]}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateTransforms": [ + { + "fieldPath": "b", + "removeAllFromArray": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-merge.json b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-merge.json new file mode 100644 index 00000000000..46c2fbfb322 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-merge.json @@ -0,0 +1,48 @@ +{ + "tests": [ + { + "description": "set: merge ArrayUnion field", + "comment": "An ArrayUnion value can occur at any depth. In this case,\nthe transform applies to the field path \"b.c\". \"a\" is left alone and remains in the object.", + "set": { + "option": { + "all": true + }, + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": {\"c\": [\"ArrayUnion\", \"foo\", \"bar\"]}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": ["a"] + }, + "updateTransforms": [ + { + "fieldPath": "b.c", + "appendMissingElements": { + "values": [ + { + "stringValue": "foo" + }, + { + "stringValue": "bar" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-multi.json b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-multi.json new file mode 100644 index 00000000000..502d7dc7dff --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-multi.json @@ -0,0 +1,61 @@ +{ + "tests": [ + { + "description": "set: multiple ArrayUnion fields", + "comment": "A document can have more than one ArrayUnion field.\nSince all the ArrayUnion fields are removed, the only field in the update is \"a\".", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": [\"ArrayUnion\", 1, 2, 3], \"c\": {\"d\": [\"ArrayUnion\", 4, 5, 6]}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateTransforms": [ + { + "fieldPath": "b", + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + }, + { + "fieldPath": "c.d", + "appendMissingElements": { + "values": [ + { + "integerValue": "4" + }, + { + "integerValue": "5" + }, + { + "integerValue": "6" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-nested.json new file mode 100644 index 00000000000..7084e6bcd91 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-nested.json @@ -0,0 +1,45 @@ +{ + "tests": [ + { + "description": "set: nested ArrayUnion field", + "comment": "An ArrayUnion value can occur at any depth. In this case,\nthe transform applies to the field path \"b.c\". Since \"c\" is removed from the update,\n\"b\" becomes empty, so it is also removed from the update.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": {\"c\": [\"ArrayUnion\", 1, 2, 3]}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateTransforms": [ + { + "fieldPath": "b.c", + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-noarray-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-noarray-nested.json new file mode 100644 index 00000000000..c9b1385e03a --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-noarray-nested.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "set: ArrayUnion cannot be anywhere inside an array value", + "comment": "There cannot be an array value anywhere on the path from the document\nroot to the ArrayUnion. Firestore transforms don't support array indexing.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, {\"b\": [\"ArrayUnion\", 1, 2, 3]}]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-noarray.json b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-noarray.json new file mode 100644 index 00000000000..4379578bd83 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-noarray.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "set: ArrayUnion cannot be in an array value", + "comment": "ArrayUnion must be the value of a field. Firestore\ntransforms don't support array indexing.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, 2, [\"ArrayRemove\", 1, 2, 3]]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-with-st.json b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-with-st.json new file mode 100644 index 00000000000..d65436af205 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion-with-st.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "set: The ServerTimestamp sentinel cannot be in an ArrayUnion", + "comment": "The ServerTimestamp sentinel must be the value of a field. It may\nnot appear in an ArrayUnion.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [\"ArrayUnion\", 1, \"ServerTimestamp\", 3]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion.json b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion.json new file mode 100644 index 00000000000..af12b33dd03 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-arrayunion.json @@ -0,0 +1,45 @@ +{ + "tests": [ + { + "description": "set: ArrayUnion with data", + "comment": "A key with ArrayUnion is removed from the data in the update \noperation. Instead it appears in a separate Transform operation.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": [\"ArrayUnion\", 1, 2, 3]}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateTransforms": [ + { + "fieldPath": "b", + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-basic.json b/handwritten/firestore/dev/conformance/conformance-tests/set-basic.json new file mode 100644 index 00000000000..f322509126d --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-basic.json @@ -0,0 +1,27 @@ +{ + "tests": [ + { + "description": "set: basic", + "comment": "A simple call, resulting in a single update operation.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-complex.json b/handwritten/firestore/dev/conformance/conformance-tests/set-complex.json new file mode 100644 index 00000000000..aa871ddae6c --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-complex.json @@ -0,0 +1,60 @@ +{ + "tests": [ + { + "description": "set: complex", + "comment": "A call to a write method with complicated input data.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, 2.5], \"b\": {\"c\": [\"three\", {\"d\": true}]}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "arrayValue": { + "values": [ + { + "integerValue": "1" + }, + { + "doubleValue": 2.5 + } + ] + } + }, + "b": { + "mapValue": { + "fields": { + "c": { + "arrayValue": { + "values": [ + { + "stringValue": "three" + }, + { + "mapValue": { + "fields": { + "d": { + "booleanValue": true + } + } + } + } + ] + } + } + } + } + } + } + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-del-merge-alone.json b/handwritten/firestore/dev/conformance/conformance-tests/set-del-merge-alone.json new file mode 100644 index 00000000000..7a8ba5d5458 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-del-merge-alone.json @@ -0,0 +1,37 @@ +{ + "tests": [ + { + "description": "set-merge: Delete with merge", + "comment": "A Delete sentinel can appear with a merge option. If the delete\npaths are the only ones to be merged, then no document is sent, just an update mask.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "fields": [ + { + "field": [ + "b", + "c" + ] + } + ] + }, + "jsonData": "{\"a\": 1, \"b\": {\"c\": \"Delete\"}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d" + }, + "updateMask": { + "fieldPaths": [ + "b.c" + ] + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-del-merge.json b/handwritten/firestore/dev/conformance/conformance-tests/set-del-merge.json new file mode 100644 index 00000000000..6a5759c1255 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-del-merge.json @@ -0,0 +1,48 @@ +{ + "tests": [ + { + "description": "set-merge: Delete with merge", + "comment": "A Delete sentinel can appear with a merge option.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "fields": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b", + "c" + ] + } + ] + }, + "jsonData": "{\"a\": 1, \"b\": {\"c\": \"Delete\"}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "b.c" + ] + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-del-mergeall.json b/handwritten/firestore/dev/conformance/conformance-tests/set-del-mergeall.json new file mode 100644 index 00000000000..6106a3e4f22 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-del-mergeall.json @@ -0,0 +1,36 @@ +{ + "tests": [ + { + "description": "set: Delete with MergeAll", + "comment": "A Delete sentinel can appear with a mergeAll option.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "all": true + }, + "jsonData": "{\"a\": 1, \"b\": {\"c\": \"Delete\"}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "b.c" + ] + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-del-noarray-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/set-del-noarray-nested.json new file mode 100644 index 00000000000..5a2303284e4 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-del-noarray-nested.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "set: Delete cannot be anywhere inside an array value", + "comment": "The Delete sentinel must be the value of a field. Deletes are implemented\nby turning the path to the Delete sentinel into a FieldPath, and FieldPaths do not support\narray indexing.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, {\"b\": \"Delete\"}]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-del-noarray.json b/handwritten/firestore/dev/conformance/conformance-tests/set-del-noarray.json new file mode 100644 index 00000000000..dee9c75f697 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-del-noarray.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "set: Delete cannot be in an array value", + "comment": "The Delete sentinel must be the value of a field. Deletes are\nimplemented by turning the path to the Delete sentinel into a FieldPath, and FieldPaths\ndo not support array indexing.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, 2, \"Delete\"]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-del-nomerge.json b/handwritten/firestore/dev/conformance/conformance-tests/set-del-nomerge.json new file mode 100644 index 00000000000..67e3b74b860 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-del-nomerge.json @@ -0,0 +1,22 @@ +{ + "tests": [ + { + "description": "set-merge: Delete cannot appear in an unmerged field", + "comment": "The client signals an error if the Delete sentinel is in the\ninput data, but not selected by a merge option, because this is most likely a programming\nbug.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "fields": [ + { + "field": [ + "a" + ] + } + ] + }, + "jsonData": "{\"a\": 1, \"b\": \"Delete\"}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-del-nonleaf.json b/handwritten/firestore/dev/conformance/conformance-tests/set-del-nonleaf.json new file mode 100644 index 00000000000..67c864957ca --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-del-nonleaf.json @@ -0,0 +1,22 @@ +{ + "tests": [ + { + "description": "set-merge: Delete cannot appear as part of a merge path", + "comment": "If a Delete is part of the value at a merge path, then the user is\nconfused: their merge path says \"replace this entire value\" but their Delete says\n\"delete this part of the value\". This should be an error, just as if they specified Delete\nin a Set with no merge.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "fields": [ + { + "field": [ + "h" + ] + } + ] + }, + "jsonData": "{\"h\": {\"g\": \"Delete\"}}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-del-wo-merge.json b/handwritten/firestore/dev/conformance/conformance-tests/set-del-wo-merge.json new file mode 100644 index 00000000000..32d860a626d --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-del-wo-merge.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "set: Delete cannot appear unless a merge option is specified", + "comment": "Without a merge option, Set replaces the document with the input\ndata. A Delete sentinel in the data makes no sense in this case.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": \"Delete\"}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-empty.json b/handwritten/firestore/dev/conformance/conformance-tests/set-empty.json new file mode 100644 index 00000000000..924992caf30 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-empty.json @@ -0,0 +1,22 @@ +{ + "tests": [ + { + "description": "set: creating or setting an empty map", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": {} + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-merge-fp.json b/handwritten/firestore/dev/conformance/conformance-tests/set-merge-fp.json new file mode 100644 index 00000000000..8a5b0faa6e2 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-merge-fp.json @@ -0,0 +1,48 @@ +{ + "tests": [ + { + "description": "set-merge: Merge with FieldPaths", + "comment": "A merge with fields that use special characters.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "fields": [ + { + "field": [ + "*", + "~" + ] + } + ] + }, + "jsonData": "{\"*\": {\"~\": true}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "*": { + "mapValue": { + "fields": { + "~": { + "booleanValue": true + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "`*`.`~`" + ] + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-merge-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/set-merge-nested.json new file mode 100644 index 00000000000..8ebec8fda27 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-merge-nested.json @@ -0,0 +1,48 @@ +{ + "tests": [ + { + "description": "set-merge: Merge with a nested field", + "comment": "A merge option where the field is not at top level.\nOnly fields mentioned in the option are present in the update operation.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "fields": [ + { + "field": [ + "h", + "g" + ] + } + ] + }, + "jsonData": "{\"h\": {\"g\": 4, \"f\": 5}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "h": { + "mapValue": { + "fields": { + "g": { + "integerValue": "4" + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "h.g" + ] + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-merge-nonleaf.json b/handwritten/firestore/dev/conformance/conformance-tests/set-merge-nonleaf.json new file mode 100644 index 00000000000..d115e12c2ab --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-merge-nonleaf.json @@ -0,0 +1,50 @@ +{ + "tests": [ + { + "description": "set-merge: Merge field is not a leaf", + "comment": "If a field path is in a merge option, the value at that path\nreplaces the stored value. That is true even if the value is complex.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "fields": [ + { + "field": [ + "h" + ] + } + ] + }, + "jsonData": "{\"h\": {\"f\": 5, \"g\": 6}, \"e\": 7}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "h": { + "mapValue": { + "fields": { + "f": { + "integerValue": "5" + }, + "g": { + "integerValue": "6" + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "h" + ] + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-merge-prefix.json b/handwritten/firestore/dev/conformance/conformance-tests/set-merge-prefix.json new file mode 100644 index 00000000000..a09e4db5098 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-merge-prefix.json @@ -0,0 +1,28 @@ +{ + "tests": [ + { + "description": "set-merge: One merge path cannot be the prefix of another", + "comment": "The prefix would make the other path meaningless, so this is\nprobably a programming error.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "fields": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "a", + "b" + ] + } + ] + }, + "jsonData": "{\"a\": {\"b\": 1}}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-merge-present.json b/handwritten/firestore/dev/conformance/conformance-tests/set-merge-present.json new file mode 100644 index 00000000000..b501b23d03f --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-merge-present.json @@ -0,0 +1,27 @@ +{ + "tests": [ + { + "description": "set-merge: Merge fields must all be present in data", + "comment": "The client signals an error if a merge option mentions a path\nthat is not in the input data.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "fields": [ + { + "field": [ + "b" + ] + }, + { + "field": [ + "a" + ] + } + ] + }, + "jsonData": "{\"a\": 1}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-merge.json b/handwritten/firestore/dev/conformance/conformance-tests/set-merge.json new file mode 100644 index 00000000000..8ce730e840a --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-merge.json @@ -0,0 +1,41 @@ +{ + "tests": [ + { + "description": "set-merge: Merge with a field", + "comment": "Fields in the input data but not in a merge option are pruned.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "fields": [ + { + "field": [ + "a" + ] + } + ] + }, + "jsonData": "{\"a\": 1, \"b\": 2}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-mergeall-empty.json b/handwritten/firestore/dev/conformance/conformance-tests/set-mergeall-empty.json new file mode 100644 index 00000000000..e541ad8c9a7 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-mergeall-empty.json @@ -0,0 +1,29 @@ +{ + "tests": [ + { + "description": "set: MergeAll can be specified with empty data.", + "comment": "This is a valid call that can be used to ensure a document exists.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "all": true + }, + "jsonData": "{}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": {} + }, + "updateMask": { + "fieldPaths": [] + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-mergeall-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/set-mergeall-nested.json new file mode 100644 index 00000000000..c70ec691e29 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-mergeall-nested.json @@ -0,0 +1,45 @@ +{ + "tests": [ + { + "description": "set: MergeAll with nested fields", + "comment": "MergeAll with nested fields results in an update mask that\nincludes entries for all the leaf fields.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "all": true + }, + "jsonData": "{\"h\": { \"g\": 3, \"f\": 4 }}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "h": { + "mapValue": { + "fields": { + "f": { + "integerValue": "4" + }, + "g": { + "integerValue": "3" + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "h.f", + "h.g" + ] + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-mergeall.json b/handwritten/firestore/dev/conformance/conformance-tests/set-mergeall.json new file mode 100644 index 00000000000..55a2377cb51 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-mergeall.json @@ -0,0 +1,39 @@ +{ + "tests": [ + { + "description": "set: MergeAll", + "comment": "The MergeAll option with a simple piece of data.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "all": true + }, + "jsonData": "{\"a\": 1, \"b\": 2}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + }, + "b": { + "integerValue": "2" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "b" + ] + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-nodel.json b/handwritten/firestore/dev/conformance/conformance-tests/set-nodel.json new file mode 100644 index 00000000000..5580bc04f64 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-nodel.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "set: Delete cannot appear in data", + "comment": "The Delete sentinel cannot be used in Create, or in Set without a Merge option.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": \"Delete\"}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-nosplit.json b/handwritten/firestore/dev/conformance/conformance-tests/set-nosplit.json new file mode 100644 index 00000000000..3866027b9b5 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-nosplit.json @@ -0,0 +1,36 @@ +{ + "tests": [ + { + "description": "set: don’t split on dots", + "comment": "Create and Set treat their map keys literally. They do not split on dots.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{ \"a.b\": { \"c.d\": 1 }, \"e\": 2 }", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a.b": { + "mapValue": { + "fields": { + "c.d": { + "integerValue": "1" + } + } + } + }, + "e": { + "integerValue": "2" + } + } + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-special-chars.json b/handwritten/firestore/dev/conformance/conformance-tests/set-special-chars.json new file mode 100644 index 00000000000..865ffcd9dc7 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-special-chars.json @@ -0,0 +1,36 @@ +{ + "tests": [ + { + "description": "set: non-alpha characters in map keys", + "comment": "Create and Set treat their map keys literally. They do not escape special characters.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{ \"*\": { \".\": 1 }, \"~\": 2 }", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "*": { + "mapValue": { + "fields": { + ".": { + "integerValue": "1" + } + } + } + }, + "~": { + "integerValue": "2" + } + } + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-st-alone-mergeall.json b/handwritten/firestore/dev/conformance/conformance-tests/set-st-alone-mergeall.json new file mode 100644 index 00000000000..f6b60af8109 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-st-alone-mergeall.json @@ -0,0 +1,35 @@ +{ + "tests": [ + { + "description": "set: ServerTimestamp alone with MergeAll", + "comment": "If the only values in the input are ServerTimestamps, then no\nupdate operation should be produced.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "all": true + }, + "jsonData": "{\"a\": \"ServerTimestamp\"}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "fields": {}, + "name": "projects/projectID/databases/(default)/documents/C/d" + }, + "updateMask": { + "fieldPaths": [] + }, + "updateTransforms": [ + { + "fieldPath": "a", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-st-alone.json b/handwritten/firestore/dev/conformance/conformance-tests/set-st-alone.json new file mode 100644 index 00000000000..1d28fd6f18d --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-st-alone.json @@ -0,0 +1,29 @@ +{ + "tests": [ + { + "description": "set: ServerTimestamp alone", + "comment": "If the only values in the input are ServerTimestamps, then\nan update operation with an empty map should be produced.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": \"ServerTimestamp\"}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": {} + }, + "updateTransforms": [ + { + "fieldPath": "a", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-st-merge-both.json b/handwritten/firestore/dev/conformance/conformance-tests/set-st-merge-both.json new file mode 100644 index 00000000000..359c899a1e2 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-st-merge-both.json @@ -0,0 +1,52 @@ +{ + "tests": [ + { + "description": "set-merge: ServerTimestamp with Merge of both fields", + "comment": "Just as when no merge option is specified, ServerTimestamp\nsentinel values are removed from the data in the update operation and become\ntransforms.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "fields": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + } + ] + }, + "jsonData": "{\"a\": 1, \"b\": \"ServerTimestamp\"}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "updateTransforms": [ + { + "fieldPath": "b", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-st-merge-nonleaf-alone.json b/handwritten/firestore/dev/conformance/conformance-tests/set-st-merge-nonleaf-alone.json new file mode 100644 index 00000000000..5af99ab0a56 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-st-merge-nonleaf-alone.json @@ -0,0 +1,42 @@ +{ + "tests": [ + { + "description": "set-merge: non-leaf merge field with ServerTimestamp alone", + "comment": "If a field path is in a merge option, the value at that path\nreplaces the stored value. If the value has only ServerTimestamps, they become transforms\nand we clear the value by including the field path in the update mask.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "fields": [ + { + "field": [ + "h" + ] + } + ] + }, + "jsonData": "{\"h\": {\"g\": \"ServerTimestamp\"}, \"e\": 7}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d" + }, + "updateMask": { + "fieldPaths": [ + "h" + ] + }, + "updateTransforms": [ + { + "fieldPath": "h.g", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-st-merge-nonleaf.json b/handwritten/firestore/dev/conformance/conformance-tests/set-st-merge-nonleaf.json new file mode 100644 index 00000000000..e66ca87bf82 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-st-merge-nonleaf.json @@ -0,0 +1,53 @@ +{ + "tests": [ + { + "description": "set-merge: non-leaf merge field with ServerTimestamp", + "comment": "If a field path is in a merge option, the value at that path\nreplaces the stored value, and ServerTimestamps inside that value become transforms\nas usual.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "fields": [ + { + "field": [ + "h" + ] + } + ] + }, + "jsonData": "{\"h\": {\"f\": 5, \"g\": \"ServerTimestamp\"}, \"e\": 7}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "h": { + "mapValue": { + "fields": { + "f": { + "integerValue": "5" + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "h" + ] + }, + "updateTransforms": [ + { + "fieldPath": "h.g", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-st-merge-nowrite.json b/handwritten/firestore/dev/conformance/conformance-tests/set-st-merge-nowrite.json new file mode 100644 index 00000000000..44091b1276e --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-st-merge-nowrite.json @@ -0,0 +1,41 @@ +{ + "tests": [ + { + "description": "set-merge: If no ordinary values in Merge, no write", + "comment": "If all the fields in the merge option have ServerTimestamp\nvalues, then no update operation is produced, only a transform.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "fields": [ + { + "field": [ + "b" + ] + } + ] + }, + "jsonData": "{\"a\": 1, \"b\": \"ServerTimestamp\"}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "fields": {}, + "name": "projects/projectID/databases/(default)/documents/C/d" + }, + "updateMask": { + "fieldPaths": [] + }, + "updateTransforms": [ + { + "fieldPath": "b", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-st-mergeall.json b/handwritten/firestore/dev/conformance/conformance-tests/set-st-mergeall.json new file mode 100644 index 00000000000..f913d69e61f --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-st-mergeall.json @@ -0,0 +1,41 @@ +{ + "tests": [ + { + "description": "set: ServerTimestamp with MergeAll", + "comment": "Just as when no merge option is specified, ServerTimestamp\nsentinel values are removed from the data in the update operation and become\ntransforms.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "all": true + }, + "jsonData": "{\"a\": 1, \"b\": \"ServerTimestamp\"}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "updateTransforms": [ + { + "fieldPath": "b", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-st-multi.json b/handwritten/firestore/dev/conformance/conformance-tests/set-st-multi.json new file mode 100644 index 00000000000..03200729cad --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-st-multi.json @@ -0,0 +1,37 @@ +{ + "tests": [ + { + "description": "set: multiple ServerTimestamp fields", + "comment": "A document can have more than one ServerTimestamp field.\nSince all the ServerTimestamp fields are removed, the only field in the update is \"a\".", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": \"ServerTimestamp\", \"c\": {\"d\": \"ServerTimestamp\"}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateTransforms": [ + { + "fieldPath": "b", + "setToServerValue": "REQUEST_TIME" + }, + { + "fieldPath": "c.d", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-st-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/set-st-nested.json new file mode 100644 index 00000000000..58406e80b36 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-st-nested.json @@ -0,0 +1,33 @@ +{ + "tests": [ + { + "description": "set: nested ServerTimestamp field", + "comment": "A ServerTimestamp value can occur at any depth. In this case,\nthe transform applies to the field path \"b.c\". Since \"c\" is removed from the update,\n\"b\" becomes empty, so it is also removed from the update.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": {\"c\": \"ServerTimestamp\"}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateTransforms": [ + { + "fieldPath": "b.c", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-st-noarray-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/set-st-noarray-nested.json new file mode 100644 index 00000000000..5ad6a50897b --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-st-noarray-nested.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "set: ServerTimestamp cannot be anywhere inside an array value", + "comment": "There cannot be an array value anywhere on the path from the document\nroot to the ServerTimestamp sentinel. Firestore transforms don't support array indexing.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, {\"b\": \"ServerTimestamp\"}]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-st-noarray.json b/handwritten/firestore/dev/conformance/conformance-tests/set-st-noarray.json new file mode 100644 index 00000000000..76a2881cb61 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-st-noarray.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "set: ServerTimestamp cannot be in an array value", + "comment": "The ServerTimestamp sentinel must be the value of a field. Firestore\ntransforms don't support array indexing.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, 2, \"ServerTimestamp\"]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-st-nomerge.json b/handwritten/firestore/dev/conformance/conformance-tests/set-st-nomerge.json new file mode 100644 index 00000000000..0523ed74fb4 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-st-nomerge.json @@ -0,0 +1,41 @@ +{ + "tests": [ + { + "description": "set-merge: If is ServerTimestamp not in Merge, no transform", + "comment": "If the ServerTimestamp value is not mentioned in a merge option,\nthen it is pruned from the data but does not result in a transform.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "option": { + "fields": [ + { + "field": [ + "a" + ] + } + ] + }, + "jsonData": "{\"a\": 1, \"b\": \"ServerTimestamp\"}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-st-with-empty-map.json b/handwritten/firestore/dev/conformance/conformance-tests/set-st-with-empty-map.json new file mode 100644 index 00000000000..a4078665378 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-st-with-empty-map.json @@ -0,0 +1,41 @@ +{ + "tests": [ + { + "description": "set: ServerTimestamp beside an empty map", + "comment": "When a ServerTimestamp and a map both reside inside a map, the\nServerTimestamp should be stripped out but the empty map should remain.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": {\"b\": {}, \"c\": \"ServerTimestamp\"}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "mapValue": { + "fields": { + "b": { + "mapValue": { + "fields": {} + } + } + } + } + } + } + }, + "updateTransforms": [ + { + "fieldPath": "a.c", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/set-st.json b/handwritten/firestore/dev/conformance/conformance-tests/set-st.json new file mode 100644 index 00000000000..3e55ae111b5 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/set-st.json @@ -0,0 +1,33 @@ +{ + "tests": [ + { + "description": "set: ServerTimestamp with data", + "comment": "A key with the special ServerTimestamp sentinel is removed from\nthe data in the update operation. Instead it appears in a separate Transform operation.\nNote that in these tests, the string \"ServerTimestamp\" should be replaced with the\nspecial ServerTimestamp value.", + "set": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": \"ServerTimestamp\"}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateTransforms": [ + { + "fieldPath": "b", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-all-transforms.json b/handwritten/firestore/dev/conformance/conformance-tests/update-all-transforms.json new file mode 100644 index 00000000000..72b16d3a1b0 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-all-transforms.json @@ -0,0 +1,73 @@ +{ + "tests": [ + { + "description": "update: all transforms in a single call", + "comment": "A document can be created with any amount of transforms.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": \"ServerTimestamp\", \"c\": [\"ArrayUnion\", 1, 2, 3], \"d\": [\"ArrayRemove\", 4, 5, 6]}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b", + "setToServerValue": "REQUEST_TIME" + }, + { + "fieldPath": "c", + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + }, + { + "fieldPath": "d", + "removeAllFromArray": { + "values": [ + { + "integerValue": "4" + }, + { + "integerValue": "5" + }, + { + "integerValue": "6" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-alone.json b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-alone.json new file mode 100644 index 00000000000..93b8ff0528b --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-alone.json @@ -0,0 +1,47 @@ +{ + "tests": [ + { + "description": "update: ArrayRemove alone", + "comment": "If the only values in the input are ArrayRemove, then no\nupdate operation should be produced.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [\"ArrayRemove\", 1, 2, 3]}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "currentDocument": { + "exists": true + }, + "update": { + "fields": {}, + "name": "projects/projectID/databases/(default)/documents/C/d" + }, + "updateMask": { + "fieldPaths": [] + }, + "updateTransforms": [ + { + "fieldPath": "a", + "removeAllFromArray": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-multi.json b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-multi.json new file mode 100644 index 00000000000..18ed0fddea3 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-multi.json @@ -0,0 +1,70 @@ +{ + "tests": [ + { + "description": "update: multiple ArrayRemove fields", + "comment": "A document can have more than one ArrayRemove field.\nSince all the ArrayRemove fields are removed, the only field in the update is \"a\".", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": [\"ArrayRemove\", 1, 2, 3], \"c\": {\"d\": [\"ArrayRemove\", 4, 5, 6]}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "c" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b", + "removeAllFromArray": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + }, + { + "fieldPath": "c.d", + "removeAllFromArray": { + "values": [ + { + "integerValue": "4" + }, + { + "integerValue": "5" + }, + { + "integerValue": "6" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-nested.json new file mode 100644 index 00000000000..7159797c77b --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-nested.json @@ -0,0 +1,54 @@ +{ + "tests": [ + { + "description": "update: nested ArrayRemove field", + "comment": "An ArrayRemove value can occur at any depth. In this case,\nthe transform applies to the field path \"b.c\". Since \"c\" is removed from the update,\n\"b\" becomes empty, so it is also removed from the update.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": {\"c\": [\"ArrayRemove\", 1, 2, 3]}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "b" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b.c", + "removeAllFromArray": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-noarray-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-noarray-nested.json new file mode 100644 index 00000000000..842c5fe3240 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-noarray-nested.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: ArrayRemove cannot be anywhere inside an array value", + "comment": "There cannot be an array value anywhere on the path from the document\nroot to the ArrayRemove. Firestore transforms don't support array indexing.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, {\"b\": [\"ArrayRemove\", 1, 2, 3]}]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-noarray.json b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-noarray.json new file mode 100644 index 00000000000..0a371f05548 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-noarray.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: ArrayRemove cannot be in an array value", + "comment": "ArrayRemove must be the value of a field. Firestore\ntransforms don't support array indexing.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, 2, [\"ArrayRemove\", 1, 2, 3]]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-with-st.json b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-with-st.json new file mode 100644 index 00000000000..9d110de9cae --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove-with-st.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: The ServerTimestamp sentinel cannot be in an ArrayUnion", + "comment": "The ServerTimestamp sentinel must be the value of a field. It may\nnot appear in an ArrayUnion.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [\"ArrayRemove\", 1, \"ServerTimestamp\", 3]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove.json b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove.json new file mode 100644 index 00000000000..2311f916de5 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayremove.json @@ -0,0 +1,53 @@ +{ + "tests": [ + { + "description": "update: ArrayRemove with data", + "comment": "A key with ArrayRemove is removed from the data in the update \noperation. Instead it appears in a separate Transform operation.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": [\"ArrayRemove\", 1, 2, 3]}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b", + "removeAllFromArray": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-alone.json b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-alone.json new file mode 100644 index 00000000000..5cb08579cb1 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-alone.json @@ -0,0 +1,47 @@ +{ + "tests": [ + { + "description": "update: ArrayUnion alone", + "comment": "If the only values in the input are ArrayUnion, then no\nupdate operation should be produced.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [\"ArrayUnion\", 1, 2, 3]}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "currentDocument": { + "exists": true + }, + "update": { + "fields": {}, + "name": "projects/projectID/databases/(default)/documents/C/d" + }, + "updateMask": { + "fieldPaths": [] + }, + "updateTransforms": [ + { + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + }, + "fieldPath": "a" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-multi.json b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-multi.json new file mode 100644 index 00000000000..674ce2b4c25 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-multi.json @@ -0,0 +1,70 @@ +{ + "tests": [ + { + "description": "update: multiple ArrayUnion fields", + "comment": "A document can have more than one ArrayUnion field.\nSince all the ArrayUnion fields are removed, the only field in the update is \"a\".", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": [\"ArrayUnion\", 1, 2, 3], \"c\": {\"d\": [\"ArrayUnion\", 4, 5, 6]}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "c" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b", + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + }, + { + "fieldPath": "c.d", + "appendMissingElements": { + "values": [ + { + "integerValue": "4" + }, + { + "integerValue": "5" + }, + { + "integerValue": "6" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-nested.json new file mode 100644 index 00000000000..841ceed0acc --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-nested.json @@ -0,0 +1,54 @@ +{ + "tests": [ + { + "description": "update: nested ArrayUnion field", + "comment": "An ArrayUnion value can occur at any depth. In this case,\nthe transform applies to the field path \"b.c\". Since \"c\" is removed from the update,\n\"b\" becomes empty, so it is also removed from the update.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": {\"c\": [\"ArrayUnion\", 1, 2, 3]}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "b" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b.c", + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-noarray-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-noarray-nested.json new file mode 100644 index 00000000000..08745a08b07 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-noarray-nested.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: ArrayUnion cannot be anywhere inside an array value", + "comment": "There cannot be an array value anywhere on the path from the document\nroot to the ArrayUnion. Firestore transforms don't support array indexing.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, {\"b\": [\"ArrayUnion\", 1, 2, 3]}]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-noarray.json b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-noarray.json new file mode 100644 index 00000000000..284f42800eb --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-noarray.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: ArrayUnion cannot be in an array value", + "comment": "ArrayUnion must be the value of a field. Firestore\ntransforms don't support array indexing.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, 2, [\"ArrayRemove\", 1, 2, 3]]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-with-st.json b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-with-st.json new file mode 100644 index 00000000000..1c47591e29b --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion-with-st.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: The ServerTimestamp sentinel cannot be in an ArrayUnion", + "comment": "The ServerTimestamp sentinel must be the value of a field. It may\nnot appear in an ArrayUnion.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [\"ArrayUnion\", 1, \"ServerTimestamp\", 3]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion.json b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion.json new file mode 100644 index 00000000000..0aca2356c1a --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-arrayunion.json @@ -0,0 +1,53 @@ +{ + "tests": [ + { + "description": "update: ArrayUnion with data", + "comment": "A key with ArrayUnion is removed from the data in the update \noperation. Instead it appears in a separate Transform operation.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": [\"ArrayUnion\", 1, 2, 3]}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b", + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-badchar.json b/handwritten/firestore/dev/conformance/conformance-tests/update-badchar.json new file mode 100644 index 00000000000..7d5e6e4f07b --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-badchar.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: invalid character", + "comment": "The keys of the data given to Update are interpreted, unlike those of Create and Set. They cannot contain special characters.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a~b\": 1}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-basic.json b/handwritten/firestore/dev/conformance/conformance-tests/update-basic.json new file mode 100644 index 00000000000..f864247427e --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-basic.json @@ -0,0 +1,35 @@ +{ + "tests": [ + { + "description": "update: basic", + "comment": "A simple call, resulting in a single update operation.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-complex.json b/handwritten/firestore/dev/conformance/conformance-tests/update-complex.json new file mode 100644 index 00000000000..ddf8373367c --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-complex.json @@ -0,0 +1,69 @@ +{ + "tests": [ + { + "description": "update: complex", + "comment": "A call to a write method with complicated input data.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, 2.5], \"b\": {\"c\": [\"three\", {\"d\": true}]}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "arrayValue": { + "values": [ + { + "integerValue": "1" + }, + { + "doubleValue": 2.5 + } + ] + } + }, + "b": { + "mapValue": { + "fields": { + "c": { + "arrayValue": { + "values": [ + { + "stringValue": "three" + }, + { + "mapValue": { + "fields": { + "d": { + "booleanValue": true + } + } + } + } + ] + } + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "b" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-del-alone.json b/handwritten/firestore/dev/conformance/conformance-tests/update-del-alone.json new file mode 100644 index 00000000000..45598ab4022 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-del-alone.json @@ -0,0 +1,30 @@ +{ + "tests": [ + { + "description": "update: Delete alone", + "comment": "If the input data consists solely of Deletes, then the update\noperation has no map, just an update mask.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": \"Delete\"}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d" + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-del-dot.json b/handwritten/firestore/dev/conformance/conformance-tests/update-del-dot.json new file mode 100644 index 00000000000..44f36b0c3e8 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-del-dot.json @@ -0,0 +1,46 @@ +{ + "tests": [ + { + "description": "update: Delete with a dotted field", + "comment": "After expanding top-level dotted fields, fields with Delete\nvalues are pruned from the output data, but appear in the update mask.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b.c\": \"Delete\", \"b.d\": 2}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + }, + "b": { + "mapValue": { + "fields": { + "d": { + "integerValue": "2" + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "b.c", + "b.d" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-del-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/update-del-nested.json new file mode 100644 index 00000000000..18d08f3f004 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-del-nested.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: Delete cannot be nested", + "comment": "The Delete sentinel must be the value of a top-level key.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": {\"b\": \"Delete\"}}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-del-noarray-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/update-del-noarray-nested.json new file mode 100644 index 00000000000..025cbed0dfb --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-del-noarray-nested.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: Delete cannot be anywhere inside an array value", + "comment": "The Delete sentinel must be the value of a field. Deletes are implemented\nby turning the path to the Delete sentinel into a FieldPath, and FieldPaths do not support\narray indexing.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, {\"b\": \"Delete\"}]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-del-noarray.json b/handwritten/firestore/dev/conformance/conformance-tests/update-del-noarray.json new file mode 100644 index 00000000000..dce3806f2c3 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-del-noarray.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: Delete cannot be in an array value", + "comment": "The Delete sentinel must be the value of a field. Deletes are\nimplemented by turning the path to the Delete sentinel into a FieldPath, and FieldPaths\ndo not support array indexing.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, 2, \"Delete\"]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-del.json b/handwritten/firestore/dev/conformance/conformance-tests/update-del.json new file mode 100644 index 00000000000..26a6a1bc7e4 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-del.json @@ -0,0 +1,36 @@ +{ + "tests": [ + { + "description": "update: Delete", + "comment": "If a field's value is the Delete sentinel, then it doesn't appear\nin the update data, but does in the mask.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": \"Delete\"}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "b" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-exists-false-precond.json b/handwritten/firestore/dev/conformance/conformance-tests/update-exists-false-precond.json new file mode 100644 index 00000000000..031fd1af3f5 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-exists-false-precond.json @@ -0,0 +1,16 @@ +{ + "tests": [ + { + "description": "update: Exists=false precondition is invalid", + "comment": "The Update method does not support an explicit exists=false precondition.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "precondition": { + "exists": false + }, + "jsonData": "{\"a\": 1}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-exists-true-precond.json b/handwritten/firestore/dev/conformance/conformance-tests/update-exists-true-precond.json new file mode 100644 index 00000000000..f1aa800e4ed --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-exists-true-precond.json @@ -0,0 +1,38 @@ +{ + "tests": [ + { + "description": "update: Exists=true precondition is valid", + "comment": "The Update method supports an explicit exists=true precondition.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "precondition": { + "exists": true + }, + "jsonData": "{\"a\": 1}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-fp-empty-component.json b/handwritten/firestore/dev/conformance/conformance-tests/update-fp-empty-component.json new file mode 100644 index 00000000000..50274e49ffe --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-fp-empty-component.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: empty field path component", + "comment": "Empty fields are not allowed.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a..b\": 1}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-nested-transform-and-nested-value.json b/handwritten/firestore/dev/conformance/conformance-tests/update-nested-transform-and-nested-value.json new file mode 100644 index 00000000000..2ccba0985a7 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-nested-transform-and-nested-value.json @@ -0,0 +1,47 @@ +{ + "tests": [ + { + "description": "update: Nested transforms should not affect the field mask, even\nwhen there are other values that do. Transforms should only affect the\nDocumentTransform_FieldTransform list.", + "comment": "For updates, top-level paths in json-like map inputs\nare split on the dot. That is, an input {\"a.b.c\": 7} results in an update to\nfield c of object b of object a with value 7. In order to specify this behavior,\nthe update must use a fieldmask \"a.b.c\". However, fieldmasks are only used for\nconcrete values - transforms are separately encoded in a\nDocumentTransform_FieldTransform array.\n\nThis test exercises a bug found in python (https://github.com/googleapis/google-cloud-python/issues/7215)\nin which nested transforms ({\"a.c\": \"ServerTimestamp\"}) next to nested values\n({\"a.b\": 7}) incorrectly caused the fieldmask \"a\" to be set, which has the\neffect of wiping out all data in \"a\" other than what was specified in the\njson-like input.\n\nInstead, as this test specifies, transforms should not affect the fieldmask.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a.b\": 7, \"a.c\": \"ServerTimestamp\"}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "mapValue": { + "fields": { + "b": { + "integerValue": "7" + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "a.b" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "a.c", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-no-paths.json b/handwritten/firestore/dev/conformance/conformance-tests/update-no-paths.json new file mode 100644 index 00000000000..6cfbc01dce2 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-no-paths.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: no paths", + "comment": "It is a client-side error to call Update with empty data.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-all-transforms.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-all-transforms.json new file mode 100644 index 00000000000..40adbcaf567 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-all-transforms.json @@ -0,0 +1,100 @@ +{ + "tests": [ + { + "description": "update-paths: all transforms in a single call", + "comment": "A document can be created with any amount of transforms.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + }, + { + "field": [ + "c" + ] + }, + { + "field": [ + "d" + ] + } + ], + "jsonValues": [ + "1", + "\"ServerTimestamp\"", + "[\"ArrayUnion\", 1, 2, 3]", + "[\"ArrayRemove\", 4, 5, 6]" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b", + "setToServerValue": "REQUEST_TIME" + }, + { + "fieldPath": "c", + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + }, + { + "fieldPath": "d", + "removeAllFromArray": { + "values": [ + { + "integerValue": "4" + }, + { + "integerValue": "5" + }, + { + "integerValue": "6" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-alone.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-alone.json new file mode 100644 index 00000000000..4097f58885b --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-alone.json @@ -0,0 +1,56 @@ +{ + "tests": [ + { + "description": "update-paths: ArrayRemove alone", + "comment": "If the only values in the input are ArrayRemove, then no\nupdate operation should be produced.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "[\"ArrayRemove\", 1, 2, 3]" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "currentDocument": { + "exists": true + }, + "update": { + "fields": {}, + "name": "projects/projectID/databases/(default)/documents/C/d" + }, + "updateMask": { + "fieldPaths": [] + }, + "updateTransforms": [ + { + "fieldPath": "a", + "removeAllFromArray": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-multi.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-multi.json new file mode 100644 index 00000000000..5e76d07bac9 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-multi.json @@ -0,0 +1,91 @@ +{ + "tests": [ + { + "description": "update-paths: multiple ArrayRemove fields", + "comment": "A document can have more than one ArrayRemove field.\nSince all the ArrayRemove fields are removed, the only field in the update is \"a\".", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + }, + { + "field": [ + "c" + ] + } + ], + "jsonValues": [ + "1", + "[\"ArrayRemove\", 1, 2, 3]", + "{\"d\": [\"ArrayRemove\", 4, 5, 6]}" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "c" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b", + "removeAllFromArray": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + }, + { + "fieldPath": "c.d", + "removeAllFromArray": { + "values": [ + { + "integerValue": "4" + }, + { + "integerValue": "5" + }, + { + "integerValue": "6" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-nested.json new file mode 100644 index 00000000000..9ee1b2a6fe6 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-nested.json @@ -0,0 +1,69 @@ +{ + "tests": [ + { + "description": "update-paths: nested ArrayRemove field", + "comment": "An ArrayRemove value can occur at any depth. In this case,\nthe transform applies to the field path \"b.c\". Since \"c\" is removed from the update,\n\"b\" becomes empty, so it is also removed from the update.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + } + ], + "jsonValues": [ + "1", + "{\"c\": [\"ArrayRemove\", 1, 2, 3]}" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "b" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b.c", + "removeAllFromArray": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-noarray-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-noarray-nested.json new file mode 100644 index 00000000000..b669e870cd3 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-noarray-nested.json @@ -0,0 +1,22 @@ +{ + "tests": [ + { + "description": "update-paths: ArrayRemove cannot be anywhere inside an array value", + "comment": "There cannot be an array value anywhere on the path from the document\nroot to the ArrayRemove. Firestore transforms don't support array indexing.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "[1, {\"b\": [\"ArrayRemove\", 1, 2, 3]}]" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-noarray.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-noarray.json new file mode 100644 index 00000000000..ff50e11e4fb --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-noarray.json @@ -0,0 +1,22 @@ +{ + "tests": [ + { + "description": "update-paths: ArrayRemove cannot be in an array value", + "comment": "ArrayRemove must be the value of a field. Firestore\ntransforms don't support array indexing.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "[1, 2, [\"ArrayRemove\", 1, 2, 3]]" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-with-st.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-with-st.json new file mode 100644 index 00000000000..d27d26e4466 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove-with-st.json @@ -0,0 +1,22 @@ +{ + "tests": [ + { + "description": "update-paths: The ServerTimestamp sentinel cannot be in an ArrayUnion", + "comment": "The ServerTimestamp sentinel must be the value of a field. It may\nnot appear in an ArrayUnion.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "[\"ArrayRemove\", 1, \"ServerTimestamp\", 3]" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove.json new file mode 100644 index 00000000000..a7be888daf0 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayremove.json @@ -0,0 +1,68 @@ +{ + "tests": [ + { + "description": "update-paths: ArrayRemove with data", + "comment": "A key with ArrayRemove is removed from the data in the update \noperation. Instead it appears in a separate Transform operation.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + } + ], + "jsonValues": [ + "1", + "[\"ArrayRemove\", 1, 2, 3]" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b", + "removeAllFromArray": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-alone.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-alone.json new file mode 100644 index 00000000000..2375d0cedb6 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-alone.json @@ -0,0 +1,56 @@ +{ + "tests": [ + { + "description": "update-paths: ArrayUnion alone", + "comment": "If the only values in the input are ArrayUnion, then no\nupdate operation should be produced.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "[\"ArrayUnion\", 1, 2, 3]" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "currentDocument": { + "exists": true + }, + "update": { + "fields": {}, + "name": "projects/projectID/databases/(default)/documents/C/d" + }, + "updateMask": { + "fieldPaths": [] + }, + "updateTransforms": [ + { + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + }, + "fieldPath": "a" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-multi.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-multi.json new file mode 100644 index 00000000000..afb6437417a --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-multi.json @@ -0,0 +1,91 @@ +{ + "tests": [ + { + "description": "update-paths: multiple ArrayUnion fields", + "comment": "A document can have more than one ArrayUnion field.\nSince all the ArrayUnion fields are removed, the only field in the update is \"a\".", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + }, + { + "field": [ + "c" + ] + } + ], + "jsonValues": [ + "1", + "[\"ArrayUnion\", 1, 2, 3]", + "{\"d\": [\"ArrayUnion\", 4, 5, 6]}" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "c" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b", + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + }, + { + "fieldPath": "c.d", + "appendMissingElements": { + "values": [ + { + "integerValue": "4" + }, + { + "integerValue": "5" + }, + { + "integerValue": "6" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-nested.json new file mode 100644 index 00000000000..d908d02055a --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-nested.json @@ -0,0 +1,69 @@ +{ + "tests": [ + { + "description": "update-paths: nested ArrayUnion field", + "comment": "An ArrayUnion value can occur at any depth. In this case,\nthe transform applies to the field path \"b.c\". Since \"c\" is removed from the update,\n\"b\" becomes empty, so it is also removed from the update.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + } + ], + "jsonValues": [ + "1", + "{\"c\": [\"ArrayUnion\", 1, 2, 3]}" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "b" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b.c", + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-noarray-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-noarray-nested.json new file mode 100644 index 00000000000..0e8a634a441 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-noarray-nested.json @@ -0,0 +1,22 @@ +{ + "tests": [ + { + "description": "update-paths: ArrayUnion cannot be anywhere inside an array value", + "comment": "There cannot be an array value anywhere on the path from the document\nroot to the ArrayUnion. Firestore transforms don't support array indexing.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "[1, {\"b\": [\"ArrayUnion\", 1, 2, 3]}]" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-noarray.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-noarray.json new file mode 100644 index 00000000000..ce45841888f --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-noarray.json @@ -0,0 +1,22 @@ +{ + "tests": [ + { + "description": "update-paths: ArrayUnion cannot be in an array value", + "comment": "ArrayUnion must be the value of a field. Firestore\ntransforms don't support array indexing.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "[1, 2, [\"ArrayRemove\", 1, 2, 3]]" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-with-st.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-with-st.json new file mode 100644 index 00000000000..c0a4204182c --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion-with-st.json @@ -0,0 +1,22 @@ +{ + "tests": [ + { + "description": "update-paths: The ServerTimestamp sentinel cannot be in an ArrayUnion", + "comment": "The ServerTimestamp sentinel must be the value of a field. It may\nnot appear in an ArrayUnion.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "[\"ArrayUnion\", 1, \"ServerTimestamp\", 3]" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion.json new file mode 100644 index 00000000000..ed2966aede7 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-arrayunion.json @@ -0,0 +1,68 @@ +{ + "tests": [ + { + "description": "update-paths: ArrayUnion with data", + "comment": "A key with ArrayUnion is removed from the data in the update \noperation. Instead it appears in a separate Transform operation.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + } + ], + "jsonValues": [ + "1", + "[\"ArrayUnion\", 1, 2, 3]" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b", + "appendMissingElements": { + "values": [ + { + "integerValue": "1" + }, + { + "integerValue": "2" + }, + { + "integerValue": "3" + } + ] + } + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-basic.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-basic.json new file mode 100644 index 00000000000..bf1164ac410 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-basic.json @@ -0,0 +1,44 @@ +{ + "tests": [ + { + "description": "update-paths: basic", + "comment": "A simple call, resulting in a single update operation.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "1" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-complex.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-complex.json new file mode 100644 index 00000000000..2f3faa7846c --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-complex.json @@ -0,0 +1,84 @@ +{ + "tests": [ + { + "description": "update-paths: complex", + "comment": "A call to a write method with complicated input data.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + } + ], + "jsonValues": [ + "[1, 2.5]", + "{\"c\": [\"three\", {\"d\": true}]}" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "arrayValue": { + "values": [ + { + "integerValue": "1" + }, + { + "doubleValue": 2.5 + } + ] + } + }, + "b": { + "mapValue": { + "fields": { + "c": { + "arrayValue": { + "values": [ + { + "stringValue": "three" + }, + { + "mapValue": { + "fields": { + "d": { + "booleanValue": true + } + } + } + } + ] + } + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "b" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-del-alone.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-del-alone.json new file mode 100644 index 00000000000..e3368c86c37 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-del-alone.json @@ -0,0 +1,39 @@ +{ + "tests": [ + { + "description": "update-paths: Delete alone", + "comment": "If the input data consists solely of Deletes, then the update\noperation has no map, just an update mask.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "\"Delete\"" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d" + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-del-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-del-nested.json new file mode 100644 index 00000000000..07f9f405ea4 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-del-nested.json @@ -0,0 +1,22 @@ +{ + "tests": [ + { + "description": "update-paths: Delete cannot be nested", + "comment": "The Delete sentinel must be the value of a top-level key.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "{\"b\": \"Delete\"}" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-del-noarray-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-del-noarray-nested.json new file mode 100644 index 00000000000..a74c0aeb570 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-del-noarray-nested.json @@ -0,0 +1,22 @@ +{ + "tests": [ + { + "description": "update-paths: Delete cannot be anywhere inside an array value", + "comment": "The Delete sentinel must be the value of a field. Deletes are implemented\nby turning the path to the Delete sentinel into a FieldPath, and FieldPaths do not support\narray indexing.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "[1, {\"b\": \"Delete\"}]" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-del-noarray.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-del-noarray.json new file mode 100644 index 00000000000..fb6d00b7240 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-del-noarray.json @@ -0,0 +1,22 @@ +{ + "tests": [ + { + "description": "update-paths: Delete cannot be in an array value", + "comment": "The Delete sentinel must be the value of a field. Deletes are\nimplemented by turning the path to the Delete sentinel into a FieldPath, and FieldPaths\ndo not support array indexing.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "[1, 2, \"Delete\"]" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-del.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-del.json new file mode 100644 index 00000000000..cb5f6bedf41 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-del.json @@ -0,0 +1,51 @@ +{ + "tests": [ + { + "description": "update-paths: Delete", + "comment": "If a field's value is the Delete sentinel, then it doesn't appear\nin the update data, but does in the mask.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + } + ], + "jsonValues": [ + "1", + "\"Delete\"" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "b" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-exists-false-precond.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-exists-false-precond.json new file mode 100644 index 00000000000..f122b530727 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-exists-false-precond.json @@ -0,0 +1,25 @@ +{ + "tests": [ + { + "description": "update-paths: Exists=false precondition is invalid", + "comment": "The Update method does not support an explicit exists=false precondition.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "precondition": { + "exists": false + }, + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "1" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-exists-true-precond.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-exists-true-precond.json new file mode 100644 index 00000000000..39d61c99a53 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-exists-true-precond.json @@ -0,0 +1,47 @@ +{ + "tests": [ + { + "description": "update-paths: Exists=true precondition is valid", + "comment": "The Update method supports an explicit exists=true precondition.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "precondition": { + "exists": true + }, + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "1" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-del.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-del.json new file mode 100644 index 00000000000..95b787a9136 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-del.json @@ -0,0 +1,59 @@ +{ + "tests": [ + { + "description": "update-paths: field paths with delete", + "comment": "If one nested field is deleted, and another isn't, preserve the second.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "foo", + "bar" + ] + }, + { + "field": [ + "foo", + "delete" + ] + } + ], + "jsonValues": [ + "1", + "\"Delete\"" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "foo": { + "mapValue": { + "fields": { + "bar": { + "integerValue": "1" + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "foo.bar", + "foo.delete" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-dup-transforms.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-dup-transforms.json new file mode 100644 index 00000000000..aff02a8d203 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-dup-transforms.json @@ -0,0 +1,34 @@ +{ + "tests": [ + { + "description": "update-paths: duplicate field path with only transforms", + "comment": "The same field cannot occur more than once, even if all the operations are transforms.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + }, + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "[\"ArrayUnion\", 1, 2, 3]", + "\"ServerTimestamp\"", + "[\"ArrayUnion\", 4, 5, 6]" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-dup.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-dup.json new file mode 100644 index 00000000000..71bf4d54a2a --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-dup.json @@ -0,0 +1,34 @@ +{ + "tests": [ + { + "description": "update-paths: duplicate field path", + "comment": "The same field cannot occur more than once.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + }, + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "1", + "2", + "3" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-empty-component.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-empty-component.json new file mode 100644 index 00000000000..161e9f6eff9 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-empty-component.json @@ -0,0 +1,23 @@ +{ + "tests": [ + { + "description": "update-paths: empty field path component", + "comment": "Empty fields are not allowed.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "*", + "" + ] + } + ], + "jsonValues": [ + "1" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-empty.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-empty.json new file mode 100644 index 00000000000..9424da13056 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-empty.json @@ -0,0 +1,20 @@ +{ + "tests": [ + { + "description": "update-paths: empty field path", + "comment": "A FieldPath of length zero is invalid.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [] + } + ], + "jsonValues": [ + "1" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-multi.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-multi.json new file mode 100644 index 00000000000..a0afd38b8f2 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-multi.json @@ -0,0 +1,51 @@ +{ + "tests": [ + { + "description": "update-paths: multiple-element field path", + "comment": "The UpdatePaths or equivalent method takes a list of FieldPaths.\nEach FieldPath is a sequence of uninterpreted path components.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a", + "b" + ] + } + ], + "jsonValues": [ + "1" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "mapValue": { + "fields": { + "b": { + "integerValue": "1" + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "a.b" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-nosplit.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-nosplit.json new file mode 100644 index 00000000000..23e9ddc9d3a --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-fp-nosplit.json @@ -0,0 +1,57 @@ +{ + "tests": [ + { + "description": "update-paths: FieldPath elements are not split on dots", + "comment": "FieldPath components are not split on dots.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a.b", + "f.g" + ] + } + ], + "jsonValues": [ + "{\"n.o\": 7}" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a.b": { + "mapValue": { + "fields": { + "f.g": { + "mapValue": { + "fields": { + "n.o": { + "integerValue": "7" + } + } + } + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "`a.b`.`f.g`" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-nested-transform-and-nested-value.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-nested-transform-and-nested-value.json new file mode 100644 index 00000000000..c4dead09e0b --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-nested-transform-and-nested-value.json @@ -0,0 +1,64 @@ +{ + "tests": [ + { + "description": "update-paths: Nested transforms should not affect the field mask, even\nwhen there are other values that do. Transforms should only affect the\nDocumentTransform_FieldTransform list.", + "comment": "For updates, top-level paths in json-like map inputs\nare split on the dot. That is, an input {\"a.b.c\": 7} results in an update to\nfield c of object b of object a with value 7. In order to specify this behavior,\nthe update must use a fieldmask \"a.b.c\". However, fieldmasks are only used for\nconcrete values - transforms are separately encoded in a\nDocumentTransform_FieldTransform array.\n\nThis test exercises a bug found in python (https://github.com/googleapis/google-cloud-python/issues/7215)\nin which nested transforms ({\"a.c\": \"ServerTimestamp\"}) next to nested values\n({\"a.b\": 7}) incorrectly caused the fieldmask \"a\" to be set, which has the\neffect of wiping out all data in \"a\" other than what was specified in the\njson-like input.\n\nInstead, as this test specifies, transforms should not affect the fieldmask.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a", + "b" + ] + }, + { + "field": [ + "a", + "c" + ] + } + ], + "jsonValues": [ + "7", + "\"ServerTimestamp\"" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "mapValue": { + "fields": { + "b": { + "integerValue": "7" + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "a.b" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "a.c", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-no-paths.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-no-paths.json new file mode 100644 index 00000000000..e8ad035eaf1 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-no-paths.json @@ -0,0 +1,12 @@ +{ + "tests": [ + { + "description": "update-paths: no paths", + "comment": "It is a client-side error to call Update with empty data.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-prefix-1.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-prefix-1.json new file mode 100644 index 00000000000..0bc1c0e812d --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-prefix-1.json @@ -0,0 +1,29 @@ +{ + "tests": [ + { + "description": "update-paths: prefix #1", + "comment": "In the input data, one field cannot be a prefix of another.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a", + "b" + ] + }, + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "1", + "2" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-prefix-2.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-prefix-2.json new file mode 100644 index 00000000000..6f1d152a707 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-prefix-2.json @@ -0,0 +1,29 @@ +{ + "tests": [ + { + "description": "update-paths: prefix #2", + "comment": "In the input data, one field cannot be a prefix of another.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "a", + "b" + ] + } + ], + "jsonValues": [ + "1", + "2" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-prefix-3.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-prefix-3.json new file mode 100644 index 00000000000..4fe17b292f6 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-prefix-3.json @@ -0,0 +1,29 @@ +{ + "tests": [ + { + "description": "update-paths: prefix #3", + "comment": "In the input data, one field cannot be a prefix of another, even if the values could in principle be combined.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "a", + "d" + ] + } + ], + "jsonValues": [ + "{\"b\": 1}", + "2" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-special-chars.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-special-chars.json new file mode 100644 index 00000000000..83b27d8dbfd --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-special-chars.json @@ -0,0 +1,62 @@ +{ + "tests": [ + { + "description": "update-paths: special characters", + "comment": "FieldPaths can contain special characters.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "*", + "~" + ] + }, + { + "field": [ + "*", + "`" + ] + } + ], + "jsonValues": [ + "1", + "2" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "*": { + "mapValue": { + "fields": { + "`": { + "integerValue": "2" + }, + "~": { + "integerValue": "1" + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "`*`.`\\``", + "`*`.`~`" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-alone.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-alone.json new file mode 100644 index 00000000000..668c1c932bf --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-alone.json @@ -0,0 +1,44 @@ +{ + "tests": [ + { + "description": "update-paths: ServerTimestamp alone", + "comment": "If the only values in the input are ServerTimestamps, then no\nupdate operation should be produced.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "\"ServerTimestamp\"" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "currentDocument": { + "exists": true + }, + "update": { + "fields": {}, + "name": "projects/projectID/databases/(default)/documents/C/d" + }, + "updateMask": { + "fieldPaths": [] + }, + "updateTransforms": [ + { + "fieldPath": "a", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-multi.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-multi.json new file mode 100644 index 00000000000..8767cf34979 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-multi.json @@ -0,0 +1,67 @@ +{ + "tests": [ + { + "description": "update-paths: multiple ServerTimestamp fields", + "comment": "A document can have more than one ServerTimestamp field.\nSince all the ServerTimestamp fields are removed, the only field in the update is \"a\".", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + }, + { + "field": [ + "c" + ] + } + ], + "jsonValues": [ + "1", + "\"ServerTimestamp\"", + "{\"d\": \"ServerTimestamp\"}" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "c" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b", + "setToServerValue": "REQUEST_TIME" + }, + { + "fieldPath": "c.d", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-nested.json new file mode 100644 index 00000000000..94ecaccaa40 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-nested.json @@ -0,0 +1,57 @@ +{ + "tests": [ + { + "description": "update-paths: nested ServerTimestamp field", + "comment": "A ServerTimestamp value can occur at any depth. In this case,\nthe transform applies to the field path \"b.c\". Since \"c\" is removed from the update,\n\"b\" becomes empty, so it is also removed from the update.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + } + ], + "jsonValues": [ + "1", + "{\"c\": \"ServerTimestamp\"}" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "b" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b.c", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-noarray-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-noarray-nested.json new file mode 100644 index 00000000000..2dd1bcacc77 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-noarray-nested.json @@ -0,0 +1,22 @@ +{ + "tests": [ + { + "description": "update-paths: ServerTimestamp cannot be anywhere inside an array value", + "comment": "There cannot be an array value anywhere on the path from the document\nroot to the ServerTimestamp sentinel. Firestore transforms don't support array indexing.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "[1, {\"b\": \"ServerTimestamp\"}]" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-noarray.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-noarray.json new file mode 100644 index 00000000000..5da60306bc2 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-noarray.json @@ -0,0 +1,22 @@ +{ + "tests": [ + { + "description": "update-paths: ServerTimestamp cannot be in an array value", + "comment": "The ServerTimestamp sentinel must be the value of a field. Firestore\ntransforms don't support array indexing.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "[1, 2, \"ServerTimestamp\"]" + ], + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-with-empty-map.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-with-empty-map.json new file mode 100644 index 00000000000..a86ae46cd18 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st-with-empty-map.json @@ -0,0 +1,58 @@ +{ + "tests": [ + { + "description": "update-paths: ServerTimestamp beside an empty map", + "comment": "When a ServerTimestamp and a map both reside inside a map, the\nServerTimestamp should be stripped out but the empty map should remain.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "{\"b\": {}, \"c\": \"ServerTimestamp\"}" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "mapValue": { + "fields": { + "b": { + "mapValue": { + "fields": {} + } + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "updateTransforms": [ + { + "fieldPath": "a.c", + "setToServerValue": "REQUEST_TIME" + } + ], + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st.json new file mode 100644 index 00000000000..1710508b2d1 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-st.json @@ -0,0 +1,56 @@ +{ + "tests": [ + { + "description": "update-paths: ServerTimestamp with data", + "comment": "A key with the special ServerTimestamp sentinel is removed from\nthe data in the update operation. Instead it appears in a separate Transform operation.\nNote that in these tests, the string \"ServerTimestamp\" should be replaced with the\nspecial ServerTimestamp value.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "fieldPaths": [ + { + "field": [ + "a" + ] + }, + { + "field": [ + "b" + ] + } + ], + "jsonValues": [ + "1", + "\"ServerTimestamp\"" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-paths-uptime.json b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-uptime.json new file mode 100644 index 00000000000..96801a0cd8e --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-paths-uptime.json @@ -0,0 +1,47 @@ +{ + "tests": [ + { + "description": "update-paths: last-update-time precondition", + "comment": "The Update call supports a last-update-time precondition.", + "updatePaths": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "precondition": { + "updateTime": "1970-01-01T00:00:42Z" + }, + "fieldPaths": [ + { + "field": [ + "a" + ] + } + ], + "jsonValues": [ + "1" + ], + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "updateTime": "1970-01-01T00:00:42Z" + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-prefix-1.json b/handwritten/firestore/dev/conformance/conformance-tests/update-prefix-1.json new file mode 100644 index 00000000000..faad69d140b --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-prefix-1.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: prefix #1", + "comment": "In the input data, one field cannot be a prefix of another.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a.b\": 1, \"a\": 2}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-prefix-2.json b/handwritten/firestore/dev/conformance/conformance-tests/update-prefix-2.json new file mode 100644 index 00000000000..96545c13486 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-prefix-2.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: prefix #2", + "comment": "In the input data, one field cannot be a prefix of another.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"a.b\": 2}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-prefix-3.json b/handwritten/firestore/dev/conformance/conformance-tests/update-prefix-3.json new file mode 100644 index 00000000000..95f7024966c --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-prefix-3.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: prefix #3", + "comment": "In the input data, one field cannot be a prefix of another, even if the values could in principle be combined.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": {\"b\": 1}, \"a.d\": 2}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-quoting.json b/handwritten/firestore/dev/conformance/conformance-tests/update-quoting.json new file mode 100644 index 00000000000..10e3c35c22c --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-quoting.json @@ -0,0 +1,47 @@ +{ + "tests": [ + { + "description": "update: non-letter starting chars are quoted, except underscore", + "comment": "In a field path, any component beginning with a non-letter or underscore is quoted.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"_0.1.+2\": 1}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "_0": { + "mapValue": { + "fields": { + "1": { + "mapValue": { + "fields": { + "+2": { + "integerValue": "1" + } + } + } + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "_0.`1`.`+2`" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-split-top-level.json b/handwritten/firestore/dev/conformance/conformance-tests/update-split-top-level.json new file mode 100644 index 00000000000..eddf360d373 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-split-top-level.json @@ -0,0 +1,47 @@ +{ + "tests": [ + { + "description": "update: Split on dots for top-level keys only", + "comment": "The Update method splits only top-level keys at dots. Keys at\nother levels are taken literally.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"h.g\": {\"j.k\": 6}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "h": { + "mapValue": { + "fields": { + "g": { + "mapValue": { + "fields": { + "j.k": { + "integerValue": "6" + } + } + } + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "h.g" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-split.json b/handwritten/firestore/dev/conformance/conformance-tests/update-split.json new file mode 100644 index 00000000000..e18c78bf6e6 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-split.json @@ -0,0 +1,47 @@ +{ + "tests": [ + { + "description": "update: split on dots", + "comment": "The Update method splits top-level keys at dots.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a.b.c\": 1}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "mapValue": { + "fields": { + "b": { + "mapValue": { + "fields": { + "c": { + "integerValue": "1" + } + } + } + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "a.b.c" + ] + }, + "currentDocument": { + "exists": true + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-st-alone.json b/handwritten/firestore/dev/conformance/conformance-tests/update-st-alone.json new file mode 100644 index 00000000000..49fab176915 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-st-alone.json @@ -0,0 +1,35 @@ +{ + "tests": [ + { + "description": "update: ServerTimestamp alone", + "comment": "If the only values in the input are ServerTimestamps, then no\nupdate operation should be produced.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": \"ServerTimestamp\"}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "currentDocument": { + "exists": true + }, + "update": { + "fields": {}, + "name": "projects/projectID/databases/(default)/documents/C/d" + }, + "updateMask": { + "fieldPaths": [] + }, + "updateTransforms": [ + { + "fieldPath": "a", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-st-dot.json b/handwritten/firestore/dev/conformance/conformance-tests/update-st-dot.json new file mode 100644 index 00000000000..8b9a7690216 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-st-dot.json @@ -0,0 +1,35 @@ +{ + "tests": [ + { + "description": "update: ServerTimestamp with dotted field", + "comment": "Like other uses of ServerTimestamp, the data is pruned and the\nfield does not appear in the update mask, because it is in the transform. In this case\nAn update operation is produced just to hold the precondition.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a.b.c\": \"ServerTimestamp\"}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "currentDocument": { + "exists": true + }, + "update": { + "fields": {}, + "name": "projects/projectID/databases/(default)/documents/C/d" + }, + "updateMask": { + "fieldPaths": [] + }, + "updateTransforms": [ + { + "fieldPath": "a.b.c", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-st-multi.json b/handwritten/firestore/dev/conformance/conformance-tests/update-st-multi.json new file mode 100644 index 00000000000..f474112b635 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-st-multi.json @@ -0,0 +1,46 @@ +{ + "tests": [ + { + "description": "update: multiple ServerTimestamp fields", + "comment": "A document can have more than one ServerTimestamp field.\nSince all the ServerTimestamp fields are removed, the only field in the update is \"a\".", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": \"ServerTimestamp\", \"c\": {\"d\": \"ServerTimestamp\"}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "c" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b", + "setToServerValue": "REQUEST_TIME" + }, + { + "fieldPath": "c.d", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-st-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/update-st-nested.json new file mode 100644 index 00000000000..fa9f46b49f6 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-st-nested.json @@ -0,0 +1,42 @@ +{ + "tests": [ + { + "description": "update: nested ServerTimestamp field", + "comment": "A ServerTimestamp value can occur at any depth. In this case,\nthe transform applies to the field path \"b.c\". Since \"c\" is removed from the update,\n\"b\" becomes empty, so it is also removed from the update.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": {\"c\": \"ServerTimestamp\"}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a", + "b" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b.c", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-st-noarray-nested.json b/handwritten/firestore/dev/conformance/conformance-tests/update-st-noarray-nested.json new file mode 100644 index 00000000000..9f94501aa7f --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-st-noarray-nested.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: ServerTimestamp cannot be anywhere inside an array value", + "comment": "There cannot be an array value anywhere on the path from the document\nroot to the ServerTimestamp sentinel. Firestore transforms don't support array indexing.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, {\"b\": \"ServerTimestamp\"}]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-st-noarray.json b/handwritten/firestore/dev/conformance/conformance-tests/update-st-noarray.json new file mode 100644 index 00000000000..02615bd3ceb --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-st-noarray.json @@ -0,0 +1,13 @@ +{ + "tests": [ + { + "description": "update: ServerTimestamp cannot be in an array value", + "comment": "The ServerTimestamp sentinel must be the value of a field. Firestore\ntransforms don't support array indexing.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": [1, 2, \"ServerTimestamp\"]}", + "isError": true + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-st-with-empty-map.json b/handwritten/firestore/dev/conformance/conformance-tests/update-st-with-empty-map.json new file mode 100644 index 00000000000..4a2c27dfb01 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-st-with-empty-map.json @@ -0,0 +1,49 @@ +{ + "tests": [ + { + "description": "update: ServerTimestamp beside an empty map", + "comment": "When a ServerTimestamp and a map both reside inside a map, the\nServerTimestamp should be stripped out but the empty map should remain.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": {\"b\": {}, \"c\": \"ServerTimestamp\"}}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "mapValue": { + "fields": { + "b": { + "mapValue": { + "fields": {} + } + } + } + } + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "a.c", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-st.json b/handwritten/firestore/dev/conformance/conformance-tests/update-st.json new file mode 100644 index 00000000000..71d17f3c7a8 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-st.json @@ -0,0 +1,41 @@ +{ + "tests": [ + { + "description": "update: ServerTimestamp with data", + "comment": "A key with the special ServerTimestamp sentinel is removed from\nthe data in the update operation. Instead it appears in a separate Transform operation.\nNote that in these tests, the string \"ServerTimestamp\" should be replaced with the\nspecial ServerTimestamp value.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "jsonData": "{\"a\": 1, \"b\": \"ServerTimestamp\"}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "exists": true + }, + "updateTransforms": [ + { + "fieldPath": "b", + "setToServerValue": "REQUEST_TIME" + } + ] + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/conformance-tests/update-uptime.json b/handwritten/firestore/dev/conformance/conformance-tests/update-uptime.json new file mode 100644 index 00000000000..9210a2cf032 --- /dev/null +++ b/handwritten/firestore/dev/conformance/conformance-tests/update-uptime.json @@ -0,0 +1,38 @@ +{ + "tests": [ + { + "description": "update: last-update-time precondition", + "comment": "The Update call supports a last-update-time precondition.", + "update": { + "docRefPath": "projects/projectID/databases/(default)/documents/C/d", + "precondition": { + "updateTime": "1970-01-01T00:00:42Z" + }, + "jsonData": "{\"a\": 1}", + "request": { + "database": "projects/projectID/databases/(default)", + "writes": [ + { + "update": { + "name": "projects/projectID/databases/(default)/documents/C/d", + "fields": { + "a": { + "integerValue": "1" + } + } + }, + "updateMask": { + "fieldPaths": [ + "a" + ] + }, + "currentDocument": { + "updateTime": "1970-01-01T00:00:42Z" + } + } + ] + } + } + } + ] +} diff --git a/handwritten/firestore/dev/conformance/runner.ts b/handwritten/firestore/dev/conformance/runner.ts new file mode 100644 index 00000000000..54bf22e77d4 --- /dev/null +++ b/handwritten/firestore/dev/conformance/runner.ts @@ -0,0 +1,618 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {DocumentData} from '@google-cloud/firestore'; + +import * as duplexify from 'duplexify'; + +import {it, xit, describe} from 'mocha'; +import {expect} from 'chai'; +import * as path from 'path'; +import * as fs from 'fs'; +import * as protobufjs from 'protobufjs'; +import * as through2 from 'through2'; +import * as proto from '../protos/firestore_v1_proto_api'; + +import { + DocumentChange, + DocumentSnapshot, + FieldPath, + FieldValue, + Firestore, + Query, + QueryDocumentSnapshot, + QuerySnapshot, + Timestamp, +} from '../src'; +import {fieldsFromJson} from '../src/convert'; +import {DocumentChangeType} from '../src/document-change'; +import {QualifiedResourcePath} from '../src/path'; +import {UnaryMethod} from '../src/types'; +import {isObject} from '../src/util'; +import { + ApiOverride, + createInstance as createInstanceHelper, + response, +} from '../test/util/helpers'; + +import api = proto.google.firestore.v1; + +// TODO(mrschmidt): Create Protobuf .d.ts file for the conformance proto +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type ConformanceProto = any; + +/** List of test cases that are ignored. */ +const ignoredRe: RegExp[] = []; + +/** If non-empty, list the test cases to run exclusively. */ +const exclusiveRe: RegExp[] = []; + +// The project ID used in the conformance test protos. +const CONFORMANCE_TEST_PROJECT_ID = 'projectID'; + +// Load Protobuf definition and types +const protobufRoot = new protobufjs.Root(); +protobufRoot.resolvePath = (origin, target) => { + if (/^google\/.*/.test(target)) { + target = path.join(__dirname, '../protos', target); + } + return target; +}; +const protoDefinition = protobufRoot.loadSync( + path.join(__dirname, 'test-definition.proto'), +); + +const TEST_SUITE_TYPE = protoDefinition.lookupType('tests.TestFile'); +const STRUCTURED_QUERY_TYPE = protoDefinition.lookupType( + 'google.firestore.v1.StructuredQuery', +); +const COMMIT_REQUEST_TYPE = protoDefinition.lookupType( + 'google.firestore.v1.CommitRequest', +); + +// Firestore instance initialized by the test runner. +let firestore: Firestore; + +const docRef = (path: string) => { + const resourcePath = QualifiedResourcePath.fromSlashSeparatedString(path); + return firestore.doc(resourcePath.relativeName); +}; + +const collRef = (path: string) => { + const resourcePath = QualifiedResourcePath.fromSlashSeparatedString(path); + return firestore.collection(resourcePath.relativeName); +}; + +const watchQuery = () => { + return firestore.collection('C').orderBy('a'); +}; + +const createInstance = (overrides: ApiOverride) => { + return createInstanceHelper(overrides, { + projectId: CONFORMANCE_TEST_PROJECT_ID, + }).then(firestoreClient => { + firestore = firestoreClient; + }); +}; + +/** Converts JSON test data into JavaScript types suitable for the Node API. */ +const convertInput = { + argument: (json: ConformanceProto) => { + const obj = JSON.parse(json); + function convertValue(value: unknown) { + if (isObject(value)) { + return convertObject(value); + } else if (Array.isArray(value)) { + return convertArray(value); + } else if (value === 'NaN') { + return NaN; + } else if (value === 'Delete') { + return FieldValue.delete(); + } else if (value === 'ServerTimestamp') { + return FieldValue.serverTimestamp(); + } + + return value; + } + function convertArray(arr: unknown[]): unknown[] | FieldValue { + if (arr.length > 0 && arr[0] === 'ArrayUnion') { + return FieldValue.arrayUnion( + ...(convertArray(arr.slice(1)) as unknown[]), + ); + } else if (arr.length > 0 && arr[0] === 'ArrayRemove') { + return FieldValue.arrayRemove( + ...(convertArray(arr.slice(1)) as unknown[]), + ); + } else { + for (let i = 0; i < arr.length; ++i) { + arr[i] = convertValue(arr[i]); + } + return arr; + } + } + function convertObject(obj: {[k: string]: unknown}) { + for (const key of Object.keys(obj)) { + obj[key] = convertValue(obj[key]); + } + return obj; + } + return convertValue(obj); + }, + precondition: (precondition: string) => { + const deepCopy = JSON.parse(JSON.stringify(precondition)); + if (deepCopy.updateTime) { + deepCopy.lastUpdateTime = Timestamp.fromProto({ + seconds: deepCopy.updateTime.seconds, + nanos: deepCopy.updateTime.nanos, + }); + delete deepCopy.updateTime; + } + return deepCopy; + }, + path: (path: ConformanceProto) => { + if (path.field.length === 1 && path.field[0] === '__name__') { + return FieldPath.documentId(); + } + return new FieldPath(...path.field); + }, + paths: (fields: ConformanceProto): FieldPath[] => { + const convertedPaths: FieldPath[] = []; + if (fields) { + for (const field of fields) { + convertedPaths.push(convertInput.path(field)); + } + } else { + convertedPaths.push(FieldPath.documentId()); + } + return convertedPaths; + }, + cursor: (cursor: ConformanceProto) => { + const args: unknown[] = []; + if (cursor.docSnapshot) { + args.push( + DocumentSnapshot.fromObject( + docRef(cursor.docSnapshot.path), + convertInput.argument(cursor.docSnapshot.jsonData) as DocumentData, + ), + ); + } else { + for (const jsonValue of cursor.jsonValues) { + args.push(convertInput.argument(jsonValue)); + } + } + return args; + }, + snapshot: (snapshot: ConformanceProto): QuerySnapshot => { + const docs: QueryDocumentSnapshot[] = []; + const changes: DocumentChange[] = []; + const readTime = Timestamp.fromProto(snapshot.readTime); + + for (const doc of snapshot.docs) { + const deepCopy = JSON.parse(JSON.stringify(doc)); + deepCopy.fields = fieldsFromJson(deepCopy.fields); + docs.push( + firestore.snapshot_( + deepCopy, + readTime.toDate().toISOString(), + 'json', + ) as QueryDocumentSnapshot, + ); + } + + for (const change of snapshot.changes) { + const deepCopy = JSON.parse(JSON.stringify(change.doc)); + deepCopy.fields = fieldsFromJson(deepCopy.fields); + const doc = firestore.snapshot_( + deepCopy, + readTime.toDate().toISOString(), + 'json', + ) as QueryDocumentSnapshot; + const type = ['unspecified', 'added', 'removed', 'modified'][ + change.kind + ] as DocumentChangeType; + changes.push( + new DocumentChange(type, doc, change.oldIndex, change.newIndex), + ); + } + + return new QuerySnapshot( + watchQuery(), + readTime, + docs.length, + () => docs, + () => changes, + ); + }, +}; + +/** Converts Firestore Protobuf types in Proto3 JSON format to Protobuf JS. */ +const convertProto = { + targetChange: (type?: string) => type || 'NO_CHANGE', + listenResponse: (listenRequest: ConformanceProto) => { + const deepCopy = JSON.parse(JSON.stringify(listenRequest)); + if (deepCopy.targetChange) { + deepCopy.targetChange.targetChangeType = convertProto.targetChange( + deepCopy.targetChange.targetChangeType, + ); + } + if (deepCopy.documentChange) { + deepCopy.documentChange.document.fields = fieldsFromJson( + deepCopy.documentChange.document.fields, + ); + } + return deepCopy; + }, +}; + +/** Request handler for _commit. */ +function commitHandler( + spec: ConformanceProto, +): UnaryMethod { + return request => { + const actualCommit = COMMIT_REQUEST_TYPE.fromObject(request); + const expectedCommit = COMMIT_REQUEST_TYPE.fromObject(spec.request); + expect(actualCommit).to.deep.equal(expectedCommit); + const res: api.ICommitResponse = { + commitTime: {}, + writeResults: [], + }; + for (let i = 1; i <= request.writes!.length; ++i) { + res.writeResults!.push({ + updateTime: {}, + }); + } + return response(res); + }; +} + +/** Request handler for _runQuery. */ +function queryHandler(spec: ConformanceProto) { + return (request: api.IRunQueryRequest) => { + const actualQuery = STRUCTURED_QUERY_TYPE.fromObject( + request.structuredQuery!, + ); + const expectedQuery = STRUCTURED_QUERY_TYPE.fromObject(spec.query); + expect(actualQuery).to.deep.equal(expectedQuery); + const stream = through2.obj(); + setImmediate(() => { + // Empty query always emits a readTime + stream.push({readTime: {seconds: 0, nanos: 0}}); + stream.push(null); + }); + return stream; + }; +} + +/** Request handler for _batchGetDocuments. */ +function getHandler(spec: ConformanceProto) { + return (request: api.IBatchGetDocumentsRequest) => { + const getDocument = spec.request; + expect(request.documents![0]).to.equal(getDocument.name); + const stream = through2.obj(); + setImmediate(() => { + stream.push({ + missing: getDocument.name, + readTime: {seconds: 0, nanos: 0}, + }); + stream.push(null); + }); + return stream; + }; +} + +function runTest(spec: ConformanceProto) { + console.log(`Running Spec:\n${JSON.stringify(spec, null, 2)}\n`); + + const updateTest = (spec: ConformanceProto) => { + const overrides = {commit: commitHandler(spec)}; + return createInstance(overrides).then(() => { + const varargs: unknown[] = []; + + if (spec.jsonData) { + varargs[0] = convertInput.argument(spec.jsonData); + } else { + for (let i = 0; i < spec.fieldPaths.length; ++i) { + varargs[2 * i] = new FieldPath(...spec.fieldPaths[i].field); + } + for (let i = 0; i < spec.jsonValues.length; ++i) { + varargs[2 * i + 1] = convertInput.argument(spec.jsonValues[i]); + } + } + + if (spec.precondition) { + varargs.push(convertInput.precondition(spec.precondition)); + } + + const document = docRef(spec.docRefPath); + return document.update(varargs[0] as string, ...varargs.slice(1)); + }); + }; + + const queryTest = (spec: ConformanceProto) => { + const overrides = {runQuery: queryHandler(spec)}; + const applyClause = (query: Query, clause: ConformanceProto) => { + if (clause.select) { + query = query.select(...convertInput.paths(clause.select.fields)); + } else if (clause.where) { + const fieldPath = convertInput.path(clause.where.path); + const value = convertInput.argument(clause.where.jsonValue); + query = query.where(fieldPath, clause.where.op, value); + } else if (clause.orderBy) { + const fieldPath = convertInput.path(clause.orderBy.path); + query = query.orderBy(fieldPath, clause.orderBy.direction); + } else if (clause.offset) { + query = query.offset(clause.offset); + } else if (clause.limit) { + query = query.limit(clause.limit); + } else if (clause.startAt) { + const cursor = convertInput.cursor(clause.startAt); + query = query.startAt(...cursor); + } else if (clause.startAfter) { + const cursor = convertInput.cursor(clause.startAfter); + query = query.startAfter(...cursor); + } else if (clause.endAt) { + const cursor = convertInput.cursor(clause.endAt); + query = query.endAt(...cursor); + } else if (clause.endBefore) { + const cursor = convertInput.cursor(clause.endBefore); + query = query.endBefore(...cursor); + } + + return query; + }; + + return createInstance(overrides).then(() => { + let query: Query = collRef(spec.collPath); + for (const clause of spec.clauses) { + query = applyClause(query, clause); + } + return query.get(); + }); + }; + + const deleteTest = (spec: ConformanceProto) => { + const overrides = {commit: commitHandler(spec)}; + return createInstance(overrides).then(() => { + if (spec.precondition) { + const precondition = convertInput.precondition(deleteSpec.precondition); + return docRef(spec.docRefPath).delete(precondition); + } else { + return docRef(spec.docRefPath).delete(); + } + }); + }; + + const setTest = (spec: ConformanceProto) => { + const overrides = {commit: commitHandler(spec)}; + return createInstance(overrides).then(() => { + const setOption: {merge?: boolean; mergeFields?: FieldPath[]} = {}; + if (spec.option && spec.option.all) { + setOption.merge = true; + } else if (spec.option && spec.option.fields) { + setOption.mergeFields = []; + for (const fieldPath of spec.option.fields) { + setOption.mergeFields.push(new FieldPath(...fieldPath.field)); + } + } + return docRef(setSpec.docRefPath).set( + convertInput.argument(spec.jsonData) as DocumentData, + setOption, + ); + }); + }; + + const createTest = (spec: ConformanceProto) => { + const overrides = {commit: commitHandler(spec)}; + return createInstance(overrides).then(() => { + return docRef(spec.docRefPath).create( + convertInput.argument(spec.jsonData) as DocumentData, + ); + }); + }; + + const getTest = (spec: ConformanceProto) => { + const overrides = {batchGetDocuments: getHandler(spec)}; + return createInstance(overrides).then(() => { + return docRef(spec.docRefPath).get(); + }); + }; + + const watchTest = (spec: ConformanceProto) => { + const expectedSnapshots = spec.snapshots; + const writeStream = through2.obj(); + const overrides: ApiOverride = { + listen: () => duplexify.obj(through2.obj(), writeStream), + }; + + return createInstance(overrides).then(() => { + return new Promise((resolve, reject) => { + const unlisten = watchQuery().onSnapshot( + actualSnap => { + const expectedSnapshot = expectedSnapshots.shift(); + if (expectedSnapshot) { + if ( + !actualSnap.isEqual(convertInput.snapshot(expectedSnapshot)) + ) { + reject( + new Error('Expected and actual snapshots do not match.'), + ); + } + + if (expectedSnapshots.length === 0 || !spec.isError) { + unlisten(); + resolve(); + } + } else { + reject(new Error('Received unexpected snapshot')); + } + }, + err => { + expect(expectedSnapshots).to.have.length(0); + unlisten(); + reject(err); + }, + ); + + for (const response of spec.responses) { + writeStream.write(convertProto.listenResponse(response)); + } + }); + }); + }; + + let testSpec: ConformanceProto; + let testPromise; + + const getSpec = spec.get; + const createSpec = spec.create; + const setSpec = spec.set; + const updateSpec = spec.update || spec.updatePaths; + const deleteSpec = spec.delete; + const querySpec = spec.query; + const listenSpec = spec.listen; + + if (getSpec) { + testSpec = getSpec; + testPromise = getTest(getSpec); + } else if (createSpec) { + testSpec = createSpec; + testPromise = createTest(createSpec); + } else if (setSpec) { + testSpec = setSpec; + testPromise = setTest(setSpec); + } else if (updateSpec) { + testSpec = updateSpec; + testPromise = updateTest(updateSpec); + } else if (deleteSpec) { + testSpec = deleteSpec; + testPromise = deleteTest(deleteSpec); + } else if (querySpec) { + testSpec = querySpec; + testPromise = queryTest(querySpec); + } else if (listenSpec) { + testSpec = listenSpec; + testPromise = watchTest(listenSpec); + } else { + return Promise.reject(new Error(`Unhandled Spec: ${JSON.stringify(spec)}`)); + } + + return testPromise.then( + () => { + expect(testSpec.isError || false).to.be.false; + }, + err => { + if (!testSpec.isError) { + throw err; + } + }, + ); +} + +/** + * Parses through the TestFile and changes all instances of Timestamps encoded + * as strings to a proper protobuf type since protobufJS does not support it at + * the moment. + */ +function normalizeTimestamp(obj: Record) { + const fieldNames = ['updateTime', 'createTime', 'readTime']; + for (const key of Object.keys(obj)) { + if (fieldNames.includes(key) && typeof obj[key] === 'string') { + obj[key] = convertTimestamp(obj[key] as string); + } else if (typeof obj[key] === 'object') { + normalizeTimestamp(obj[key] as Record); + } + } +} + +/** + * Convert a string TimeStamp, e.g. "1970-01-01T00:00:42Z", to its protobuf + * type. + */ +function convertTimestamp(text: string): {[key: string]: number} { + const split = text.split(':'); + const secondsStr = split[split.length - 1]; + + // Remove trailing 'Z' from Timestamp + const seconds = Number(secondsStr.slice(0, secondsStr.length - 2)); + const frac = seconds - Math.floor(seconds); + + return { + seconds: Math.floor(seconds), + nanos: frac * 1e9, + }; +} + +/** + * Parses through the TestFile and changes all instances of Int32Values encoded + * as numbers to a proper protobuf type since protobufJS does not support it at + * the moment. + * + * We must include a parent field to properly catch which fields are standard + * values vs. Int32Values. In this case, the 'limit' field in 'clauses' has + * Value type, but the 'limit' field in 'query' has Int32Value type, resulting + * in the need for an extra layer of specificity. + */ +function normalizeInt32Value(obj: Record, parent = '') { + const fieldNames = ['limit']; + const parentNames = ['query']; + for (const key of Object.keys(obj)) { + if ( + fieldNames.includes(key) && + typeof obj[key] === 'number' && + parentNames.includes(parent) + ) { + obj[key] = { + value: obj[key], + }; + } else if (typeof obj[key] === 'object') { + normalizeInt32Value(obj[key] as Record, key); + } + } +} + +describe('Conformance Tests', () => { + const loadTestCases = () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let testDataJson: any[] = []; + + const testPath = path.join(__dirname, 'conformance-tests'); + const fileNames = fs.readdirSync(testPath); + for (const fileName of fileNames) { + const testFilePath = path.join(__dirname, 'conformance-tests', fileName); + const singleTest = JSON.parse(fs.readFileSync(testFilePath, 'utf-8')); + + // Convert Timestamp string representation to protobuf object. + normalizeTimestamp(singleTest); + + // Convert Int32Value to protobuf object. + normalizeInt32Value(singleTest); + + const testFile = TEST_SUITE_TYPE.fromObject(singleTest); + testDataJson = testDataJson.concat(testFile); + } + + return testDataJson.map(testFile => testFile.tests[0]); + }; + + for (const testCase of loadTestCases()) { + const isIgnored = ignoredRe.find(re => re.test(testCase.description)); + const isExclusive = exclusiveRe.find(re => re.test(testCase.description)); + + if (isIgnored || (exclusiveRe.length > 0 && !isExclusive)) { + xit(`${testCase.description}`, () => {}); + } else { + it(`${testCase.description}`, () => runTest(testCase)); + } + } +}); diff --git a/handwritten/firestore/dev/conformance/test-definition.proto b/handwritten/firestore/dev/conformance/test-definition.proto new file mode 100644 index 00000000000..c06a699ea53 --- /dev/null +++ b/handwritten/firestore/dev/conformance/test-definition.proto @@ -0,0 +1,197 @@ +// Tests for firestore clients. + +syntax = "proto3"; + +package tests; + +option php_namespace = "Google\\Cloud\\Firestore\\Tests\\Conformance"; +option csharp_namespace = "Google.Cloud.Firestore.Tests.Proto"; +option java_package = "com.google.cloud.firestore.conformance"; + +import "google/firestore/v1/common.proto"; +import "google/firestore/v1/document.proto"; +import "google/firestore/v1/firestore.proto"; +import "google/firestore/v1/query.proto"; +import "google/protobuf/timestamp.proto"; + +// A collection of tests. +message TestFile { + repeated Test tests = 1; +} + +// A Test describes a single client method call and its expected result. +message Test { + string description = 1; // short description of the test + string comment = 10; // a comment describing the behavior being tested + + oneof test { + GetTest get = 2; + CreateTest create = 3; + SetTest set = 4; + UpdateTest update = 5; + UpdatePathsTest update_paths = 6; + DeleteTest delete = 7; + QueryTest query = 8; + ListenTest listen = 9; + } +} + +// Call to the DocumentRef.Get method. +message GetTest { + // The path of the doc, e.g. "projects/projectID/databases/(default)/documents/C/d" + string doc_ref_path = 1; + + // The request that the call should send to the Firestore service. + google.firestore.v1.GetDocumentRequest request = 2; +} + +// Call to DocumentRef.Create. +message CreateTest { + // The path of the doc, e.g. "projects/projectID/databases/(default)/documents/C/d" + string doc_ref_path = 1; + + // The data passed to Create, as JSON. The strings "Delete" and "ServerTimestamp" + // denote the two special sentinel values. Values that could be interpreted as integers + // (i.e. digit strings) should be treated as integers. + string json_data = 2; + + // The request that the call should generate. + google.firestore.v1.CommitRequest request = 3; + + // If true, the call should result in an error without generating a request. + // If this is true, request should not be set. + bool is_error = 4; +} + +// A call to DocumentRef.Set. +message SetTest { + string doc_ref_path = 1; // path of doc + SetOption option = 2; // option to the Set call, if any + string json_data = 3; // data (see CreateTest.json_data) + google.firestore.v1.CommitRequest request = 4; // expected request + bool is_error = 5; // call signals an error +} + +// A call to the form of DocumentRef.Update that represents the data as a map +// or dictionary. +message UpdateTest { + string doc_ref_path = 1; // path of doc + google.firestore.v1.Precondition precondition = 2; // precondition in call, if any + string json_data = 3; // data (see CreateTest.json_data) + google.firestore.v1.CommitRequest request = 4; // expected request + bool is_error = 5; // call signals an error +} + +// A call to the form of DocumentRef.Update that represents the data as a list +// of field paths and their values. +message UpdatePathsTest { + string doc_ref_path = 1; // path of doc + google.firestore.v1.Precondition precondition = 2; // precondition in call, if any + // parallel sequences: field_paths[i] corresponds to json_values[i] + repeated FieldPath field_paths = 3; // the argument field paths + repeated string json_values = 4; // the argument values, as JSON + google.firestore.v1.CommitRequest request = 5; // expected rquest + bool is_error = 6; // call signals an error +} + +// A call to DocmentRef.Delete +message DeleteTest { + string doc_ref_path = 1; // path of doc + google.firestore.v1.Precondition precondition = 2; + google.firestore.v1.CommitRequest request = 3; // expected rquest + bool is_error = 4; // call signals an error +} + +// An option to the DocumentRef.Set call. +message SetOption { + bool all = 1; // if true, merge all fields ("fields" is ignored). + repeated FieldPath fields = 2; // field paths for a Merge option +} + +message QueryTest { + string coll_path = 1; // path of collection, e.g. "projects/projectID/databases/(default)/documents/C" + repeated Clause clauses = 2; + google.firestore.v1.StructuredQuery query = 3; + bool is_error = 4; +} + +message Clause { + oneof clause { + Select select = 1; + Where where = 2; + OrderBy order_by = 3; + int32 offset = 4; + int32 limit = 5; + Cursor start_at = 6; + Cursor start_after = 7; + Cursor end_at = 8; + Cursor end_before = 9; + } +} + +message Select { + repeated FieldPath fields = 1; +} + +message Where { + FieldPath path = 1; + string op = 2; + string json_value = 3; +} + +message OrderBy { + FieldPath path = 1; + string direction = 2; // "asc" or "desc" +} + +message Cursor { + // one of: + DocSnapshot doc_snapshot = 1; + repeated string json_values = 2; +} + +message DocSnapshot { + string path = 1; + string json_data = 2; +} + +message FieldPath { + repeated string field = 1; +} + +// A test of the Listen streaming RPC (a.k.a. FireStore watch). +// If the sequence of responses is provided to the implementation, +// it should produce the sequence of snapshots. +// If is_error is true, an error should occur after the snapshots. +// +// The tests assume that the query is +// Collection("projects/projectID/databases/(default)/documents/C").OrderBy("a", Ascending) +// +// The watch target ID used in these tests is 1. Test interpreters +// should either change their client's ID for testing, +// or change the ID in the tests before running them. +message ListenTest { + repeated google.firestore.v1.ListenResponse responses = 1; + repeated Snapshot snapshots = 2; + bool is_error = 3; +} + +message Snapshot { + repeated google.firestore.v1.Document docs = 1; + repeated DocChange changes = 2; + google.protobuf.Timestamp read_time = 3; +} + +message DocChange { + enum Kind { + KIND_UNSPECIFIED = 0; + ADDED = 1; + REMOVED = 2; + MODIFIED = 3; + } + + Kind kind = 1; + google.firestore.v1.Document doc = 2; + int32 old_index = 3; + int32 new_index = 4; +} diff --git a/handwritten/firestore/dev/protos/admin_v1.json b/handwritten/firestore/dev/protos/admin_v1.json new file mode 100644 index 00000000000..e39436cd1b8 --- /dev/null +++ b/handwritten/firestore/dev/protos/admin_v1.json @@ -0,0 +1,4835 @@ +{ + "nested": { + "google": { + "nested": { + "firestore": { + "nested": { + "admin": { + "nested": { + "v1": { + "options": { + "csharp_namespace": "Google.Cloud.Firestore.Admin.V1", + "go_package": "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb", + "java_multiple_files": true, + "java_outer_classname": "LocationProto", + "java_package": "com.google.firestore.admin.v1", + "objc_class_prefix": "GCFS", + "php_namespace": "Google\\Cloud\\Firestore\\Admin\\V1", + "ruby_package": "Google::Cloud::Firestore::Admin::V1", + "(google.api.resource_definition).type": "firestore.googleapis.com/CollectionGroup", + "(google.api.resource_definition).pattern": "projects/{project}/databases/{database}/collectionGroups/{collection}" + }, + "nested": { + "Backup": { + "options": { + "(google.api.resource).type": "firestore.googleapis.com/Backup", + "(google.api.resource).pattern": "projects/{project}/locations/{location}/backups/{backup}" + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "database": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY", + "(google.api.resource_reference).type": "firestore.googleapis.com/Database" + } + }, + "databaseUid": { + "type": "string", + "id": 7, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "snapshotTime": { + "type": "google.protobuf.Timestamp", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "expireTime": { + "type": "google.protobuf.Timestamp", + "id": 4, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "stats": { + "type": "Stats", + "id": 6, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "state": { + "type": "State", + "id": 8, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + }, + "nested": { + "Stats": { + "fields": { + "sizeBytes": { + "type": "int64", + "id": 1, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "documentCount": { + "type": "int64", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "indexCount": { + "type": "int64", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + } + }, + "State": { + "values": { + "STATE_UNSPECIFIED": 0, + "CREATING": 1, + "READY": 2, + "NOT_AVAILABLE": 3 + } + } + } + }, + "Database": { + "options": { + "(google.api.resource).type": "firestore.googleapis.com/Database", + "(google.api.resource).pattern": "projects/{project}/databases/{database}", + "(google.api.resource).style": "DECLARATIVE_FRIENDLY" + }, + "oneofs": { + "_freeTier": { + "oneof": [ + "freeTier" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "uid": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "createTime": { + "type": "google.protobuf.Timestamp", + "id": 5, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "updateTime": { + "type": "google.protobuf.Timestamp", + "id": 6, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "deleteTime": { + "type": "google.protobuf.Timestamp", + "id": 7, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "locationId": { + "type": "string", + "id": 9 + }, + "type": { + "type": "DatabaseType", + "id": 10 + }, + "concurrencyMode": { + "type": "ConcurrencyMode", + "id": 15 + }, + "versionRetentionPeriod": { + "type": "google.protobuf.Duration", + "id": 17, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "earliestVersionTime": { + "type": "google.protobuf.Timestamp", + "id": 18, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "pointInTimeRecoveryEnablement": { + "type": "PointInTimeRecoveryEnablement", + "id": 21 + }, + "appEngineIntegrationMode": { + "type": "AppEngineIntegrationMode", + "id": 19 + }, + "keyPrefix": { + "type": "string", + "id": 20, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "deleteProtectionState": { + "type": "DeleteProtectionState", + "id": 22 + }, + "cmekConfig": { + "type": "CmekConfig", + "id": 23, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "previousId": { + "type": "string", + "id": 25, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "sourceInfo": { + "type": "SourceInfo", + "id": 26, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "tags": { + "keyType": "string", + "type": "string", + "id": 29, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "freeTier": { + "type": "bool", + "id": 30, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY", + "proto3_optional": true + } + }, + "etag": { + "type": "string", + "id": 99 + }, + "databaseEdition": { + "type": "DatabaseEdition", + "id": 28, + "options": { + "(google.api.field_behavior)": "IMMUTABLE" + } + } + }, + "nested": { + "DatabaseType": { + "values": { + "DATABASE_TYPE_UNSPECIFIED": 0, + "FIRESTORE_NATIVE": 1, + "DATASTORE_MODE": 2 + } + }, + "ConcurrencyMode": { + "values": { + "CONCURRENCY_MODE_UNSPECIFIED": 0, + "OPTIMISTIC": 1, + "PESSIMISTIC": 2, + "OPTIMISTIC_WITH_ENTITY_GROUPS": 3 + } + }, + "PointInTimeRecoveryEnablement": { + "values": { + "POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED": 0, + "POINT_IN_TIME_RECOVERY_ENABLED": 1, + "POINT_IN_TIME_RECOVERY_DISABLED": 2 + } + }, + "AppEngineIntegrationMode": { + "values": { + "APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED": 0, + "ENABLED": 1, + "DISABLED": 2 + } + }, + "DeleteProtectionState": { + "values": { + "DELETE_PROTECTION_STATE_UNSPECIFIED": 0, + "DELETE_PROTECTION_DISABLED": 1, + "DELETE_PROTECTION_ENABLED": 2 + } + }, + "CmekConfig": { + "fields": { + "kmsKeyName": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "activeKeyVersion": { + "rule": "repeated", + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + } + }, + "SourceInfo": { + "oneofs": { + "source": { + "oneof": [ + "backup" + ] + } + }, + "fields": { + "backup": { + "type": "BackupSource", + "id": 1 + }, + "operation": { + "type": "string", + "id": 3, + "options": { + "(google.api.resource_reference).type": "firestore.googleapis.com/Operation" + } + } + }, + "nested": { + "BackupSource": { + "fields": { + "backup": { + "type": "string", + "id": 1, + "options": { + "(google.api.resource_reference).type": "firestore.googleapis.com/Backup" + } + } + } + } + } + }, + "EncryptionConfig": { + "oneofs": { + "encryptionType": { + "oneof": [ + "googleDefaultEncryption", + "useSourceEncryption", + "customerManagedEncryption" + ] + } + }, + "fields": { + "googleDefaultEncryption": { + "type": "GoogleDefaultEncryptionOptions", + "id": 1 + }, + "useSourceEncryption": { + "type": "SourceEncryptionOptions", + "id": 2 + }, + "customerManagedEncryption": { + "type": "CustomerManagedEncryptionOptions", + "id": 3 + } + }, + "nested": { + "GoogleDefaultEncryptionOptions": { + "fields": {} + }, + "SourceEncryptionOptions": { + "fields": {} + }, + "CustomerManagedEncryptionOptions": { + "fields": { + "kmsKeyName": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + } + } + }, + "DatabaseEdition": { + "values": { + "DATABASE_EDITION_UNSPECIFIED": 0, + "STANDARD": 1, + "ENTERPRISE": 2 + } + } + } + }, + "Field": { + "options": { + "(google.api.resource).type": "firestore.googleapis.com/Field", + "(google.api.resource).pattern": "projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}" + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "indexConfig": { + "type": "IndexConfig", + "id": 2 + }, + "ttlConfig": { + "type": "TtlConfig", + "id": 3 + } + }, + "nested": { + "IndexConfig": { + "fields": { + "indexes": { + "rule": "repeated", + "type": "Index", + "id": 1 + }, + "usesAncestorConfig": { + "type": "bool", + "id": 2 + }, + "ancestorField": { + "type": "string", + "id": 3 + }, + "reverting": { + "type": "bool", + "id": 4 + } + } + }, + "TtlConfig": { + "fields": { + "state": { + "type": "State", + "id": 1, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + }, + "nested": { + "State": { + "values": { + "STATE_UNSPECIFIED": 0, + "CREATING": 1, + "ACTIVE": 2, + "NEEDS_REPAIR": 3 + } + } + } + } + } + }, + "Index": { + "options": { + "(google.api.resource).type": "firestore.googleapis.com/Index", + "(google.api.resource).pattern": "projects/{project}/databases/{database}/collectionGroups/{collection}/indexes/{index}" + }, + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "queryScope": { + "type": "QueryScope", + "id": 2 + }, + "apiScope": { + "type": "ApiScope", + "id": 5 + }, + "fields": { + "rule": "repeated", + "type": "IndexField", + "id": 3 + }, + "state": { + "type": "State", + "id": 4 + }, + "density": { + "type": "Density", + "id": 6, + "options": { + "(google.api.field_behavior)": "IMMUTABLE" + } + }, + "multikey": { + "type": "bool", + "id": 7, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "shardCount": { + "type": "int32", + "id": 8, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "QueryScope": { + "values": { + "QUERY_SCOPE_UNSPECIFIED": 0, + "COLLECTION": 1, + "COLLECTION_GROUP": 2, + "COLLECTION_RECURSIVE": 3 + } + }, + "ApiScope": { + "values": { + "ANY_API": 0, + "DATASTORE_MODE_API": 1, + "MONGODB_COMPATIBLE_API": 2 + } + }, + "IndexField": { + "oneofs": { + "valueMode": { + "oneof": [ + "order", + "arrayConfig", + "vectorConfig" + ] + } + }, + "fields": { + "fieldPath": { + "type": "string", + "id": 1 + }, + "order": { + "type": "Order", + "id": 2 + }, + "arrayConfig": { + "type": "ArrayConfig", + "id": 3 + }, + "vectorConfig": { + "type": "VectorConfig", + "id": 4 + } + }, + "nested": { + "Order": { + "values": { + "ORDER_UNSPECIFIED": 0, + "ASCENDING": 1, + "DESCENDING": 2 + } + }, + "ArrayConfig": { + "values": { + "ARRAY_CONFIG_UNSPECIFIED": 0, + "CONTAINS": 1 + } + }, + "VectorConfig": { + "oneofs": { + "type": { + "oneof": [ + "flat" + ] + } + }, + "fields": { + "dimension": { + "type": "int32", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "flat": { + "type": "FlatIndex", + "id": 2 + } + }, + "nested": { + "FlatIndex": { + "fields": {} + } + } + } + } + }, + "State": { + "values": { + "STATE_UNSPECIFIED": 0, + "CREATING": 1, + "READY": 2, + "NEEDS_REPAIR": 3 + } + }, + "Density": { + "values": { + "DENSITY_UNSPECIFIED": 0, + "SPARSE_ALL": 1, + "SPARSE_ANY": 2, + "DENSE": 3 + } + } + } + }, + "FirestoreAdmin": { + "options": { + "(google.api.default_host)": "firestore.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/datastore" + }, + "methods": { + "CreateIndex": { + "requestType": "CreateIndexRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/collectionGroups/*}/indexes", + "(google.api.http).body": "index", + "(google.api.method_signature)": "parent,index", + "(google.longrunning.operation_info).response_type": "Index", + "(google.longrunning.operation_info).metadata_type": "IndexOperationMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/databases/*/collectionGroups/*}/indexes", + "body": "index" + } + }, + { + "(google.api.method_signature)": "parent,index" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "Index", + "metadata_type": "IndexOperationMetadata" + } + } + ] + }, + "ListIndexes": { + "requestType": "ListIndexesRequest", + "responseType": "ListIndexesResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*/databases/*/collectionGroups/*}/indexes", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*/databases/*/collectionGroups/*}/indexes" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "GetIndex": { + "requestType": "GetIndexRequest", + "responseType": "Index", + "options": { + "(google.api.http).get": "/v1/{name=projects/*/databases/*/collectionGroups/*/indexes/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=projects/*/databases/*/collectionGroups/*/indexes/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "DeleteIndex": { + "requestType": "DeleteIndexRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=projects/*/databases/*/collectionGroups/*/indexes/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=projects/*/databases/*/collectionGroups/*/indexes/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "GetField": { + "requestType": "GetFieldRequest", + "responseType": "Field", + "options": { + "(google.api.http).get": "/v1/{name=projects/*/databases/*/collectionGroups/*/fields/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=projects/*/databases/*/collectionGroups/*/fields/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "UpdateField": { + "requestType": "UpdateFieldRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).patch": "/v1/{field.name=projects/*/databases/*/collectionGroups/*/fields/*}", + "(google.api.http).body": "field", + "(google.api.method_signature)": "field", + "(google.longrunning.operation_info).response_type": "Field", + "(google.longrunning.operation_info).metadata_type": "FieldOperationMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "patch": "/v1/{field.name=projects/*/databases/*/collectionGroups/*/fields/*}", + "body": "field" + } + }, + { + "(google.api.method_signature)": "field" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "Field", + "metadata_type": "FieldOperationMetadata" + } + } + ] + }, + "ListFields": { + "requestType": "ListFieldsRequest", + "responseType": "ListFieldsResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*/databases/*/collectionGroups/*}/fields", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*/databases/*/collectionGroups/*}/fields" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "ExportDocuments": { + "requestType": "ExportDocumentsRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).post": "/v1/{name=projects/*/databases/*}:exportDocuments", + "(google.api.http).body": "*", + "(google.api.method_signature)": "name", + "(google.longrunning.operation_info).response_type": "ExportDocumentsResponse", + "(google.longrunning.operation_info).metadata_type": "ExportDocumentsMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{name=projects/*/databases/*}:exportDocuments", + "body": "*" + } + }, + { + "(google.api.method_signature)": "name" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "ExportDocumentsResponse", + "metadata_type": "ExportDocumentsMetadata" + } + } + ] + }, + "ImportDocuments": { + "requestType": "ImportDocumentsRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).post": "/v1/{name=projects/*/databases/*}:importDocuments", + "(google.api.http).body": "*", + "(google.api.method_signature)": "name", + "(google.longrunning.operation_info).response_type": "google.protobuf.Empty", + "(google.longrunning.operation_info).metadata_type": "ImportDocumentsMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{name=projects/*/databases/*}:importDocuments", + "body": "*" + } + }, + { + "(google.api.method_signature)": "name" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "google.protobuf.Empty", + "metadata_type": "ImportDocumentsMetadata" + } + } + ] + }, + "BulkDeleteDocuments": { + "requestType": "BulkDeleteDocumentsRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).post": "/v1/{name=projects/*/databases/*}:bulkDeleteDocuments", + "(google.api.http).body": "*", + "(google.api.method_signature)": "name", + "(google.longrunning.operation_info).response_type": "BulkDeleteDocumentsResponse", + "(google.longrunning.operation_info).metadata_type": "BulkDeleteDocumentsMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{name=projects/*/databases/*}:bulkDeleteDocuments", + "body": "*" + } + }, + { + "(google.api.method_signature)": "name" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "BulkDeleteDocumentsResponse", + "metadata_type": "BulkDeleteDocumentsMetadata" + } + } + ] + }, + "CreateDatabase": { + "requestType": "CreateDatabaseRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*}/databases", + "(google.api.http).body": "database", + "(google.api.method_signature)": "parent,database,database_id", + "(google.longrunning.operation_info).response_type": "Database", + "(google.longrunning.operation_info).metadata_type": "CreateDatabaseMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*}/databases", + "body": "database" + } + }, + { + "(google.api.method_signature)": "parent,database,database_id" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "Database", + "metadata_type": "CreateDatabaseMetadata" + } + } + ] + }, + "GetDatabase": { + "requestType": "GetDatabaseRequest", + "responseType": "Database", + "options": { + "(google.api.http).get": "/v1/{name=projects/*/databases/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=projects/*/databases/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "ListDatabases": { + "requestType": "ListDatabasesRequest", + "responseType": "ListDatabasesResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*}/databases", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*}/databases" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "UpdateDatabase": { + "requestType": "UpdateDatabaseRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).patch": "/v1/{database.name=projects/*/databases/*}", + "(google.api.http).body": "database", + "(google.api.method_signature)": "database,update_mask", + "(google.longrunning.operation_info).response_type": "Database", + "(google.longrunning.operation_info).metadata_type": "UpdateDatabaseMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "patch": "/v1/{database.name=projects/*/databases/*}", + "body": "database" + } + }, + { + "(google.api.method_signature)": "database,update_mask" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "Database", + "metadata_type": "UpdateDatabaseMetadata" + } + } + ] + }, + "DeleteDatabase": { + "requestType": "DeleteDatabaseRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).delete": "/v1/{name=projects/*/databases/*}", + "(google.api.method_signature)": "name", + "(google.longrunning.operation_info).response_type": "Database", + "(google.longrunning.operation_info).metadata_type": "DeleteDatabaseMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=projects/*/databases/*}" + } + }, + { + "(google.api.method_signature)": "name" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "Database", + "metadata_type": "DeleteDatabaseMetadata" + } + } + ] + }, + "CreateUserCreds": { + "requestType": "CreateUserCredsRequest", + "responseType": "UserCreds", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*}/userCreds", + "(google.api.http).body": "user_creds", + "(google.api.method_signature)": "parent,user_creds,user_creds_id" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/databases/*}/userCreds", + "body": "user_creds" + } + }, + { + "(google.api.method_signature)": "parent,user_creds,user_creds_id" + } + ] + }, + "GetUserCreds": { + "requestType": "GetUserCredsRequest", + "responseType": "UserCreds", + "options": { + "(google.api.http).get": "/v1/{name=projects/*/databases/*/userCreds/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=projects/*/databases/*/userCreds/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "ListUserCreds": { + "requestType": "ListUserCredsRequest", + "responseType": "ListUserCredsResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*/databases/*}/userCreds", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*/databases/*}/userCreds" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "EnableUserCreds": { + "requestType": "EnableUserCredsRequest", + "responseType": "UserCreds", + "options": { + "(google.api.http).post": "/v1/{name=projects/*/databases/*/userCreds/*}:enable", + "(google.api.http).body": "*", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{name=projects/*/databases/*/userCreds/*}:enable", + "body": "*" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "DisableUserCreds": { + "requestType": "DisableUserCredsRequest", + "responseType": "UserCreds", + "options": { + "(google.api.http).post": "/v1/{name=projects/*/databases/*/userCreds/*}:disable", + "(google.api.http).body": "*", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{name=projects/*/databases/*/userCreds/*}:disable", + "body": "*" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "ResetUserPassword": { + "requestType": "ResetUserPasswordRequest", + "responseType": "UserCreds", + "options": { + "(google.api.http).post": "/v1/{name=projects/*/databases/*/userCreds/*}:resetPassword", + "(google.api.http).body": "*", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{name=projects/*/databases/*/userCreds/*}:resetPassword", + "body": "*" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "DeleteUserCreds": { + "requestType": "DeleteUserCredsRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=projects/*/databases/*/userCreds/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=projects/*/databases/*/userCreds/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "GetBackup": { + "requestType": "GetBackupRequest", + "responseType": "Backup", + "options": { + "(google.api.http).get": "/v1/{name=projects/*/locations/*/backups/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=projects/*/locations/*/backups/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "ListBackups": { + "requestType": "ListBackupsRequest", + "responseType": "ListBackupsResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*/locations/*}/backups", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*/locations/*}/backups" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "DeleteBackup": { + "requestType": "DeleteBackupRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=projects/*/locations/*/backups/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=projects/*/locations/*/backups/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "RestoreDatabase": { + "requestType": "RestoreDatabaseRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*}/databases:restore", + "(google.api.http).body": "*", + "(google.longrunning.operation_info).response_type": "Database", + "(google.longrunning.operation_info).metadata_type": "RestoreDatabaseMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*}/databases:restore", + "body": "*" + } + }, + { + "(google.longrunning.operation_info)": { + "response_type": "Database", + "metadata_type": "RestoreDatabaseMetadata" + } + } + ] + }, + "CreateBackupSchedule": { + "requestType": "CreateBackupScheduleRequest", + "responseType": "BackupSchedule", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*}/backupSchedules", + "(google.api.http).body": "backup_schedule", + "(google.api.method_signature)": "parent,backup_schedule" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/databases/*}/backupSchedules", + "body": "backup_schedule" + } + }, + { + "(google.api.method_signature)": "parent,backup_schedule" + } + ] + }, + "GetBackupSchedule": { + "requestType": "GetBackupScheduleRequest", + "responseType": "BackupSchedule", + "options": { + "(google.api.http).get": "/v1/{name=projects/*/databases/*/backupSchedules/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=projects/*/databases/*/backupSchedules/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "ListBackupSchedules": { + "requestType": "ListBackupSchedulesRequest", + "responseType": "ListBackupSchedulesResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*/databases/*}/backupSchedules", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*/databases/*}/backupSchedules" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "UpdateBackupSchedule": { + "requestType": "UpdateBackupScheduleRequest", + "responseType": "BackupSchedule", + "options": { + "(google.api.http).patch": "/v1/{backup_schedule.name=projects/*/databases/*/backupSchedules/*}", + "(google.api.http).body": "backup_schedule", + "(google.api.method_signature)": "backup_schedule,update_mask" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "patch": "/v1/{backup_schedule.name=projects/*/databases/*/backupSchedules/*}", + "body": "backup_schedule" + } + }, + { + "(google.api.method_signature)": "backup_schedule,update_mask" + } + ] + }, + "DeleteBackupSchedule": { + "requestType": "DeleteBackupScheduleRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=projects/*/databases/*/backupSchedules/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=projects/*/databases/*/backupSchedules/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "CloneDatabase": { + "requestType": "CloneDatabaseRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*}/databases:clone", + "(google.api.http).body": "*", + "(google.api.routing).routing_parameters.field": "pitr_snapshot.database", + "(google.api.routing).routing_parameters.path_template": "projects/*/databases/{database_id=*}/**", + "(google.longrunning.operation_info).response_type": "Database", + "(google.longrunning.operation_info).metadata_type": "CloneDatabaseMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*}/databases:clone", + "body": "*" + } + }, + { + "(google.api.routing)": { + "routing_parameters": [ + { + "field": "pitr_snapshot.database", + "path_template": "projects/{project_id=*}/**" + }, + { + "field": "pitr_snapshot.database", + "path_template": "projects/*/databases/{database_id=*}/**" + } + ] + } + }, + { + "(google.longrunning.operation_info)": { + "response_type": "Database", + "metadata_type": "CloneDatabaseMetadata" + } + } + ] + } + } + }, + "ListDatabasesRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "firestore.googleapis.com/Database" + } + }, + "showDeleted": { + "type": "bool", + "id": 4 + } + } + }, + "CreateDatabaseRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "firestore.googleapis.com/Database" + } + }, + "database": { + "type": "Database", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "databaseId": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "CreateDatabaseMetadata": { + "fields": {} + }, + "ListDatabasesResponse": { + "fields": { + "databases": { + "rule": "repeated", + "type": "Database", + "id": 1 + }, + "unreachable": { + "rule": "repeated", + "type": "string", + "id": 3 + } + } + }, + "GetDatabaseRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/Database" + } + } + } + }, + "UpdateDatabaseRequest": { + "fields": { + "database": { + "type": "Database", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "updateMask": { + "type": "google.protobuf.FieldMask", + "id": 2 + } + } + }, + "UpdateDatabaseMetadata": { + "fields": {} + }, + "DeleteDatabaseRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/Database" + } + }, + "etag": { + "type": "string", + "id": 3 + } + } + }, + "DeleteDatabaseMetadata": { + "fields": {} + }, + "CreateUserCredsRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "firestore.googleapis.com/UserCreds" + } + }, + "userCreds": { + "type": "UserCreds", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "userCredsId": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "GetUserCredsRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/UserCreds" + } + } + } + }, + "ListUserCredsRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "firestore.googleapis.com/UserCreds" + } + } + } + }, + "ListUserCredsResponse": { + "fields": { + "userCreds": { + "rule": "repeated", + "type": "UserCreds", + "id": 1 + } + } + }, + "EnableUserCredsRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/UserCreds" + } + } + } + }, + "DisableUserCredsRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/UserCreds" + } + } + } + }, + "ResetUserPasswordRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/UserCreds" + } + } + } + }, + "DeleteUserCredsRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/UserCreds" + } + } + } + }, + "CreateBackupScheduleRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/Database" + } + }, + "backupSchedule": { + "type": "BackupSchedule", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "GetBackupScheduleRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/BackupSchedule" + } + } + } + }, + "UpdateBackupScheduleRequest": { + "fields": { + "backupSchedule": { + "type": "BackupSchedule", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "updateMask": { + "type": "google.protobuf.FieldMask", + "id": 2 + } + } + }, + "ListBackupSchedulesRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/Database" + } + } + } + }, + "ListBackupSchedulesResponse": { + "fields": { + "backupSchedules": { + "rule": "repeated", + "type": "BackupSchedule", + "id": 1 + } + } + }, + "DeleteBackupScheduleRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/BackupSchedule" + } + } + } + }, + "CreateIndexRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/CollectionGroup" + } + }, + "index": { + "type": "Index", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "ListIndexesRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/CollectionGroup" + } + }, + "filter": { + "type": "string", + "id": 2 + }, + "pageSize": { + "type": "int32", + "id": 3 + }, + "pageToken": { + "type": "string", + "id": 4 + } + } + }, + "ListIndexesResponse": { + "fields": { + "indexes": { + "rule": "repeated", + "type": "Index", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "GetIndexRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/Index" + } + } + } + }, + "DeleteIndexRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/Index" + } + } + } + }, + "UpdateFieldRequest": { + "fields": { + "field": { + "type": "Field", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "updateMask": { + "type": "google.protobuf.FieldMask", + "id": 2 + } + } + }, + "GetFieldRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/Field" + } + } + } + }, + "ListFieldsRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/CollectionGroup" + } + }, + "filter": { + "type": "string", + "id": 2 + }, + "pageSize": { + "type": "int32", + "id": 3 + }, + "pageToken": { + "type": "string", + "id": 4 + } + } + }, + "ListFieldsResponse": { + "fields": { + "fields": { + "rule": "repeated", + "type": "Field", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "ExportDocumentsRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/Database" + } + }, + "collectionIds": { + "rule": "repeated", + "type": "string", + "id": 2 + }, + "outputUriPrefix": { + "type": "string", + "id": 3 + }, + "namespaceIds": { + "rule": "repeated", + "type": "string", + "id": 4 + }, + "snapshotTime": { + "type": "google.protobuf.Timestamp", + "id": 5 + } + } + }, + "ImportDocumentsRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/Database" + } + }, + "collectionIds": { + "rule": "repeated", + "type": "string", + "id": 2 + }, + "inputUriPrefix": { + "type": "string", + "id": 3 + }, + "namespaceIds": { + "rule": "repeated", + "type": "string", + "id": 4 + } + } + }, + "BulkDeleteDocumentsRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/Database" + } + }, + "collectionIds": { + "rule": "repeated", + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "namespaceIds": { + "rule": "repeated", + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "BulkDeleteDocumentsResponse": { + "fields": {} + }, + "GetBackupRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/Backup" + } + } + } + }, + "ListBackupsRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/Location" + } + }, + "filter": { + "type": "string", + "id": 2 + } + } + }, + "ListBackupsResponse": { + "fields": { + "backups": { + "rule": "repeated", + "type": "Backup", + "id": 1 + }, + "unreachable": { + "rule": "repeated", + "type": "string", + "id": 3 + } + } + }, + "DeleteBackupRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/Backup" + } + } + } + }, + "RestoreDatabaseRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "firestore.googleapis.com/Database" + } + }, + "databaseId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "backup": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/Backup" + } + }, + "encryptionConfig": { + "type": "Database.EncryptionConfig", + "id": 9, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "tags": { + "keyType": "string", + "type": "string", + "id": 10, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "CloneDatabaseRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "firestore.googleapis.com/Database" + } + }, + "databaseId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "pitrSnapshot": { + "type": "PitrSnapshot", + "id": 6, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "encryptionConfig": { + "type": "Database.EncryptionConfig", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "tags": { + "keyType": "string", + "type": "string", + "id": 5, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "IndexOperationMetadata": { + "fields": { + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "endTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "index": { + "type": "string", + "id": 3 + }, + "state": { + "type": "OperationState", + "id": 4 + }, + "progressDocuments": { + "type": "Progress", + "id": 5 + }, + "progressBytes": { + "type": "Progress", + "id": 6 + } + } + }, + "FieldOperationMetadata": { + "fields": { + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "endTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "field": { + "type": "string", + "id": 3 + }, + "indexConfigDeltas": { + "rule": "repeated", + "type": "IndexConfigDelta", + "id": 4 + }, + "state": { + "type": "OperationState", + "id": 5 + }, + "progressDocuments": { + "type": "Progress", + "id": 6 + }, + "progressBytes": { + "type": "Progress", + "id": 7 + }, + "ttlConfigDelta": { + "type": "TtlConfigDelta", + "id": 8 + } + }, + "nested": { + "IndexConfigDelta": { + "fields": { + "changeType": { + "type": "ChangeType", + "id": 1 + }, + "index": { + "type": "Index", + "id": 2 + } + }, + "nested": { + "ChangeType": { + "values": { + "CHANGE_TYPE_UNSPECIFIED": 0, + "ADD": 1, + "REMOVE": 2 + } + } + } + }, + "TtlConfigDelta": { + "fields": { + "changeType": { + "type": "ChangeType", + "id": 1 + } + }, + "nested": { + "ChangeType": { + "values": { + "CHANGE_TYPE_UNSPECIFIED": 0, + "ADD": 1, + "REMOVE": 2 + } + } + } + } + } + }, + "ExportDocumentsMetadata": { + "fields": { + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "endTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "operationState": { + "type": "OperationState", + "id": 3 + }, + "progressDocuments": { + "type": "Progress", + "id": 4 + }, + "progressBytes": { + "type": "Progress", + "id": 5 + }, + "collectionIds": { + "rule": "repeated", + "type": "string", + "id": 6 + }, + "outputUriPrefix": { + "type": "string", + "id": 7 + }, + "namespaceIds": { + "rule": "repeated", + "type": "string", + "id": 8 + }, + "snapshotTime": { + "type": "google.protobuf.Timestamp", + "id": 9 + } + } + }, + "ImportDocumentsMetadata": { + "fields": { + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "endTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "operationState": { + "type": "OperationState", + "id": 3 + }, + "progressDocuments": { + "type": "Progress", + "id": 4 + }, + "progressBytes": { + "type": "Progress", + "id": 5 + }, + "collectionIds": { + "rule": "repeated", + "type": "string", + "id": 6 + }, + "inputUriPrefix": { + "type": "string", + "id": 7 + }, + "namespaceIds": { + "rule": "repeated", + "type": "string", + "id": 8 + } + } + }, + "BulkDeleteDocumentsMetadata": { + "fields": { + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "endTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "operationState": { + "type": "OperationState", + "id": 3 + }, + "progressDocuments": { + "type": "Progress", + "id": 4 + }, + "progressBytes": { + "type": "Progress", + "id": 5 + }, + "collectionIds": { + "rule": "repeated", + "type": "string", + "id": 6 + }, + "namespaceIds": { + "rule": "repeated", + "type": "string", + "id": 7 + }, + "snapshotTime": { + "type": "google.protobuf.Timestamp", + "id": 8 + } + } + }, + "ExportDocumentsResponse": { + "fields": { + "outputUriPrefix": { + "type": "string", + "id": 1 + } + } + }, + "RestoreDatabaseMetadata": { + "fields": { + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "endTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "operationState": { + "type": "OperationState", + "id": 3 + }, + "database": { + "type": "string", + "id": 4, + "options": { + "(google.api.resource_reference).type": "firestore.googleapis.com/Database" + } + }, + "backup": { + "type": "string", + "id": 5, + "options": { + "(google.api.resource_reference).type": "firestore.googleapis.com/Backup" + } + }, + "progressPercentage": { + "type": "Progress", + "id": 8 + } + } + }, + "CloneDatabaseMetadata": { + "fields": { + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "endTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "operationState": { + "type": "OperationState", + "id": 3 + }, + "database": { + "type": "string", + "id": 4, + "options": { + "(google.api.resource_reference).type": "firestore.googleapis.com/Database" + } + }, + "pitrSnapshot": { + "type": "PitrSnapshot", + "id": 7 + }, + "progressPercentage": { + "type": "Progress", + "id": 6 + } + } + }, + "Progress": { + "fields": { + "estimatedWork": { + "type": "int64", + "id": 1 + }, + "completedWork": { + "type": "int64", + "id": 2 + } + } + }, + "OperationState": { + "values": { + "OPERATION_STATE_UNSPECIFIED": 0, + "INITIALIZING": 1, + "PROCESSING": 2, + "CANCELLING": 3, + "FINALIZING": 4, + "SUCCESSFUL": 5, + "FAILED": 6, + "CANCELLED": 7 + } + }, + "PitrSnapshot": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/Database" + } + }, + "databaseUid": { + "type": "bytes", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "snapshotTime": { + "type": "google.protobuf.Timestamp", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "BackupSchedule": { + "options": { + "(google.api.resource).type": "firestore.googleapis.com/BackupSchedule", + "(google.api.resource).pattern": "projects/{project}/databases/{database}/backupSchedules/{backup_schedule}" + }, + "oneofs": { + "recurrence": { + "oneof": [ + "dailyRecurrence", + "weeklyRecurrence" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "createTime": { + "type": "google.protobuf.Timestamp", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "updateTime": { + "type": "google.protobuf.Timestamp", + "id": 10, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "retention": { + "type": "google.protobuf.Duration", + "id": 6 + }, + "dailyRecurrence": { + "type": "DailyRecurrence", + "id": 7 + }, + "weeklyRecurrence": { + "type": "WeeklyRecurrence", + "id": 8 + } + } + }, + "DailyRecurrence": { + "fields": {} + }, + "WeeklyRecurrence": { + "fields": { + "day": { + "type": "google.type.DayOfWeek", + "id": 2 + } + } + }, + "UserCreds": { + "options": { + "(google.api.resource).type": "firestore.googleapis.com/UserCreds", + "(google.api.resource).pattern": "projects/{project}/databases/{database}/userCreds/{user_creds}", + "(google.api.resource).plural": "userCreds", + "(google.api.resource).singular": "userCreds" + }, + "oneofs": { + "UserCredsIdentity": { + "oneof": [ + "resourceIdentity" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "IDENTIFIER" + } + }, + "createTime": { + "type": "google.protobuf.Timestamp", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "updateTime": { + "type": "google.protobuf.Timestamp", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "state": { + "type": "State", + "id": 4, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "securePassword": { + "type": "string", + "id": 5, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "resourceIdentity": { + "type": "ResourceIdentity", + "id": 6 + } + }, + "nested": { + "State": { + "values": { + "STATE_UNSPECIFIED": 0, + "ENABLED": 1, + "DISABLED": 2 + } + }, + "ResourceIdentity": { + "fields": { + "principal": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + } + } + } + }, + "LocationMetadata": { + "fields": {} + } + } + } + } + } + } + }, + "api": { + "options": { + "go_package": "google.golang.org/genproto/googleapis/api/annotations;annotations", + "java_multiple_files": true, + "java_outer_classname": "RoutingProto", + "java_package": "com.google.api", + "objc_class_prefix": "GAPI" + }, + "nested": { + "fieldBehavior": { + "rule": "repeated", + "type": "google.api.FieldBehavior", + "id": 1052, + "extend": "google.protobuf.FieldOptions", + "options": { + "packed": false + } + }, + "FieldBehavior": { + "values": { + "FIELD_BEHAVIOR_UNSPECIFIED": 0, + "OPTIONAL": 1, + "REQUIRED": 2, + "OUTPUT_ONLY": 3, + "INPUT_ONLY": 4, + "IMMUTABLE": 5, + "UNORDERED_LIST": 6, + "NON_EMPTY_DEFAULT": 7, + "IDENTIFIER": 8 + } + }, + "resourceReference": { + "type": "google.api.ResourceReference", + "id": 1055, + "extend": "google.protobuf.FieldOptions" + }, + "resourceDefinition": { + "rule": "repeated", + "type": "google.api.ResourceDescriptor", + "id": 1053, + "extend": "google.protobuf.FileOptions" + }, + "resource": { + "type": "google.api.ResourceDescriptor", + "id": 1053, + "extend": "google.protobuf.MessageOptions" + }, + "ResourceDescriptor": { + "fields": { + "type": { + "type": "string", + "id": 1 + }, + "pattern": { + "rule": "repeated", + "type": "string", + "id": 2 + }, + "nameField": { + "type": "string", + "id": 3 + }, + "history": { + "type": "History", + "id": 4 + }, + "plural": { + "type": "string", + "id": 5 + }, + "singular": { + "type": "string", + "id": 6 + }, + "style": { + "rule": "repeated", + "type": "Style", + "id": 10 + } + }, + "nested": { + "History": { + "values": { + "HISTORY_UNSPECIFIED": 0, + "ORIGINALLY_SINGLE_PATTERN": 1, + "FUTURE_MULTI_PATTERN": 2 + } + }, + "Style": { + "values": { + "STYLE_UNSPECIFIED": 0, + "DECLARATIVE_FRIENDLY": 1 + } + } + } + }, + "ResourceReference": { + "fields": { + "type": { + "type": "string", + "id": 1 + }, + "childType": { + "type": "string", + "id": 2 + } + } + }, + "http": { + "type": "HttpRule", + "id": 72295728, + "extend": "google.protobuf.MethodOptions" + }, + "Http": { + "fields": { + "rules": { + "rule": "repeated", + "type": "HttpRule", + "id": 1 + }, + "fullyDecodeReservedExpansion": { + "type": "bool", + "id": 2 + } + } + }, + "HttpRule": { + "oneofs": { + "pattern": { + "oneof": [ + "get", + "put", + "post", + "delete", + "patch", + "custom" + ] + } + }, + "fields": { + "selector": { + "type": "string", + "id": 1 + }, + "get": { + "type": "string", + "id": 2 + }, + "put": { + "type": "string", + "id": 3 + }, + "post": { + "type": "string", + "id": 4 + }, + "delete": { + "type": "string", + "id": 5 + }, + "patch": { + "type": "string", + "id": 6 + }, + "custom": { + "type": "CustomHttpPattern", + "id": 8 + }, + "body": { + "type": "string", + "id": 7 + }, + "responseBody": { + "type": "string", + "id": 12 + }, + "additionalBindings": { + "rule": "repeated", + "type": "HttpRule", + "id": 11 + } + } + }, + "CustomHttpPattern": { + "fields": { + "kind": { + "type": "string", + "id": 1 + }, + "path": { + "type": "string", + "id": 2 + } + } + }, + "methodSignature": { + "rule": "repeated", + "type": "string", + "id": 1051, + "extend": "google.protobuf.MethodOptions" + }, + "defaultHost": { + "type": "string", + "id": 1049, + "extend": "google.protobuf.ServiceOptions" + }, + "oauthScopes": { + "type": "string", + "id": 1050, + "extend": "google.protobuf.ServiceOptions" + }, + "apiVersion": { + "type": "string", + "id": 525000001, + "extend": "google.protobuf.ServiceOptions" + }, + "CommonLanguageSettings": { + "fields": { + "referenceDocsUri": { + "type": "string", + "id": 1, + "options": { + "deprecated": true + } + }, + "destinations": { + "rule": "repeated", + "type": "ClientLibraryDestination", + "id": 2 + }, + "selectiveGapicGeneration": { + "type": "SelectiveGapicGeneration", + "id": 3 + } + } + }, + "ClientLibrarySettings": { + "fields": { + "version": { + "type": "string", + "id": 1 + }, + "launchStage": { + "type": "LaunchStage", + "id": 2 + }, + "restNumericEnums": { + "type": "bool", + "id": 3 + }, + "javaSettings": { + "type": "JavaSettings", + "id": 21 + }, + "cppSettings": { + "type": "CppSettings", + "id": 22 + }, + "phpSettings": { + "type": "PhpSettings", + "id": 23 + }, + "pythonSettings": { + "type": "PythonSettings", + "id": 24 + }, + "nodeSettings": { + "type": "NodeSettings", + "id": 25 + }, + "dotnetSettings": { + "type": "DotnetSettings", + "id": 26 + }, + "rubySettings": { + "type": "RubySettings", + "id": 27 + }, + "goSettings": { + "type": "GoSettings", + "id": 28 + } + } + }, + "Publishing": { + "fields": { + "methodSettings": { + "rule": "repeated", + "type": "MethodSettings", + "id": 2 + }, + "newIssueUri": { + "type": "string", + "id": 101 + }, + "documentationUri": { + "type": "string", + "id": 102 + }, + "apiShortName": { + "type": "string", + "id": 103 + }, + "githubLabel": { + "type": "string", + "id": 104 + }, + "codeownerGithubTeams": { + "rule": "repeated", + "type": "string", + "id": 105 + }, + "docTagPrefix": { + "type": "string", + "id": 106 + }, + "organization": { + "type": "ClientLibraryOrganization", + "id": 107 + }, + "librarySettings": { + "rule": "repeated", + "type": "ClientLibrarySettings", + "id": 109 + }, + "protoReferenceDocumentationUri": { + "type": "string", + "id": 110 + }, + "restReferenceDocumentationUri": { + "type": "string", + "id": 111 + } + } + }, + "JavaSettings": { + "fields": { + "libraryPackage": { + "type": "string", + "id": 1 + }, + "serviceClassNames": { + "keyType": "string", + "type": "string", + "id": 2 + }, + "common": { + "type": "CommonLanguageSettings", + "id": 3 + } + } + }, + "CppSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "PhpSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "PythonSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + }, + "experimentalFeatures": { + "type": "ExperimentalFeatures", + "id": 2 + } + }, + "nested": { + "ExperimentalFeatures": { + "fields": { + "restAsyncIoEnabled": { + "type": "bool", + "id": 1 + }, + "protobufPythonicTypesEnabled": { + "type": "bool", + "id": 2 + }, + "unversionedPackageDisabled": { + "type": "bool", + "id": 3 + } + } + } + } + }, + "NodeSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "DotnetSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + }, + "renamedServices": { + "keyType": "string", + "type": "string", + "id": 2 + }, + "renamedResources": { + "keyType": "string", + "type": "string", + "id": 3 + }, + "ignoredResources": { + "rule": "repeated", + "type": "string", + "id": 4 + }, + "forcedNamespaceAliases": { + "rule": "repeated", + "type": "string", + "id": 5 + }, + "handwrittenSignatures": { + "rule": "repeated", + "type": "string", + "id": 6 + } + } + }, + "RubySettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "GoSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + }, + "renamedServices": { + "keyType": "string", + "type": "string", + "id": 2 + } + } + }, + "MethodSettings": { + "fields": { + "selector": { + "type": "string", + "id": 1 + }, + "longRunning": { + "type": "LongRunning", + "id": 2 + }, + "autoPopulatedFields": { + "rule": "repeated", + "type": "string", + "id": 3 + } + }, + "nested": { + "LongRunning": { + "fields": { + "initialPollDelay": { + "type": "google.protobuf.Duration", + "id": 1 + }, + "pollDelayMultiplier": { + "type": "float", + "id": 2 + }, + "maxPollDelay": { + "type": "google.protobuf.Duration", + "id": 3 + }, + "totalPollTimeout": { + "type": "google.protobuf.Duration", + "id": 4 + } + } + } + } + }, + "ClientLibraryOrganization": { + "values": { + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED": 0, + "CLOUD": 1, + "ADS": 2, + "PHOTOS": 3, + "STREET_VIEW": 4, + "SHOPPING": 5, + "GEO": 6, + "GENERATIVE_AI": 7 + } + }, + "ClientLibraryDestination": { + "values": { + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED": 0, + "GITHUB": 10, + "PACKAGE_MANAGER": 20 + } + }, + "SelectiveGapicGeneration": { + "fields": { + "methods": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "generateOmittedAsInternal": { + "type": "bool", + "id": 2 + } + } + }, + "LaunchStage": { + "values": { + "LAUNCH_STAGE_UNSPECIFIED": 0, + "UNIMPLEMENTED": 6, + "PRELAUNCH": 7, + "EARLY_ACCESS": 1, + "ALPHA": 2, + "BETA": 3, + "GA": 4, + "DEPRECATED": 5 + } + }, + "routing": { + "type": "google.api.RoutingRule", + "id": 72295729, + "extend": "google.protobuf.MethodOptions" + }, + "RoutingRule": { + "fields": { + "routingParameters": { + "rule": "repeated", + "type": "RoutingParameter", + "id": 2 + } + } + }, + "RoutingParameter": { + "fields": { + "field": { + "type": "string", + "id": 1 + }, + "pathTemplate": { + "type": "string", + "id": 2 + } + } + } + } + }, + "protobuf": { + "options": { + "go_package": "google.golang.org/protobuf/types/descriptorpb", + "java_package": "com.google.protobuf", + "java_outer_classname": "DescriptorProtos", + "csharp_namespace": "Google.Protobuf.Reflection", + "objc_class_prefix": "GPB", + "cc_enable_arenas": true, + "optimize_for": "SPEED" + }, + "nested": { + "FileDescriptorSet": { + "edition": "proto2", + "fields": { + "file": { + "rule": "repeated", + "type": "FileDescriptorProto", + "id": 1 + } + } + }, + "Edition": { + "edition": "proto2", + "values": { + "EDITION_UNKNOWN": 0, + "EDITION_PROTO2": 998, + "EDITION_PROTO3": 999, + "EDITION_2023": 1000, + "EDITION_2024": 1001, + "EDITION_1_TEST_ONLY": 1, + "EDITION_2_TEST_ONLY": 2, + "EDITION_99997_TEST_ONLY": 99997, + "EDITION_99998_TEST_ONLY": 99998, + "EDITION_99999_TEST_ONLY": 99999, + "EDITION_MAX": 2147483647 + } + }, + "FileDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "package": { + "type": "string", + "id": 2 + }, + "dependency": { + "rule": "repeated", + "type": "string", + "id": 3 + }, + "publicDependency": { + "rule": "repeated", + "type": "int32", + "id": 10 + }, + "weakDependency": { + "rule": "repeated", + "type": "int32", + "id": 11 + }, + "messageType": { + "rule": "repeated", + "type": "DescriptorProto", + "id": 4 + }, + "enumType": { + "rule": "repeated", + "type": "EnumDescriptorProto", + "id": 5 + }, + "service": { + "rule": "repeated", + "type": "ServiceDescriptorProto", + "id": 6 + }, + "extension": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 7 + }, + "options": { + "type": "FileOptions", + "id": 8 + }, + "sourceCodeInfo": { + "type": "SourceCodeInfo", + "id": 9 + }, + "syntax": { + "type": "string", + "id": 12 + }, + "edition": { + "type": "Edition", + "id": 14 + } + } + }, + "DescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "field": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 2 + }, + "extension": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 6 + }, + "nestedType": { + "rule": "repeated", + "type": "DescriptorProto", + "id": 3 + }, + "enumType": { + "rule": "repeated", + "type": "EnumDescriptorProto", + "id": 4 + }, + "extensionRange": { + "rule": "repeated", + "type": "ExtensionRange", + "id": 5 + }, + "oneofDecl": { + "rule": "repeated", + "type": "OneofDescriptorProto", + "id": 8 + }, + "options": { + "type": "MessageOptions", + "id": 7 + }, + "reservedRange": { + "rule": "repeated", + "type": "ReservedRange", + "id": 9 + }, + "reservedName": { + "rule": "repeated", + "type": "string", + "id": 10 + } + }, + "nested": { + "ExtensionRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + }, + "options": { + "type": "ExtensionRangeOptions", + "id": 3 + } + } + }, + "ReservedRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + } + } + } + } + }, + "ExtensionRangeOptions": { + "edition": "proto2", + "fields": { + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + }, + "declaration": { + "rule": "repeated", + "type": "Declaration", + "id": 2, + "options": { + "retention": "RETENTION_SOURCE" + } + }, + "features": { + "type": "FeatureSet", + "id": 50 + }, + "verification": { + "type": "VerificationState", + "id": 3, + "options": { + "default": "UNVERIFIED", + "retention": "RETENTION_SOURCE" + } + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "nested": { + "Declaration": { + "fields": { + "number": { + "type": "int32", + "id": 1 + }, + "fullName": { + "type": "string", + "id": 2 + }, + "type": { + "type": "string", + "id": 3 + }, + "reserved": { + "type": "bool", + "id": 5 + }, + "repeated": { + "type": "bool", + "id": 6 + } + }, + "reserved": [ + [ + 4, + 4 + ] + ] + }, + "VerificationState": { + "values": { + "DECLARATION": 0, + "UNVERIFIED": 1 + } + } + } + }, + "FieldDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "number": { + "type": "int32", + "id": 3 + }, + "label": { + "type": "Label", + "id": 4 + }, + "type": { + "type": "Type", + "id": 5 + }, + "typeName": { + "type": "string", + "id": 6 + }, + "extendee": { + "type": "string", + "id": 2 + }, + "defaultValue": { + "type": "string", + "id": 7 + }, + "oneofIndex": { + "type": "int32", + "id": 9 + }, + "jsonName": { + "type": "string", + "id": 10 + }, + "options": { + "type": "FieldOptions", + "id": 8 + }, + "proto3Optional": { + "type": "bool", + "id": 17 + } + }, + "nested": { + "Type": { + "values": { + "TYPE_DOUBLE": 1, + "TYPE_FLOAT": 2, + "TYPE_INT64": 3, + "TYPE_UINT64": 4, + "TYPE_INT32": 5, + "TYPE_FIXED64": 6, + "TYPE_FIXED32": 7, + "TYPE_BOOL": 8, + "TYPE_STRING": 9, + "TYPE_GROUP": 10, + "TYPE_MESSAGE": 11, + "TYPE_BYTES": 12, + "TYPE_UINT32": 13, + "TYPE_ENUM": 14, + "TYPE_SFIXED32": 15, + "TYPE_SFIXED64": 16, + "TYPE_SINT32": 17, + "TYPE_SINT64": 18 + } + }, + "Label": { + "values": { + "LABEL_OPTIONAL": 1, + "LABEL_REPEATED": 3, + "LABEL_REQUIRED": 2 + } + } + } + }, + "OneofDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "options": { + "type": "OneofOptions", + "id": 2 + } + } + }, + "EnumDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "value": { + "rule": "repeated", + "type": "EnumValueDescriptorProto", + "id": 2 + }, + "options": { + "type": "EnumOptions", + "id": 3 + }, + "reservedRange": { + "rule": "repeated", + "type": "EnumReservedRange", + "id": 4 + }, + "reservedName": { + "rule": "repeated", + "type": "string", + "id": 5 + } + }, + "nested": { + "EnumReservedRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + } + } + } + } + }, + "EnumValueDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "number": { + "type": "int32", + "id": 2 + }, + "options": { + "type": "EnumValueOptions", + "id": 3 + } + } + }, + "ServiceDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "method": { + "rule": "repeated", + "type": "MethodDescriptorProto", + "id": 2 + }, + "options": { + "type": "ServiceOptions", + "id": 3 + } + } + }, + "MethodDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "inputType": { + "type": "string", + "id": 2 + }, + "outputType": { + "type": "string", + "id": 3 + }, + "options": { + "type": "MethodOptions", + "id": 4 + }, + "clientStreaming": { + "type": "bool", + "id": 5, + "options": { + "default": false + } + }, + "serverStreaming": { + "type": "bool", + "id": 6, + "options": { + "default": false + } + } + } + }, + "FileOptions": { + "edition": "proto2", + "fields": { + "javaPackage": { + "type": "string", + "id": 1 + }, + "javaOuterClassname": { + "type": "string", + "id": 8 + }, + "javaMultipleFiles": { + "type": "bool", + "id": 10, + "options": { + "default": false + } + }, + "javaGenerateEqualsAndHash": { + "type": "bool", + "id": 20, + "options": { + "deprecated": true + } + }, + "javaStringCheckUtf8": { + "type": "bool", + "id": 27, + "options": { + "default": false + } + }, + "optimizeFor": { + "type": "OptimizeMode", + "id": 9, + "options": { + "default": "SPEED" + } + }, + "goPackage": { + "type": "string", + "id": 11 + }, + "ccGenericServices": { + "type": "bool", + "id": 16, + "options": { + "default": false + } + }, + "javaGenericServices": { + "type": "bool", + "id": 17, + "options": { + "default": false + } + }, + "pyGenericServices": { + "type": "bool", + "id": 18, + "options": { + "default": false + } + }, + "deprecated": { + "type": "bool", + "id": 23, + "options": { + "default": false + } + }, + "ccEnableArenas": { + "type": "bool", + "id": 31, + "options": { + "default": true + } + }, + "objcClassPrefix": { + "type": "string", + "id": 36 + }, + "csharpNamespace": { + "type": "string", + "id": 37 + }, + "swiftPrefix": { + "type": "string", + "id": 39 + }, + "phpClassPrefix": { + "type": "string", + "id": 40 + }, + "phpNamespace": { + "type": "string", + "id": 41 + }, + "phpMetadataNamespace": { + "type": "string", + "id": 44 + }, + "rubyPackage": { + "type": "string", + "id": 45 + }, + "features": { + "type": "FeatureSet", + "id": 50 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 42, + 42 + ], + [ + 38, + 38 + ] + ], + "nested": { + "OptimizeMode": { + "values": { + "SPEED": 1, + "CODE_SIZE": 2, + "LITE_RUNTIME": 3 + } + } + } + }, + "MessageOptions": { + "edition": "proto2", + "fields": { + "messageSetWireFormat": { + "type": "bool", + "id": 1, + "options": { + "default": false + } + }, + "noStandardDescriptorAccessor": { + "type": "bool", + "id": 2, + "options": { + "default": false + } + }, + "deprecated": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "mapEntry": { + "type": "bool", + "id": 7 + }, + "deprecatedLegacyJsonFieldConflicts": { + "type": "bool", + "id": 11, + "options": { + "deprecated": true + } + }, + "features": { + "type": "FeatureSet", + "id": 12 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 4, + 4 + ], + [ + 5, + 5 + ], + [ + 6, + 6 + ], + [ + 8, + 8 + ], + [ + 9, + 9 + ] + ] + }, + "FieldOptions": { + "edition": "proto2", + "fields": { + "ctype": { + "type": "CType", + "id": 1, + "options": { + "default": "STRING" + } + }, + "packed": { + "type": "bool", + "id": 2 + }, + "jstype": { + "type": "JSType", + "id": 6, + "options": { + "default": "JS_NORMAL" + } + }, + "lazy": { + "type": "bool", + "id": 5, + "options": { + "default": false + } + }, + "unverifiedLazy": { + "type": "bool", + "id": 15, + "options": { + "default": false + } + }, + "deprecated": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "weak": { + "type": "bool", + "id": 10, + "options": { + "default": false + } + }, + "debugRedact": { + "type": "bool", + "id": 16, + "options": { + "default": false + } + }, + "retention": { + "type": "OptionRetention", + "id": 17 + }, + "targets": { + "rule": "repeated", + "type": "OptionTargetType", + "id": 19 + }, + "editionDefaults": { + "rule": "repeated", + "type": "EditionDefault", + "id": 20 + }, + "features": { + "type": "FeatureSet", + "id": 21 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 4, + 4 + ], + [ + 18, + 18 + ] + ], + "nested": { + "CType": { + "values": { + "STRING": 0, + "CORD": 1, + "STRING_PIECE": 2 + } + }, + "JSType": { + "values": { + "JS_NORMAL": 0, + "JS_STRING": 1, + "JS_NUMBER": 2 + } + }, + "OptionRetention": { + "values": { + "RETENTION_UNKNOWN": 0, + "RETENTION_RUNTIME": 1, + "RETENTION_SOURCE": 2 + } + }, + "OptionTargetType": { + "values": { + "TARGET_TYPE_UNKNOWN": 0, + "TARGET_TYPE_FILE": 1, + "TARGET_TYPE_EXTENSION_RANGE": 2, + "TARGET_TYPE_MESSAGE": 3, + "TARGET_TYPE_FIELD": 4, + "TARGET_TYPE_ONEOF": 5, + "TARGET_TYPE_ENUM": 6, + "TARGET_TYPE_ENUM_ENTRY": 7, + "TARGET_TYPE_SERVICE": 8, + "TARGET_TYPE_METHOD": 9 + } + }, + "EditionDefault": { + "fields": { + "edition": { + "type": "Edition", + "id": 3 + }, + "value": { + "type": "string", + "id": 2 + } + } + } + } + }, + "OneofOptions": { + "edition": "proto2", + "fields": { + "features": { + "type": "FeatureSet", + "id": 1 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "EnumOptions": { + "edition": "proto2", + "fields": { + "allowAlias": { + "type": "bool", + "id": 2 + }, + "deprecated": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "deprecatedLegacyJsonFieldConflicts": { + "type": "bool", + "id": 6, + "options": { + "deprecated": true + } + }, + "features": { + "type": "FeatureSet", + "id": 7 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 5, + 5 + ] + ] + }, + "EnumValueOptions": { + "edition": "proto2", + "fields": { + "deprecated": { + "type": "bool", + "id": 1, + "options": { + "default": false + } + }, + "features": { + "type": "FeatureSet", + "id": 2 + }, + "debugRedact": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "ServiceOptions": { + "edition": "proto2", + "fields": { + "features": { + "type": "FeatureSet", + "id": 34 + }, + "deprecated": { + "type": "bool", + "id": 33, + "options": { + "default": false + } + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "MethodOptions": { + "edition": "proto2", + "fields": { + "deprecated": { + "type": "bool", + "id": 33, + "options": { + "default": false + } + }, + "idempotencyLevel": { + "type": "IdempotencyLevel", + "id": 34, + "options": { + "default": "IDEMPOTENCY_UNKNOWN" + } + }, + "features": { + "type": "FeatureSet", + "id": 35 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "nested": { + "IdempotencyLevel": { + "values": { + "IDEMPOTENCY_UNKNOWN": 0, + "NO_SIDE_EFFECTS": 1, + "IDEMPOTENT": 2 + } + } + } + }, + "UninterpretedOption": { + "edition": "proto2", + "fields": { + "name": { + "rule": "repeated", + "type": "NamePart", + "id": 2 + }, + "identifierValue": { + "type": "string", + "id": 3 + }, + "positiveIntValue": { + "type": "uint64", + "id": 4 + }, + "negativeIntValue": { + "type": "int64", + "id": 5 + }, + "doubleValue": { + "type": "double", + "id": 6 + }, + "stringValue": { + "type": "bytes", + "id": 7 + }, + "aggregateValue": { + "type": "string", + "id": 8 + } + }, + "nested": { + "NamePart": { + "fields": { + "namePart": { + "rule": "required", + "type": "string", + "id": 1 + }, + "isExtension": { + "rule": "required", + "type": "bool", + "id": 2 + } + } + } + } + }, + "FeatureSet": { + "edition": "proto2", + "fields": { + "fieldPresence": { + "type": "FieldPresence", + "id": 1, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_2023", + "edition_defaults.value": "EXPLICIT" + } + }, + "enumType": { + "type": "EnumType", + "id": 2, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "OPEN" + } + }, + "repeatedFieldEncoding": { + "type": "RepeatedFieldEncoding", + "id": 3, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "PACKED" + } + }, + "utf8Validation": { + "type": "Utf8Validation", + "id": 4, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "VERIFY" + } + }, + "messageEncoding": { + "type": "MessageEncoding", + "id": 5, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO2", + "edition_defaults.value": "LENGTH_PREFIXED" + } + }, + "jsonFormat": { + "type": "JsonFormat", + "id": 6, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "ALLOW" + } + } + }, + "extensions": [ + [ + 1000, + 1000 + ], + [ + 1001, + 1001 + ], + [ + 1002, + 1002 + ], + [ + 9995, + 9999 + ], + [ + 10000, + 10000 + ] + ], + "reserved": [ + [ + 999, + 999 + ] + ], + "nested": { + "FieldPresence": { + "values": { + "FIELD_PRESENCE_UNKNOWN": 0, + "EXPLICIT": 1, + "IMPLICIT": 2, + "LEGACY_REQUIRED": 3 + } + }, + "EnumType": { + "values": { + "ENUM_TYPE_UNKNOWN": 0, + "OPEN": 1, + "CLOSED": 2 + } + }, + "RepeatedFieldEncoding": { + "values": { + "REPEATED_FIELD_ENCODING_UNKNOWN": 0, + "PACKED": 1, + "EXPANDED": 2 + } + }, + "Utf8Validation": { + "values": { + "UTF8_VALIDATION_UNKNOWN": 0, + "VERIFY": 2, + "NONE": 3 + } + }, + "MessageEncoding": { + "values": { + "MESSAGE_ENCODING_UNKNOWN": 0, + "LENGTH_PREFIXED": 1, + "DELIMITED": 2 + } + }, + "JsonFormat": { + "values": { + "JSON_FORMAT_UNKNOWN": 0, + "ALLOW": 1, + "LEGACY_BEST_EFFORT": 2 + } + } + } + }, + "FeatureSetDefaults": { + "edition": "proto2", + "fields": { + "defaults": { + "rule": "repeated", + "type": "FeatureSetEditionDefault", + "id": 1 + }, + "minimumEdition": { + "type": "Edition", + "id": 4 + }, + "maximumEdition": { + "type": "Edition", + "id": 5 + } + }, + "nested": { + "FeatureSetEditionDefault": { + "fields": { + "edition": { + "type": "Edition", + "id": 3 + }, + "features": { + "type": "FeatureSet", + "id": 2 + } + } + } + } + }, + "SourceCodeInfo": { + "edition": "proto2", + "fields": { + "location": { + "rule": "repeated", + "type": "Location", + "id": 1 + } + }, + "nested": { + "Location": { + "fields": { + "path": { + "rule": "repeated", + "type": "int32", + "id": 1, + "options": { + "packed": true + } + }, + "span": { + "rule": "repeated", + "type": "int32", + "id": 2, + "options": { + "packed": true + } + }, + "leadingComments": { + "type": "string", + "id": 3 + }, + "trailingComments": { + "type": "string", + "id": 4 + }, + "leadingDetachedComments": { + "rule": "repeated", + "type": "string", + "id": 6 + } + } + } + } + }, + "GeneratedCodeInfo": { + "edition": "proto2", + "fields": { + "annotation": { + "rule": "repeated", + "type": "Annotation", + "id": 1 + } + }, + "nested": { + "Annotation": { + "fields": { + "path": { + "rule": "repeated", + "type": "int32", + "id": 1, + "options": { + "packed": true + } + }, + "sourceFile": { + "type": "string", + "id": 2 + }, + "begin": { + "type": "int32", + "id": 3 + }, + "end": { + "type": "int32", + "id": 4 + }, + "semantic": { + "type": "Semantic", + "id": 5 + } + }, + "nested": { + "Semantic": { + "values": { + "NONE": 0, + "SET": 1, + "ALIAS": 2 + } + } + } + } + } + }, + "Timestamp": { + "fields": { + "seconds": { + "type": "int64", + "id": 1 + }, + "nanos": { + "type": "int32", + "id": 2 + } + } + }, + "Duration": { + "fields": { + "seconds": { + "type": "int64", + "id": 1 + }, + "nanos": { + "type": "int32", + "id": 2 + } + } + }, + "Any": { + "fields": { + "type_url": { + "type": "string", + "id": 1 + }, + "value": { + "type": "bytes", + "id": 2 + } + } + }, + "Empty": { + "fields": {} + }, + "FieldMask": { + "fields": { + "paths": { + "rule": "repeated", + "type": "string", + "id": 1 + } + } + }, + "Struct": { + "fields": { + "fields": { + "keyType": "string", + "type": "Value", + "id": 1 + } + } + }, + "Value": { + "oneofs": { + "kind": { + "oneof": [ + "nullValue", + "numberValue", + "stringValue", + "boolValue", + "structValue", + "listValue" + ] + } + }, + "fields": { + "nullValue": { + "type": "NullValue", + "id": 1 + }, + "numberValue": { + "type": "double", + "id": 2 + }, + "stringValue": { + "type": "string", + "id": 3 + }, + "boolValue": { + "type": "bool", + "id": 4 + }, + "structValue": { + "type": "Struct", + "id": 5 + }, + "listValue": { + "type": "ListValue", + "id": 6 + } + } + }, + "NullValue": { + "values": { + "NULL_VALUE": 0 + } + }, + "ListValue": { + "fields": { + "values": { + "rule": "repeated", + "type": "Value", + "id": 1 + } + } + }, + "DoubleValue": { + "fields": { + "value": { + "type": "double", + "id": 1 + } + } + }, + "FloatValue": { + "fields": { + "value": { + "type": "float", + "id": 1 + } + } + }, + "Int64Value": { + "fields": { + "value": { + "type": "int64", + "id": 1 + } + } + }, + "UInt64Value": { + "fields": { + "value": { + "type": "uint64", + "id": 1 + } + } + }, + "Int32Value": { + "fields": { + "value": { + "type": "int32", + "id": 1 + } + } + }, + "UInt32Value": { + "fields": { + "value": { + "type": "uint32", + "id": 1 + } + } + }, + "BoolValue": { + "fields": { + "value": { + "type": "bool", + "id": 1 + } + } + }, + "StringValue": { + "fields": { + "value": { + "type": "string", + "id": 1 + } + } + }, + "BytesValue": { + "fields": { + "value": { + "type": "bytes", + "id": 1 + } + } + } + } + }, + "type": { + "options": { + "go_package": "google.golang.org/genproto/googleapis/type/latlng;latlng", + "java_multiple_files": true, + "java_outer_classname": "LatLngProto", + "java_package": "com.google.type", + "objc_class_prefix": "GTP", + "cc_enable_arenas": true + }, + "nested": { + "DayOfWeek": { + "values": { + "DAY_OF_WEEK_UNSPECIFIED": 0, + "MONDAY": 1, + "TUESDAY": 2, + "WEDNESDAY": 3, + "THURSDAY": 4, + "FRIDAY": 5, + "SATURDAY": 6, + "SUNDAY": 7 + } + }, + "LatLng": { + "fields": { + "latitude": { + "type": "double", + "id": 1 + }, + "longitude": { + "type": "double", + "id": 2 + } + } + } + } + }, + "longrunning": { + "options": { + "csharp_namespace": "Google.LongRunning", + "go_package": "cloud.google.com/go/longrunning/autogen/longrunningpb;longrunningpb", + "java_multiple_files": true, + "java_outer_classname": "OperationsProto", + "java_package": "com.google.longrunning", + "objc_class_prefix": "GLRUN", + "php_namespace": "Google\\LongRunning" + }, + "nested": { + "operationInfo": { + "type": "google.longrunning.OperationInfo", + "id": 1049, + "extend": "google.protobuf.MethodOptions" + }, + "Operations": { + "options": { + "(google.api.default_host)": "longrunning.googleapis.com" + }, + "methods": { + "ListOperations": { + "requestType": "ListOperationsRequest", + "responseType": "ListOperationsResponse", + "options": { + "(google.api.http).get": "/v1/{name=operations}", + "(google.api.method_signature)": "name,filter" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=operations}" + } + }, + { + "(google.api.method_signature)": "name,filter" + } + ] + }, + "GetOperation": { + "requestType": "GetOperationRequest", + "responseType": "Operation", + "options": { + "(google.api.http).get": "/v1/{name=operations/**}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=operations/**}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "DeleteOperation": { + "requestType": "DeleteOperationRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=operations/**}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=operations/**}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "CancelOperation": { + "requestType": "CancelOperationRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).post": "/v1/{name=operations/**}:cancel", + "(google.api.http).body": "*", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{name=operations/**}:cancel", + "body": "*" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "WaitOperation": { + "requestType": "WaitOperationRequest", + "responseType": "Operation" + } + } + }, + "Operation": { + "oneofs": { + "result": { + "oneof": [ + "error", + "response" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "metadata": { + "type": "google.protobuf.Any", + "id": 2 + }, + "done": { + "type": "bool", + "id": 3 + }, + "error": { + "type": "google.rpc.Status", + "id": 4 + }, + "response": { + "type": "google.protobuf.Any", + "id": 5 + } + } + }, + "GetOperationRequest": { + "fields": { + "name": { + "type": "string", + "id": 1 + } + } + }, + "ListOperationsRequest": { + "fields": { + "name": { + "type": "string", + "id": 4 + }, + "filter": { + "type": "string", + "id": 1 + }, + "pageSize": { + "type": "int32", + "id": 2 + }, + "pageToken": { + "type": "string", + "id": 3 + }, + "returnPartialSuccess": { + "type": "bool", + "id": 5 + } + } + }, + "ListOperationsResponse": { + "fields": { + "operations": { + "rule": "repeated", + "type": "Operation", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + }, + "unreachable": { + "rule": "repeated", + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "UNORDERED_LIST" + } + } + } + }, + "CancelOperationRequest": { + "fields": { + "name": { + "type": "string", + "id": 1 + } + } + }, + "DeleteOperationRequest": { + "fields": { + "name": { + "type": "string", + "id": 1 + } + } + }, + "WaitOperationRequest": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "timeout": { + "type": "google.protobuf.Duration", + "id": 2 + } + } + }, + "OperationInfo": { + "fields": { + "responseType": { + "type": "string", + "id": 1 + }, + "metadataType": { + "type": "string", + "id": 2 + } + } + } + } + }, + "rpc": { + "options": { + "cc_enable_arenas": true, + "go_package": "google.golang.org/genproto/googleapis/rpc/status;status", + "java_multiple_files": true, + "java_outer_classname": "StatusProto", + "java_package": "com.google.rpc", + "objc_class_prefix": "RPC" + }, + "nested": { + "Status": { + "fields": { + "code": { + "type": "int32", + "id": 1 + }, + "message": { + "type": "string", + "id": 2 + }, + "details": { + "rule": "repeated", + "type": "google.protobuf.Any", + "id": 3 + } + } + } + } + } + } + } + } +} diff --git a/handwritten/firestore/dev/protos/firestore/bundle.proto b/handwritten/firestore/dev/protos/firestore/bundle.proto new file mode 100644 index 00000000000..22bbd8a0915 --- /dev/null +++ b/handwritten/firestore/dev/protos/firestore/bundle.proto @@ -0,0 +1,120 @@ +// Copyright 2020 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// This file defines the format of Firestore bundle file/stream. It is not a part of the +// Firestore API, only a specification used by Server and Client SDK to write and read +// bundles. + +syntax = "proto3"; + +package firestore; + +import "google/firestore/v1/document.proto"; +import "google/firestore/v1/query.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Firestore.Proto"; +option go_package = "google.golang.org/genproto/firestore/proto;firestore"; +option java_multiple_files = true; +option java_outer_classname = "BundleProto"; +option java_package = "com.google.firestore.proto"; +option objc_class_prefix = "FSTPB"; +option php_namespace = "Firestore\\Proto"; + +// Encodes a query saved in the bundle. +message BundledQuery { + // The parent resource name. + string parent = 1; + + // The query to run. + oneof query_type { + // A structured query. + google.firestore.v1.StructuredQuery structured_query = 2; + } + + // If the query is a limit query, should the limit be applied to the beginning or + // the end of results. + enum LimitType { + FIRST = 0; + LAST = 1; + } + LimitType limit_type = 3; +} + +// A Query associated with a name, created as part of the bundle file, and can be read +// by client SDKs once the bundle containing them is loaded. +message NamedQuery { + // Name of the query, such that client can use the name to load this query + // from bundle, and resume from when the query results are materialized + // into this bundle. + string name = 1; + + // The query saved in the bundle. + BundledQuery bundled_query = 2; + + // The read time of the query, when it is used to build the bundle. This is useful to + // resume the query from the bundle, once it is loaded by client SDKs. + google.protobuf.Timestamp read_time = 3; +} + +// Metadata describing a Firestore document saved in the bundle. +message BundledDocumentMetadata { + // The document key of a bundled document. + string name = 1; + + // The snapshot version of the document data bundled. + google.protobuf.Timestamp read_time = 2; + + // Whether the document exists. + bool exists = 3; + + // The names of the queries in this bundle that this document matches to. + repeated string queries = 4; +} + +// Metadata describing the bundle file/stream. +message BundleMetadata { + // The ID of the bundle. + string id = 1; + + // Time at which the documents snapshot is taken for this bundle. + google.protobuf.Timestamp create_time = 2; + + // The schema version of the bundle. + uint32 version = 3; + + // The number of documents in the bundle. + uint32 total_documents = 4; + + // The size of the bundle in bytes, excluding this `BundleMetadata`. + uint64 total_bytes = 5; +} + +// A Firestore bundle is a length-prefixed stream of JSON representations of +// `BundleElement`. +// Only one `BundleMetadata` is expected, and it should be the first element. +// The named queries follow after `metadata`. Every `document_metadata` is +// immediately followed by a `document`. +message BundleElement { + oneof element_type { + BundleMetadata metadata = 1; + + NamedQuery named_query = 2; + + BundledDocumentMetadata document_metadata = 3; + + google.firestore.v1.Document document = 4; + } +} diff --git a/handwritten/firestore/dev/protos/firestore_admin_v1_proto_api.d.ts b/handwritten/firestore/dev/protos/firestore_admin_v1_proto_api.d.ts new file mode 100644 index 00000000000..0e5aeb9e870 --- /dev/null +++ b/handwritten/firestore/dev/protos/firestore_admin_v1_proto_api.d.ts @@ -0,0 +1,10845 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as $protobuf from "protobufjs"; +import Long = require("long"); +/** Namespace google. */ +export namespace google { + + /** Namespace firestore. */ + namespace firestore { + + /** Namespace admin. */ + namespace admin { + + /** Namespace v1. */ + namespace v1 { + + /** Properties of a Backup. */ + interface IBackup { + + /** Backup name */ + name?: (string|null); + + /** Backup database */ + database?: (string|null); + + /** Backup databaseUid */ + databaseUid?: (string|null); + + /** Backup snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + + /** Backup expireTime */ + expireTime?: (google.protobuf.ITimestamp|null); + + /** Backup stats */ + stats?: (google.firestore.admin.v1.Backup.IStats|null); + + /** Backup state */ + state?: (google.firestore.admin.v1.Backup.State|null); + } + + /** Represents a Backup. */ + class Backup implements IBackup { + + /** + * Constructs a new Backup. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBackup); + + /** Backup name. */ + public name: string; + + /** Backup database. */ + public database: string; + + /** Backup databaseUid. */ + public databaseUid: string; + + /** Backup snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** Backup expireTime. */ + public expireTime?: (google.protobuf.ITimestamp|null); + + /** Backup stats. */ + public stats?: (google.firestore.admin.v1.Backup.IStats|null); + + /** Backup state. */ + public state: google.firestore.admin.v1.Backup.State; + + /** + * Creates a Backup message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Backup + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Backup; + + /** + * Creates a plain object from a Backup message. Also converts values to other types if specified. + * @param message Backup + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Backup, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Backup to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Backup + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Backup { + + /** Properties of a Stats. */ + interface IStats { + + /** Stats sizeBytes */ + sizeBytes?: (number|string|null); + + /** Stats documentCount */ + documentCount?: (number|string|null); + + /** Stats indexCount */ + indexCount?: (number|string|null); + } + + /** Represents a Stats. */ + class Stats implements IStats { + + /** + * Constructs a new Stats. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Backup.IStats); + + /** Stats sizeBytes. */ + public sizeBytes: (number|string); + + /** Stats documentCount. */ + public documentCount: (number|string); + + /** Stats indexCount. */ + public indexCount: (number|string); + + /** + * Creates a Stats message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Stats + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Backup.Stats; + + /** + * Creates a plain object from a Stats message. Also converts values to other types if specified. + * @param message Stats + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Backup.Stats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Stats to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Stats + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "CREATING"| "READY"| "NOT_AVAILABLE"; + } + + /** Properties of a Database. */ + interface IDatabase { + + /** Database name */ + name?: (string|null); + + /** Database uid */ + uid?: (string|null); + + /** Database createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** Database updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** Database deleteTime */ + deleteTime?: (google.protobuf.ITimestamp|null); + + /** Database locationId */ + locationId?: (string|null); + + /** Database type */ + type?: (google.firestore.admin.v1.Database.DatabaseType|null); + + /** Database concurrencyMode */ + concurrencyMode?: (google.firestore.admin.v1.Database.ConcurrencyMode|null); + + /** Database versionRetentionPeriod */ + versionRetentionPeriod?: (google.protobuf.IDuration|null); + + /** Database earliestVersionTime */ + earliestVersionTime?: (google.protobuf.ITimestamp|null); + + /** Database pointInTimeRecoveryEnablement */ + pointInTimeRecoveryEnablement?: (google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement|null); + + /** Database appEngineIntegrationMode */ + appEngineIntegrationMode?: (google.firestore.admin.v1.Database.AppEngineIntegrationMode|null); + + /** Database keyPrefix */ + keyPrefix?: (string|null); + + /** Database deleteProtectionState */ + deleteProtectionState?: (google.firestore.admin.v1.Database.DeleteProtectionState|null); + + /** Database cmekConfig */ + cmekConfig?: (google.firestore.admin.v1.Database.ICmekConfig|null); + + /** Database previousId */ + previousId?: (string|null); + + /** Database sourceInfo */ + sourceInfo?: (google.firestore.admin.v1.Database.ISourceInfo|null); + + /** Database tags */ + tags?: ({ [k: string]: string }|null); + + /** Database freeTier */ + freeTier?: (boolean|null); + + /** Database etag */ + etag?: (string|null); + + /** Database databaseEdition */ + databaseEdition?: (google.firestore.admin.v1.Database.DatabaseEdition|null); + } + + /** Represents a Database. */ + class Database implements IDatabase { + + /** + * Constructs a new Database. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDatabase); + + /** Database name. */ + public name: string; + + /** Database uid. */ + public uid: string; + + /** Database createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** Database updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** Database deleteTime. */ + public deleteTime?: (google.protobuf.ITimestamp|null); + + /** Database locationId. */ + public locationId: string; + + /** Database type. */ + public type: google.firestore.admin.v1.Database.DatabaseType; + + /** Database concurrencyMode. */ + public concurrencyMode: google.firestore.admin.v1.Database.ConcurrencyMode; + + /** Database versionRetentionPeriod. */ + public versionRetentionPeriod?: (google.protobuf.IDuration|null); + + /** Database earliestVersionTime. */ + public earliestVersionTime?: (google.protobuf.ITimestamp|null); + + /** Database pointInTimeRecoveryEnablement. */ + public pointInTimeRecoveryEnablement: google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement; + + /** Database appEngineIntegrationMode. */ + public appEngineIntegrationMode: google.firestore.admin.v1.Database.AppEngineIntegrationMode; + + /** Database keyPrefix. */ + public keyPrefix: string; + + /** Database deleteProtectionState. */ + public deleteProtectionState: google.firestore.admin.v1.Database.DeleteProtectionState; + + /** Database cmekConfig. */ + public cmekConfig?: (google.firestore.admin.v1.Database.ICmekConfig|null); + + /** Database previousId. */ + public previousId: string; + + /** Database sourceInfo. */ + public sourceInfo?: (google.firestore.admin.v1.Database.ISourceInfo|null); + + /** Database tags. */ + public tags: { [k: string]: string }; + + /** Database freeTier. */ + public freeTier?: (boolean|null); + + /** Database etag. */ + public etag: string; + + /** Database databaseEdition. */ + public databaseEdition: google.firestore.admin.v1.Database.DatabaseEdition; + + /** + * Creates a Database message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Database + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database; + + /** + * Creates a plain object from a Database message. Also converts values to other types if specified. + * @param message Database + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Database to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Database + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Database { + + /** DatabaseType enum. */ + type DatabaseType = + "DATABASE_TYPE_UNSPECIFIED"| "FIRESTORE_NATIVE"| "DATASTORE_MODE"; + + /** ConcurrencyMode enum. */ + type ConcurrencyMode = + "CONCURRENCY_MODE_UNSPECIFIED"| "OPTIMISTIC"| "PESSIMISTIC"| "OPTIMISTIC_WITH_ENTITY_GROUPS"; + + /** PointInTimeRecoveryEnablement enum. */ + type PointInTimeRecoveryEnablement = + "POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED"| "POINT_IN_TIME_RECOVERY_ENABLED"| "POINT_IN_TIME_RECOVERY_DISABLED"; + + /** AppEngineIntegrationMode enum. */ + type AppEngineIntegrationMode = + "APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED"| "ENABLED"| "DISABLED"; + + /** DeleteProtectionState enum. */ + type DeleteProtectionState = + "DELETE_PROTECTION_STATE_UNSPECIFIED"| "DELETE_PROTECTION_DISABLED"| "DELETE_PROTECTION_ENABLED"; + + /** Properties of a CmekConfig. */ + interface ICmekConfig { + + /** CmekConfig kmsKeyName */ + kmsKeyName?: (string|null); + + /** CmekConfig activeKeyVersion */ + activeKeyVersion?: (string[]|null); + } + + /** Represents a CmekConfig. */ + class CmekConfig implements ICmekConfig { + + /** + * Constructs a new CmekConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.ICmekConfig); + + /** CmekConfig kmsKeyName. */ + public kmsKeyName: string; + + /** CmekConfig activeKeyVersion. */ + public activeKeyVersion: string[]; + + /** + * Creates a CmekConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CmekConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.CmekConfig; + + /** + * Creates a plain object from a CmekConfig message. Also converts values to other types if specified. + * @param message CmekConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.CmekConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CmekConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CmekConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SourceInfo. */ + interface ISourceInfo { + + /** SourceInfo backup */ + backup?: (google.firestore.admin.v1.Database.SourceInfo.IBackupSource|null); + + /** SourceInfo operation */ + operation?: (string|null); + } + + /** Represents a SourceInfo. */ + class SourceInfo implements ISourceInfo { + + /** + * Constructs a new SourceInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.ISourceInfo); + + /** SourceInfo backup. */ + public backup?: (google.firestore.admin.v1.Database.SourceInfo.IBackupSource|null); + + /** SourceInfo operation. */ + public operation: string; + + /** SourceInfo source. */ + public source?: "backup"; + + /** + * Creates a SourceInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceInfo + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.SourceInfo; + + /** + * Creates a plain object from a SourceInfo message. Also converts values to other types if specified. + * @param message SourceInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.SourceInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SourceInfo { + + /** Properties of a BackupSource. */ + interface IBackupSource { + + /** BackupSource backup */ + backup?: (string|null); + } + + /** Represents a BackupSource. */ + class BackupSource implements IBackupSource { + + /** + * Constructs a new BackupSource. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.SourceInfo.IBackupSource); + + /** BackupSource backup. */ + public backup: string; + + /** + * Creates a BackupSource message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BackupSource + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.SourceInfo.BackupSource; + + /** + * Creates a plain object from a BackupSource message. Also converts values to other types if specified. + * @param message BackupSource + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.SourceInfo.BackupSource, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BackupSource to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BackupSource + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an EncryptionConfig. */ + interface IEncryptionConfig { + + /** EncryptionConfig googleDefaultEncryption */ + googleDefaultEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.IGoogleDefaultEncryptionOptions|null); + + /** EncryptionConfig useSourceEncryption */ + useSourceEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.ISourceEncryptionOptions|null); + + /** EncryptionConfig customerManagedEncryption */ + customerManagedEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.ICustomerManagedEncryptionOptions|null); + } + + /** Represents an EncryptionConfig. */ + class EncryptionConfig implements IEncryptionConfig { + + /** + * Constructs a new EncryptionConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.IEncryptionConfig); + + /** EncryptionConfig googleDefaultEncryption. */ + public googleDefaultEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.IGoogleDefaultEncryptionOptions|null); + + /** EncryptionConfig useSourceEncryption. */ + public useSourceEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.ISourceEncryptionOptions|null); + + /** EncryptionConfig customerManagedEncryption. */ + public customerManagedEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.ICustomerManagedEncryptionOptions|null); + + /** EncryptionConfig encryptionType. */ + public encryptionType?: ("googleDefaultEncryption"|"useSourceEncryption"|"customerManagedEncryption"); + + /** + * Creates an EncryptionConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EncryptionConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.EncryptionConfig; + + /** + * Creates a plain object from an EncryptionConfig message. Also converts values to other types if specified. + * @param message EncryptionConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.EncryptionConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EncryptionConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EncryptionConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EncryptionConfig { + + /** Properties of a GoogleDefaultEncryptionOptions. */ + interface IGoogleDefaultEncryptionOptions { + } + + /** Represents a GoogleDefaultEncryptionOptions. */ + class GoogleDefaultEncryptionOptions implements IGoogleDefaultEncryptionOptions { + + /** + * Constructs a new GoogleDefaultEncryptionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.EncryptionConfig.IGoogleDefaultEncryptionOptions); + + /** + * Creates a GoogleDefaultEncryptionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoogleDefaultEncryptionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions; + + /** + * Creates a plain object from a GoogleDefaultEncryptionOptions message. Also converts values to other types if specified. + * @param message GoogleDefaultEncryptionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoogleDefaultEncryptionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoogleDefaultEncryptionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SourceEncryptionOptions. */ + interface ISourceEncryptionOptions { + } + + /** Represents a SourceEncryptionOptions. */ + class SourceEncryptionOptions implements ISourceEncryptionOptions { + + /** + * Constructs a new SourceEncryptionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.EncryptionConfig.ISourceEncryptionOptions); + + /** + * Creates a SourceEncryptionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceEncryptionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions; + + /** + * Creates a plain object from a SourceEncryptionOptions message. Also converts values to other types if specified. + * @param message SourceEncryptionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceEncryptionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceEncryptionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomerManagedEncryptionOptions. */ + interface ICustomerManagedEncryptionOptions { + + /** CustomerManagedEncryptionOptions kmsKeyName */ + kmsKeyName?: (string|null); + } + + /** Represents a CustomerManagedEncryptionOptions. */ + class CustomerManagedEncryptionOptions implements ICustomerManagedEncryptionOptions { + + /** + * Constructs a new CustomerManagedEncryptionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.EncryptionConfig.ICustomerManagedEncryptionOptions); + + /** CustomerManagedEncryptionOptions kmsKeyName. */ + public kmsKeyName: string; + + /** + * Creates a CustomerManagedEncryptionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomerManagedEncryptionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions; + + /** + * Creates a plain object from a CustomerManagedEncryptionOptions message. Also converts values to other types if specified. + * @param message CustomerManagedEncryptionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomerManagedEncryptionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomerManagedEncryptionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** DatabaseEdition enum. */ + type DatabaseEdition = + "DATABASE_EDITION_UNSPECIFIED"| "STANDARD"| "ENTERPRISE"; + } + + /** Properties of a Field. */ + interface IField { + + /** Field name */ + name?: (string|null); + + /** Field indexConfig */ + indexConfig?: (google.firestore.admin.v1.Field.IIndexConfig|null); + + /** Field ttlConfig */ + ttlConfig?: (google.firestore.admin.v1.Field.ITtlConfig|null); + } + + /** Represents a Field. */ + class Field implements IField { + + /** + * Constructs a new Field. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IField); + + /** Field name. */ + public name: string; + + /** Field indexConfig. */ + public indexConfig?: (google.firestore.admin.v1.Field.IIndexConfig|null); + + /** Field ttlConfig. */ + public ttlConfig?: (google.firestore.admin.v1.Field.ITtlConfig|null); + + /** + * Creates a Field message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Field + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Field; + + /** + * Creates a plain object from a Field message. Also converts values to other types if specified. + * @param message Field + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Field, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Field to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Field + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Field { + + /** Properties of an IndexConfig. */ + interface IIndexConfig { + + /** IndexConfig indexes */ + indexes?: (google.firestore.admin.v1.IIndex[]|null); + + /** IndexConfig usesAncestorConfig */ + usesAncestorConfig?: (boolean|null); + + /** IndexConfig ancestorField */ + ancestorField?: (string|null); + + /** IndexConfig reverting */ + reverting?: (boolean|null); + } + + /** Represents an IndexConfig. */ + class IndexConfig implements IIndexConfig { + + /** + * Constructs a new IndexConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Field.IIndexConfig); + + /** IndexConfig indexes. */ + public indexes: google.firestore.admin.v1.IIndex[]; + + /** IndexConfig usesAncestorConfig. */ + public usesAncestorConfig: boolean; + + /** IndexConfig ancestorField. */ + public ancestorField: string; + + /** IndexConfig reverting. */ + public reverting: boolean; + + /** + * Creates an IndexConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Field.IndexConfig; + + /** + * Creates a plain object from an IndexConfig message. Also converts values to other types if specified. + * @param message IndexConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Field.IndexConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TtlConfig. */ + interface ITtlConfig { + + /** TtlConfig state */ + state?: (google.firestore.admin.v1.Field.TtlConfig.State|null); + } + + /** Represents a TtlConfig. */ + class TtlConfig implements ITtlConfig { + + /** + * Constructs a new TtlConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Field.ITtlConfig); + + /** TtlConfig state. */ + public state: google.firestore.admin.v1.Field.TtlConfig.State; + + /** + * Creates a TtlConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TtlConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Field.TtlConfig; + + /** + * Creates a plain object from a TtlConfig message. Also converts values to other types if specified. + * @param message TtlConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Field.TtlConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TtlConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TtlConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TtlConfig { + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "CREATING"| "ACTIVE"| "NEEDS_REPAIR"; + } + } + + /** Properties of an Index. */ + interface IIndex { + + /** Index name */ + name?: (string|null); + + /** Index queryScope */ + queryScope?: (google.firestore.admin.v1.Index.QueryScope|null); + + /** Index apiScope */ + apiScope?: (google.firestore.admin.v1.Index.ApiScope|null); + + /** Index fields */ + fields?: (google.firestore.admin.v1.Index.IIndexField[]|null); + + /** Index state */ + state?: (google.firestore.admin.v1.Index.State|null); + + /** Index density */ + density?: (google.firestore.admin.v1.Index.Density|null); + + /** Index multikey */ + multikey?: (boolean|null); + + /** Index shardCount */ + shardCount?: (number|null); + } + + /** Represents an Index. */ + class Index implements IIndex { + + /** + * Constructs a new Index. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IIndex); + + /** Index name. */ + public name: string; + + /** Index queryScope. */ + public queryScope: google.firestore.admin.v1.Index.QueryScope; + + /** Index apiScope. */ + public apiScope: google.firestore.admin.v1.Index.ApiScope; + + /** Index fields. */ + public fields: google.firestore.admin.v1.Index.IIndexField[]; + + /** Index state. */ + public state: google.firestore.admin.v1.Index.State; + + /** Index density. */ + public density: google.firestore.admin.v1.Index.Density; + + /** Index multikey. */ + public multikey: boolean; + + /** Index shardCount. */ + public shardCount: number; + + /** + * Creates an Index message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Index + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index; + + /** + * Creates a plain object from an Index message. Also converts values to other types if specified. + * @param message Index + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Index to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Index + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Index { + + /** QueryScope enum. */ + type QueryScope = + "QUERY_SCOPE_UNSPECIFIED"| "COLLECTION"| "COLLECTION_GROUP"| "COLLECTION_RECURSIVE"; + + /** ApiScope enum. */ + type ApiScope = + "ANY_API"| "DATASTORE_MODE_API"| "MONGODB_COMPATIBLE_API"; + + /** Properties of an IndexField. */ + interface IIndexField { + + /** IndexField fieldPath */ + fieldPath?: (string|null); + + /** IndexField order */ + order?: (google.firestore.admin.v1.Index.IndexField.Order|null); + + /** IndexField arrayConfig */ + arrayConfig?: (google.firestore.admin.v1.Index.IndexField.ArrayConfig|null); + + /** IndexField vectorConfig */ + vectorConfig?: (google.firestore.admin.v1.Index.IndexField.IVectorConfig|null); + } + + /** Represents an IndexField. */ + class IndexField implements IIndexField { + + /** + * Constructs a new IndexField. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Index.IIndexField); + + /** IndexField fieldPath. */ + public fieldPath: string; + + /** IndexField order. */ + public order?: (google.firestore.admin.v1.Index.IndexField.Order|null); + + /** IndexField arrayConfig. */ + public arrayConfig?: (google.firestore.admin.v1.Index.IndexField.ArrayConfig|null); + + /** IndexField vectorConfig. */ + public vectorConfig?: (google.firestore.admin.v1.Index.IndexField.IVectorConfig|null); + + /** IndexField valueMode. */ + public valueMode?: ("order"|"arrayConfig"|"vectorConfig"); + + /** + * Creates an IndexField message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexField + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField; + + /** + * Creates a plain object from an IndexField message. Also converts values to other types if specified. + * @param message IndexField + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index.IndexField, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexField to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexField + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace IndexField { + + /** Order enum. */ + type Order = + "ORDER_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; + + /** ArrayConfig enum. */ + type ArrayConfig = + "ARRAY_CONFIG_UNSPECIFIED"| "CONTAINS"; + + /** Properties of a VectorConfig. */ + interface IVectorConfig { + + /** VectorConfig dimension */ + dimension?: (number|null); + + /** VectorConfig flat */ + flat?: (google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex|null); + } + + /** Represents a VectorConfig. */ + class VectorConfig implements IVectorConfig { + + /** + * Constructs a new VectorConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Index.IndexField.IVectorConfig); + + /** VectorConfig dimension. */ + public dimension: number; + + /** VectorConfig flat. */ + public flat?: (google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex|null); + + /** VectorConfig type. */ + public type?: "flat"; + + /** + * Creates a VectorConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns VectorConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField.VectorConfig; + + /** + * Creates a plain object from a VectorConfig message. Also converts values to other types if specified. + * @param message VectorConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index.IndexField.VectorConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this VectorConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for VectorConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace VectorConfig { + + /** Properties of a FlatIndex. */ + interface IFlatIndex { + } + + /** Represents a FlatIndex. */ + class FlatIndex implements IFlatIndex { + + /** + * Constructs a new FlatIndex. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex); + + /** + * Creates a FlatIndex message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FlatIndex + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex; + + /** + * Creates a plain object from a FlatIndex message. Also converts values to other types if specified. + * @param message FlatIndex + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FlatIndex to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FlatIndex + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "CREATING"| "READY"| "NEEDS_REPAIR"; + + /** Density enum. */ + type Density = + "DENSITY_UNSPECIFIED"| "SPARSE_ALL"| "SPARSE_ANY"| "DENSE"; + } + + /** Represents a FirestoreAdmin */ + class FirestoreAdmin extends $protobuf.rpc.Service { + + /** + * Constructs a new FirestoreAdmin service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls CreateIndex. + * @param request CreateIndexRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public createIndex(request: google.firestore.admin.v1.ICreateIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateIndexCallback): void; + + /** + * Calls CreateIndex. + * @param request CreateIndexRequest message or plain object + * @returns Promise + */ + public createIndex(request: google.firestore.admin.v1.ICreateIndexRequest): Promise; + + /** + * Calls ListIndexes. + * @param request ListIndexesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListIndexesResponse + */ + public listIndexes(request: google.firestore.admin.v1.IListIndexesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListIndexesCallback): void; + + /** + * Calls ListIndexes. + * @param request ListIndexesRequest message or plain object + * @returns Promise + */ + public listIndexes(request: google.firestore.admin.v1.IListIndexesRequest): Promise; + + /** + * Calls GetIndex. + * @param request GetIndexRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Index + */ + public getIndex(request: google.firestore.admin.v1.IGetIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetIndexCallback): void; + + /** + * Calls GetIndex. + * @param request GetIndexRequest message or plain object + * @returns Promise + */ + public getIndex(request: google.firestore.admin.v1.IGetIndexRequest): Promise; + + /** + * Calls DeleteIndex. + * @param request DeleteIndexRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteIndex(request: google.firestore.admin.v1.IDeleteIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteIndexCallback): void; + + /** + * Calls DeleteIndex. + * @param request DeleteIndexRequest message or plain object + * @returns Promise + */ + public deleteIndex(request: google.firestore.admin.v1.IDeleteIndexRequest): Promise; + + /** + * Calls GetField. + * @param request GetFieldRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Field + */ + public getField(request: google.firestore.admin.v1.IGetFieldRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetFieldCallback): void; + + /** + * Calls GetField. + * @param request GetFieldRequest message or plain object + * @returns Promise + */ + public getField(request: google.firestore.admin.v1.IGetFieldRequest): Promise; + + /** + * Calls UpdateField. + * @param request UpdateFieldRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public updateField(request: google.firestore.admin.v1.IUpdateFieldRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateFieldCallback): void; + + /** + * Calls UpdateField. + * @param request UpdateFieldRequest message or plain object + * @returns Promise + */ + public updateField(request: google.firestore.admin.v1.IUpdateFieldRequest): Promise; + + /** + * Calls ListFields. + * @param request ListFieldsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListFieldsResponse + */ + public listFields(request: google.firestore.admin.v1.IListFieldsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListFieldsCallback): void; + + /** + * Calls ListFields. + * @param request ListFieldsRequest message or plain object + * @returns Promise + */ + public listFields(request: google.firestore.admin.v1.IListFieldsRequest): Promise; + + /** + * Calls ExportDocuments. + * @param request ExportDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public exportDocuments(request: google.firestore.admin.v1.IExportDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ExportDocumentsCallback): void; + + /** + * Calls ExportDocuments. + * @param request ExportDocumentsRequest message or plain object + * @returns Promise + */ + public exportDocuments(request: google.firestore.admin.v1.IExportDocumentsRequest): Promise; + + /** + * Calls ImportDocuments. + * @param request ImportDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public importDocuments(request: google.firestore.admin.v1.IImportDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ImportDocumentsCallback): void; + + /** + * Calls ImportDocuments. + * @param request ImportDocumentsRequest message or plain object + * @returns Promise + */ + public importDocuments(request: google.firestore.admin.v1.IImportDocumentsRequest): Promise; + + /** + * Calls BulkDeleteDocuments. + * @param request BulkDeleteDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public bulkDeleteDocuments(request: google.firestore.admin.v1.IBulkDeleteDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocumentsCallback): void; + + /** + * Calls BulkDeleteDocuments. + * @param request BulkDeleteDocumentsRequest message or plain object + * @returns Promise + */ + public bulkDeleteDocuments(request: google.firestore.admin.v1.IBulkDeleteDocumentsRequest): Promise; + + /** + * Calls CreateDatabase. + * @param request CreateDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public createDatabase(request: google.firestore.admin.v1.ICreateDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateDatabaseCallback): void; + + /** + * Calls CreateDatabase. + * @param request CreateDatabaseRequest message or plain object + * @returns Promise + */ + public createDatabase(request: google.firestore.admin.v1.ICreateDatabaseRequest): Promise; + + /** + * Calls GetDatabase. + * @param request GetDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Database + */ + public getDatabase(request: google.firestore.admin.v1.IGetDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetDatabaseCallback): void; + + /** + * Calls GetDatabase. + * @param request GetDatabaseRequest message or plain object + * @returns Promise + */ + public getDatabase(request: google.firestore.admin.v1.IGetDatabaseRequest): Promise; + + /** + * Calls ListDatabases. + * @param request ListDatabasesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDatabasesResponse + */ + public listDatabases(request: google.firestore.admin.v1.IListDatabasesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListDatabasesCallback): void; + + /** + * Calls ListDatabases. + * @param request ListDatabasesRequest message or plain object + * @returns Promise + */ + public listDatabases(request: google.firestore.admin.v1.IListDatabasesRequest): Promise; + + /** + * Calls UpdateDatabase. + * @param request UpdateDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public updateDatabase(request: google.firestore.admin.v1.IUpdateDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateDatabaseCallback): void; + + /** + * Calls UpdateDatabase. + * @param request UpdateDatabaseRequest message or plain object + * @returns Promise + */ + public updateDatabase(request: google.firestore.admin.v1.IUpdateDatabaseRequest): Promise; + + /** + * Calls DeleteDatabase. + * @param request DeleteDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public deleteDatabase(request: google.firestore.admin.v1.IDeleteDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteDatabaseCallback): void; + + /** + * Calls DeleteDatabase. + * @param request DeleteDatabaseRequest message or plain object + * @returns Promise + */ + public deleteDatabase(request: google.firestore.admin.v1.IDeleteDatabaseRequest): Promise; + + /** + * Calls CreateUserCreds. + * @param request CreateUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserCreds + */ + public createUserCreds(request: google.firestore.admin.v1.ICreateUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateUserCredsCallback): void; + + /** + * Calls CreateUserCreds. + * @param request CreateUserCredsRequest message or plain object + * @returns Promise + */ + public createUserCreds(request: google.firestore.admin.v1.ICreateUserCredsRequest): Promise; + + /** + * Calls GetUserCreds. + * @param request GetUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserCreds + */ + public getUserCreds(request: google.firestore.admin.v1.IGetUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetUserCredsCallback): void; + + /** + * Calls GetUserCreds. + * @param request GetUserCredsRequest message or plain object + * @returns Promise + */ + public getUserCreds(request: google.firestore.admin.v1.IGetUserCredsRequest): Promise; + + /** + * Calls ListUserCreds. + * @param request ListUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListUserCredsResponse + */ + public listUserCreds(request: google.firestore.admin.v1.IListUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListUserCredsCallback): void; + + /** + * Calls ListUserCreds. + * @param request ListUserCredsRequest message or plain object + * @returns Promise + */ + public listUserCreds(request: google.firestore.admin.v1.IListUserCredsRequest): Promise; + + /** + * Calls EnableUserCreds. + * @param request EnableUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserCreds + */ + public enableUserCreds(request: google.firestore.admin.v1.IEnableUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.EnableUserCredsCallback): void; + + /** + * Calls EnableUserCreds. + * @param request EnableUserCredsRequest message or plain object + * @returns Promise + */ + public enableUserCreds(request: google.firestore.admin.v1.IEnableUserCredsRequest): Promise; + + /** + * Calls DisableUserCreds. + * @param request DisableUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserCreds + */ + public disableUserCreds(request: google.firestore.admin.v1.IDisableUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DisableUserCredsCallback): void; + + /** + * Calls DisableUserCreds. + * @param request DisableUserCredsRequest message or plain object + * @returns Promise + */ + public disableUserCreds(request: google.firestore.admin.v1.IDisableUserCredsRequest): Promise; + + /** + * Calls ResetUserPassword. + * @param request ResetUserPasswordRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserCreds + */ + public resetUserPassword(request: google.firestore.admin.v1.IResetUserPasswordRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ResetUserPasswordCallback): void; + + /** + * Calls ResetUserPassword. + * @param request ResetUserPasswordRequest message or plain object + * @returns Promise + */ + public resetUserPassword(request: google.firestore.admin.v1.IResetUserPasswordRequest): Promise; + + /** + * Calls DeleteUserCreds. + * @param request DeleteUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteUserCreds(request: google.firestore.admin.v1.IDeleteUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteUserCredsCallback): void; + + /** + * Calls DeleteUserCreds. + * @param request DeleteUserCredsRequest message or plain object + * @returns Promise + */ + public deleteUserCreds(request: google.firestore.admin.v1.IDeleteUserCredsRequest): Promise; + + /** + * Calls GetBackup. + * @param request GetBackupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Backup + */ + public getBackup(request: google.firestore.admin.v1.IGetBackupRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetBackupCallback): void; + + /** + * Calls GetBackup. + * @param request GetBackupRequest message or plain object + * @returns Promise + */ + public getBackup(request: google.firestore.admin.v1.IGetBackupRequest): Promise; + + /** + * Calls ListBackups. + * @param request ListBackupsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListBackupsResponse + */ + public listBackups(request: google.firestore.admin.v1.IListBackupsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListBackupsCallback): void; + + /** + * Calls ListBackups. + * @param request ListBackupsRequest message or plain object + * @returns Promise + */ + public listBackups(request: google.firestore.admin.v1.IListBackupsRequest): Promise; + + /** + * Calls DeleteBackup. + * @param request DeleteBackupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteBackup(request: google.firestore.admin.v1.IDeleteBackupRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteBackupCallback): void; + + /** + * Calls DeleteBackup. + * @param request DeleteBackupRequest message or plain object + * @returns Promise + */ + public deleteBackup(request: google.firestore.admin.v1.IDeleteBackupRequest): Promise; + + /** + * Calls RestoreDatabase. + * @param request RestoreDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public restoreDatabase(request: google.firestore.admin.v1.IRestoreDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.RestoreDatabaseCallback): void; + + /** + * Calls RestoreDatabase. + * @param request RestoreDatabaseRequest message or plain object + * @returns Promise + */ + public restoreDatabase(request: google.firestore.admin.v1.IRestoreDatabaseRequest): Promise; + + /** + * Calls CreateBackupSchedule. + * @param request CreateBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public createBackupSchedule(request: google.firestore.admin.v1.ICreateBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateBackupScheduleCallback): void; + + /** + * Calls CreateBackupSchedule. + * @param request CreateBackupScheduleRequest message or plain object + * @returns Promise + */ + public createBackupSchedule(request: google.firestore.admin.v1.ICreateBackupScheduleRequest): Promise; + + /** + * Calls GetBackupSchedule. + * @param request GetBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public getBackupSchedule(request: google.firestore.admin.v1.IGetBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetBackupScheduleCallback): void; + + /** + * Calls GetBackupSchedule. + * @param request GetBackupScheduleRequest message or plain object + * @returns Promise + */ + public getBackupSchedule(request: google.firestore.admin.v1.IGetBackupScheduleRequest): Promise; + + /** + * Calls ListBackupSchedules. + * @param request ListBackupSchedulesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListBackupSchedulesResponse + */ + public listBackupSchedules(request: google.firestore.admin.v1.IListBackupSchedulesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListBackupSchedulesCallback): void; + + /** + * Calls ListBackupSchedules. + * @param request ListBackupSchedulesRequest message or plain object + * @returns Promise + */ + public listBackupSchedules(request: google.firestore.admin.v1.IListBackupSchedulesRequest): Promise; + + /** + * Calls UpdateBackupSchedule. + * @param request UpdateBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public updateBackupSchedule(request: google.firestore.admin.v1.IUpdateBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateBackupScheduleCallback): void; + + /** + * Calls UpdateBackupSchedule. + * @param request UpdateBackupScheduleRequest message or plain object + * @returns Promise + */ + public updateBackupSchedule(request: google.firestore.admin.v1.IUpdateBackupScheduleRequest): Promise; + + /** + * Calls DeleteBackupSchedule. + * @param request DeleteBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteBackupSchedule(request: google.firestore.admin.v1.IDeleteBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteBackupScheduleCallback): void; + + /** + * Calls DeleteBackupSchedule. + * @param request DeleteBackupScheduleRequest message or plain object + * @returns Promise + */ + public deleteBackupSchedule(request: google.firestore.admin.v1.IDeleteBackupScheduleRequest): Promise; + + /** + * Calls CloneDatabase. + * @param request CloneDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public cloneDatabase(request: google.firestore.admin.v1.ICloneDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CloneDatabaseCallback): void; + + /** + * Calls CloneDatabase. + * @param request CloneDatabaseRequest message or plain object + * @returns Promise + */ + public cloneDatabase(request: google.firestore.admin.v1.ICloneDatabaseRequest): Promise; + } + + namespace FirestoreAdmin { + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createIndex}. + * @param error Error, if any + * @param [response] Operation + */ + type CreateIndexCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listIndexes}. + * @param error Error, if any + * @param [response] ListIndexesResponse + */ + type ListIndexesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListIndexesResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getIndex}. + * @param error Error, if any + * @param [response] Index + */ + type GetIndexCallback = (error: (Error|null), response?: google.firestore.admin.v1.Index) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteIndex}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteIndexCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getField}. + * @param error Error, if any + * @param [response] Field + */ + type GetFieldCallback = (error: (Error|null), response?: google.firestore.admin.v1.Field) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateField}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateFieldCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listFields}. + * @param error Error, if any + * @param [response] ListFieldsResponse + */ + type ListFieldsCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListFieldsResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#exportDocuments}. + * @param error Error, if any + * @param [response] Operation + */ + type ExportDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#importDocuments}. + * @param error Error, if any + * @param [response] Operation + */ + type ImportDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#bulkDeleteDocuments}. + * @param error Error, if any + * @param [response] Operation + */ + type BulkDeleteDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type CreateDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getDatabase}. + * @param error Error, if any + * @param [response] Database + */ + type GetDatabaseCallback = (error: (Error|null), response?: google.firestore.admin.v1.Database) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listDatabases}. + * @param error Error, if any + * @param [response] ListDatabasesResponse + */ + type ListDatabasesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListDatabasesResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type DeleteDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createUserCreds}. + * @param error Error, if any + * @param [response] UserCreds + */ + type CreateUserCredsCallback = (error: (Error|null), response?: google.firestore.admin.v1.UserCreds) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getUserCreds}. + * @param error Error, if any + * @param [response] UserCreds + */ + type GetUserCredsCallback = (error: (Error|null), response?: google.firestore.admin.v1.UserCreds) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listUserCreds}. + * @param error Error, if any + * @param [response] ListUserCredsResponse + */ + type ListUserCredsCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListUserCredsResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#enableUserCreds}. + * @param error Error, if any + * @param [response] UserCreds + */ + type EnableUserCredsCallback = (error: (Error|null), response?: google.firestore.admin.v1.UserCreds) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#disableUserCreds}. + * @param error Error, if any + * @param [response] UserCreds + */ + type DisableUserCredsCallback = (error: (Error|null), response?: google.firestore.admin.v1.UserCreds) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#resetUserPassword}. + * @param error Error, if any + * @param [response] UserCreds + */ + type ResetUserPasswordCallback = (error: (Error|null), response?: google.firestore.admin.v1.UserCreds) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteUserCreds}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteUserCredsCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getBackup}. + * @param error Error, if any + * @param [response] Backup + */ + type GetBackupCallback = (error: (Error|null), response?: google.firestore.admin.v1.Backup) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listBackups}. + * @param error Error, if any + * @param [response] ListBackupsResponse + */ + type ListBackupsCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListBackupsResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteBackup}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteBackupCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#restoreDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type RestoreDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type CreateBackupScheduleCallback = (error: (Error|null), response?: google.firestore.admin.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type GetBackupScheduleCallback = (error: (Error|null), response?: google.firestore.admin.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listBackupSchedules}. + * @param error Error, if any + * @param [response] ListBackupSchedulesResponse + */ + type ListBackupSchedulesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListBackupSchedulesResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type UpdateBackupScheduleCallback = (error: (Error|null), response?: google.firestore.admin.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteBackupSchedule}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteBackupScheduleCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#cloneDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type CloneDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of a ListDatabasesRequest. */ + interface IListDatabasesRequest { + + /** ListDatabasesRequest parent */ + parent?: (string|null); + + /** ListDatabasesRequest showDeleted */ + showDeleted?: (boolean|null); + } + + /** Represents a ListDatabasesRequest. */ + class ListDatabasesRequest implements IListDatabasesRequest { + + /** + * Constructs a new ListDatabasesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListDatabasesRequest); + + /** ListDatabasesRequest parent. */ + public parent: string; + + /** ListDatabasesRequest showDeleted. */ + public showDeleted: boolean; + + /** + * Creates a ListDatabasesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDatabasesRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListDatabasesRequest; + + /** + * Creates a plain object from a ListDatabasesRequest message. Also converts values to other types if specified. + * @param message ListDatabasesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListDatabasesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDatabasesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDatabasesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDatabaseRequest. */ + interface ICreateDatabaseRequest { + + /** CreateDatabaseRequest parent */ + parent?: (string|null); + + /** CreateDatabaseRequest database */ + database?: (google.firestore.admin.v1.IDatabase|null); + + /** CreateDatabaseRequest databaseId */ + databaseId?: (string|null); + } + + /** Represents a CreateDatabaseRequest. */ + class CreateDatabaseRequest implements ICreateDatabaseRequest { + + /** + * Constructs a new CreateDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateDatabaseRequest); + + /** CreateDatabaseRequest parent. */ + public parent: string; + + /** CreateDatabaseRequest database. */ + public database?: (google.firestore.admin.v1.IDatabase|null); + + /** CreateDatabaseRequest databaseId. */ + public databaseId: string; + + /** + * Creates a CreateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateDatabaseRequest; + + /** + * Creates a plain object from a CreateDatabaseRequest message. Also converts values to other types if specified. + * @param message CreateDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDatabaseMetadata. */ + interface ICreateDatabaseMetadata { + } + + /** Represents a CreateDatabaseMetadata. */ + class CreateDatabaseMetadata implements ICreateDatabaseMetadata { + + /** + * Constructs a new CreateDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateDatabaseMetadata); + + /** + * Creates a CreateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateDatabaseMetadata; + + /** + * Creates a plain object from a CreateDatabaseMetadata message. Also converts values to other types if specified. + * @param message CreateDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDatabasesResponse. */ + interface IListDatabasesResponse { + + /** ListDatabasesResponse databases */ + databases?: (google.firestore.admin.v1.IDatabase[]|null); + + /** ListDatabasesResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListDatabasesResponse. */ + class ListDatabasesResponse implements IListDatabasesResponse { + + /** + * Constructs a new ListDatabasesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListDatabasesResponse); + + /** ListDatabasesResponse databases. */ + public databases: google.firestore.admin.v1.IDatabase[]; + + /** ListDatabasesResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a ListDatabasesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDatabasesResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListDatabasesResponse; + + /** + * Creates a plain object from a ListDatabasesResponse message. Also converts values to other types if specified. + * @param message ListDatabasesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListDatabasesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDatabasesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDatabasesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetDatabaseRequest. */ + interface IGetDatabaseRequest { + + /** GetDatabaseRequest name */ + name?: (string|null); + } + + /** Represents a GetDatabaseRequest. */ + class GetDatabaseRequest implements IGetDatabaseRequest { + + /** + * Constructs a new GetDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetDatabaseRequest); + + /** GetDatabaseRequest name. */ + public name: string; + + /** + * Creates a GetDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetDatabaseRequest; + + /** + * Creates a plain object from a GetDatabaseRequest message. Also converts values to other types if specified. + * @param message GetDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDatabaseRequest. */ + interface IUpdateDatabaseRequest { + + /** UpdateDatabaseRequest database */ + database?: (google.firestore.admin.v1.IDatabase|null); + + /** UpdateDatabaseRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateDatabaseRequest. */ + class UpdateDatabaseRequest implements IUpdateDatabaseRequest { + + /** + * Constructs a new UpdateDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateDatabaseRequest); + + /** UpdateDatabaseRequest database. */ + public database?: (google.firestore.admin.v1.IDatabase|null); + + /** UpdateDatabaseRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates an UpdateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateDatabaseRequest; + + /** + * Creates a plain object from an UpdateDatabaseRequest message. Also converts values to other types if specified. + * @param message UpdateDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDatabaseMetadata. */ + interface IUpdateDatabaseMetadata { + } + + /** Represents an UpdateDatabaseMetadata. */ + class UpdateDatabaseMetadata implements IUpdateDatabaseMetadata { + + /** + * Constructs a new UpdateDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateDatabaseMetadata); + + /** + * Creates an UpdateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateDatabaseMetadata; + + /** + * Creates a plain object from an UpdateDatabaseMetadata message. Also converts values to other types if specified. + * @param message UpdateDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDatabaseRequest. */ + interface IDeleteDatabaseRequest { + + /** DeleteDatabaseRequest name */ + name?: (string|null); + + /** DeleteDatabaseRequest etag */ + etag?: (string|null); + } + + /** Represents a DeleteDatabaseRequest. */ + class DeleteDatabaseRequest implements IDeleteDatabaseRequest { + + /** + * Constructs a new DeleteDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteDatabaseRequest); + + /** DeleteDatabaseRequest name. */ + public name: string; + + /** DeleteDatabaseRequest etag. */ + public etag: string; + + /** + * Creates a DeleteDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteDatabaseRequest; + + /** + * Creates a plain object from a DeleteDatabaseRequest message. Also converts values to other types if specified. + * @param message DeleteDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDatabaseMetadata. */ + interface IDeleteDatabaseMetadata { + } + + /** Represents a DeleteDatabaseMetadata. */ + class DeleteDatabaseMetadata implements IDeleteDatabaseMetadata { + + /** + * Constructs a new DeleteDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteDatabaseMetadata); + + /** + * Creates a DeleteDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteDatabaseMetadata; + + /** + * Creates a plain object from a DeleteDatabaseMetadata message. Also converts values to other types if specified. + * @param message DeleteDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateUserCredsRequest. */ + interface ICreateUserCredsRequest { + + /** CreateUserCredsRequest parent */ + parent?: (string|null); + + /** CreateUserCredsRequest userCreds */ + userCreds?: (google.firestore.admin.v1.IUserCreds|null); + + /** CreateUserCredsRequest userCredsId */ + userCredsId?: (string|null); + } + + /** Represents a CreateUserCredsRequest. */ + class CreateUserCredsRequest implements ICreateUserCredsRequest { + + /** + * Constructs a new CreateUserCredsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateUserCredsRequest); + + /** CreateUserCredsRequest parent. */ + public parent: string; + + /** CreateUserCredsRequest userCreds. */ + public userCreds?: (google.firestore.admin.v1.IUserCreds|null); + + /** CreateUserCredsRequest userCredsId. */ + public userCredsId: string; + + /** + * Creates a CreateUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateUserCredsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateUserCredsRequest; + + /** + * Creates a plain object from a CreateUserCredsRequest message. Also converts values to other types if specified. + * @param message CreateUserCredsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateUserCredsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateUserCredsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetUserCredsRequest. */ + interface IGetUserCredsRequest { + + /** GetUserCredsRequest name */ + name?: (string|null); + } + + /** Represents a GetUserCredsRequest. */ + class GetUserCredsRequest implements IGetUserCredsRequest { + + /** + * Constructs a new GetUserCredsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetUserCredsRequest); + + /** GetUserCredsRequest name. */ + public name: string; + + /** + * Creates a GetUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetUserCredsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetUserCredsRequest; + + /** + * Creates a plain object from a GetUserCredsRequest message. Also converts values to other types if specified. + * @param message GetUserCredsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetUserCredsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetUserCredsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListUserCredsRequest. */ + interface IListUserCredsRequest { + + /** ListUserCredsRequest parent */ + parent?: (string|null); + } + + /** Represents a ListUserCredsRequest. */ + class ListUserCredsRequest implements IListUserCredsRequest { + + /** + * Constructs a new ListUserCredsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListUserCredsRequest); + + /** ListUserCredsRequest parent. */ + public parent: string; + + /** + * Creates a ListUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListUserCredsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListUserCredsRequest; + + /** + * Creates a plain object from a ListUserCredsRequest message. Also converts values to other types if specified. + * @param message ListUserCredsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListUserCredsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListUserCredsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListUserCredsResponse. */ + interface IListUserCredsResponse { + + /** ListUserCredsResponse userCreds */ + userCreds?: (google.firestore.admin.v1.IUserCreds[]|null); + } + + /** Represents a ListUserCredsResponse. */ + class ListUserCredsResponse implements IListUserCredsResponse { + + /** + * Constructs a new ListUserCredsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListUserCredsResponse); + + /** ListUserCredsResponse userCreds. */ + public userCreds: google.firestore.admin.v1.IUserCreds[]; + + /** + * Creates a ListUserCredsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListUserCredsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListUserCredsResponse; + + /** + * Creates a plain object from a ListUserCredsResponse message. Also converts values to other types if specified. + * @param message ListUserCredsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListUserCredsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListUserCredsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListUserCredsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnableUserCredsRequest. */ + interface IEnableUserCredsRequest { + + /** EnableUserCredsRequest name */ + name?: (string|null); + } + + /** Represents an EnableUserCredsRequest. */ + class EnableUserCredsRequest implements IEnableUserCredsRequest { + + /** + * Constructs a new EnableUserCredsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IEnableUserCredsRequest); + + /** EnableUserCredsRequest name. */ + public name: string; + + /** + * Creates an EnableUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnableUserCredsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.EnableUserCredsRequest; + + /** + * Creates a plain object from an EnableUserCredsRequest message. Also converts values to other types if specified. + * @param message EnableUserCredsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.EnableUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnableUserCredsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnableUserCredsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DisableUserCredsRequest. */ + interface IDisableUserCredsRequest { + + /** DisableUserCredsRequest name */ + name?: (string|null); + } + + /** Represents a DisableUserCredsRequest. */ + class DisableUserCredsRequest implements IDisableUserCredsRequest { + + /** + * Constructs a new DisableUserCredsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDisableUserCredsRequest); + + /** DisableUserCredsRequest name. */ + public name: string; + + /** + * Creates a DisableUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DisableUserCredsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DisableUserCredsRequest; + + /** + * Creates a plain object from a DisableUserCredsRequest message. Also converts values to other types if specified. + * @param message DisableUserCredsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DisableUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DisableUserCredsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DisableUserCredsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ResetUserPasswordRequest. */ + interface IResetUserPasswordRequest { + + /** ResetUserPasswordRequest name */ + name?: (string|null); + } + + /** Represents a ResetUserPasswordRequest. */ + class ResetUserPasswordRequest implements IResetUserPasswordRequest { + + /** + * Constructs a new ResetUserPasswordRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IResetUserPasswordRequest); + + /** ResetUserPasswordRequest name. */ + public name: string; + + /** + * Creates a ResetUserPasswordRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResetUserPasswordRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ResetUserPasswordRequest; + + /** + * Creates a plain object from a ResetUserPasswordRequest message. Also converts values to other types if specified. + * @param message ResetUserPasswordRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ResetUserPasswordRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResetUserPasswordRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResetUserPasswordRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteUserCredsRequest. */ + interface IDeleteUserCredsRequest { + + /** DeleteUserCredsRequest name */ + name?: (string|null); + } + + /** Represents a DeleteUserCredsRequest. */ + class DeleteUserCredsRequest implements IDeleteUserCredsRequest { + + /** + * Constructs a new DeleteUserCredsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteUserCredsRequest); + + /** DeleteUserCredsRequest name. */ + public name: string; + + /** + * Creates a DeleteUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteUserCredsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteUserCredsRequest; + + /** + * Creates a plain object from a DeleteUserCredsRequest message. Also converts values to other types if specified. + * @param message DeleteUserCredsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteUserCredsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteUserCredsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateBackupScheduleRequest. */ + interface ICreateBackupScheduleRequest { + + /** CreateBackupScheduleRequest parent */ + parent?: (string|null); + + /** CreateBackupScheduleRequest backupSchedule */ + backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + } + + /** Represents a CreateBackupScheduleRequest. */ + class CreateBackupScheduleRequest implements ICreateBackupScheduleRequest { + + /** + * Constructs a new CreateBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateBackupScheduleRequest); + + /** CreateBackupScheduleRequest parent. */ + public parent: string; + + /** CreateBackupScheduleRequest backupSchedule. */ + public backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + + /** + * Creates a CreateBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateBackupScheduleRequest; + + /** + * Creates a plain object from a CreateBackupScheduleRequest message. Also converts values to other types if specified. + * @param message CreateBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetBackupScheduleRequest. */ + interface IGetBackupScheduleRequest { + + /** GetBackupScheduleRequest name */ + name?: (string|null); + } + + /** Represents a GetBackupScheduleRequest. */ + class GetBackupScheduleRequest implements IGetBackupScheduleRequest { + + /** + * Constructs a new GetBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetBackupScheduleRequest); + + /** GetBackupScheduleRequest name. */ + public name: string; + + /** + * Creates a GetBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetBackupScheduleRequest; + + /** + * Creates a plain object from a GetBackupScheduleRequest message. Also converts values to other types if specified. + * @param message GetBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateBackupScheduleRequest. */ + interface IUpdateBackupScheduleRequest { + + /** UpdateBackupScheduleRequest backupSchedule */ + backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + + /** UpdateBackupScheduleRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateBackupScheduleRequest. */ + class UpdateBackupScheduleRequest implements IUpdateBackupScheduleRequest { + + /** + * Constructs a new UpdateBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateBackupScheduleRequest); + + /** UpdateBackupScheduleRequest backupSchedule. */ + public backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + + /** UpdateBackupScheduleRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates an UpdateBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateBackupScheduleRequest; + + /** + * Creates a plain object from an UpdateBackupScheduleRequest message. Also converts values to other types if specified. + * @param message UpdateBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupSchedulesRequest. */ + interface IListBackupSchedulesRequest { + + /** ListBackupSchedulesRequest parent */ + parent?: (string|null); + } + + /** Represents a ListBackupSchedulesRequest. */ + class ListBackupSchedulesRequest implements IListBackupSchedulesRequest { + + /** + * Constructs a new ListBackupSchedulesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupSchedulesRequest); + + /** ListBackupSchedulesRequest parent. */ + public parent: string; + + /** + * Creates a ListBackupSchedulesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupSchedulesRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupSchedulesRequest; + + /** + * Creates a plain object from a ListBackupSchedulesRequest message. Also converts values to other types if specified. + * @param message ListBackupSchedulesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupSchedulesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupSchedulesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupSchedulesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupSchedulesResponse. */ + interface IListBackupSchedulesResponse { + + /** ListBackupSchedulesResponse backupSchedules */ + backupSchedules?: (google.firestore.admin.v1.IBackupSchedule[]|null); + } + + /** Represents a ListBackupSchedulesResponse. */ + class ListBackupSchedulesResponse implements IListBackupSchedulesResponse { + + /** + * Constructs a new ListBackupSchedulesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupSchedulesResponse); + + /** ListBackupSchedulesResponse backupSchedules. */ + public backupSchedules: google.firestore.admin.v1.IBackupSchedule[]; + + /** + * Creates a ListBackupSchedulesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupSchedulesResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupSchedulesResponse; + + /** + * Creates a plain object from a ListBackupSchedulesResponse message. Also converts values to other types if specified. + * @param message ListBackupSchedulesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupSchedulesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupSchedulesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupSchedulesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteBackupScheduleRequest. */ + interface IDeleteBackupScheduleRequest { + + /** DeleteBackupScheduleRequest name */ + name?: (string|null); + } + + /** Represents a DeleteBackupScheduleRequest. */ + class DeleteBackupScheduleRequest implements IDeleteBackupScheduleRequest { + + /** + * Constructs a new DeleteBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteBackupScheduleRequest); + + /** DeleteBackupScheduleRequest name. */ + public name: string; + + /** + * Creates a DeleteBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteBackupScheduleRequest; + + /** + * Creates a plain object from a DeleteBackupScheduleRequest message. Also converts values to other types if specified. + * @param message DeleteBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateIndexRequest. */ + interface ICreateIndexRequest { + + /** CreateIndexRequest parent */ + parent?: (string|null); + + /** CreateIndexRequest index */ + index?: (google.firestore.admin.v1.IIndex|null); + } + + /** Represents a CreateIndexRequest. */ + class CreateIndexRequest implements ICreateIndexRequest { + + /** + * Constructs a new CreateIndexRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateIndexRequest); + + /** CreateIndexRequest parent. */ + public parent: string; + + /** CreateIndexRequest index. */ + public index?: (google.firestore.admin.v1.IIndex|null); + + /** + * Creates a CreateIndexRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateIndexRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateIndexRequest; + + /** + * Creates a plain object from a CreateIndexRequest message. Also converts values to other types if specified. + * @param message CreateIndexRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateIndexRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateIndexRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListIndexesRequest. */ + interface IListIndexesRequest { + + /** ListIndexesRequest parent */ + parent?: (string|null); + + /** ListIndexesRequest filter */ + filter?: (string|null); + + /** ListIndexesRequest pageSize */ + pageSize?: (number|null); + + /** ListIndexesRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListIndexesRequest. */ + class ListIndexesRequest implements IListIndexesRequest { + + /** + * Constructs a new ListIndexesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListIndexesRequest); + + /** ListIndexesRequest parent. */ + public parent: string; + + /** ListIndexesRequest filter. */ + public filter: string; + + /** ListIndexesRequest pageSize. */ + public pageSize: number; + + /** ListIndexesRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListIndexesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListIndexesRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListIndexesRequest; + + /** + * Creates a plain object from a ListIndexesRequest message. Also converts values to other types if specified. + * @param message ListIndexesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListIndexesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListIndexesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListIndexesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListIndexesResponse. */ + interface IListIndexesResponse { + + /** ListIndexesResponse indexes */ + indexes?: (google.firestore.admin.v1.IIndex[]|null); + + /** ListIndexesResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListIndexesResponse. */ + class ListIndexesResponse implements IListIndexesResponse { + + /** + * Constructs a new ListIndexesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListIndexesResponse); + + /** ListIndexesResponse indexes. */ + public indexes: google.firestore.admin.v1.IIndex[]; + + /** ListIndexesResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListIndexesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListIndexesResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListIndexesResponse; + + /** + * Creates a plain object from a ListIndexesResponse message. Also converts values to other types if specified. + * @param message ListIndexesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListIndexesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListIndexesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListIndexesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetIndexRequest. */ + interface IGetIndexRequest { + + /** GetIndexRequest name */ + name?: (string|null); + } + + /** Represents a GetIndexRequest. */ + class GetIndexRequest implements IGetIndexRequest { + + /** + * Constructs a new GetIndexRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetIndexRequest); + + /** GetIndexRequest name. */ + public name: string; + + /** + * Creates a GetIndexRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetIndexRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetIndexRequest; + + /** + * Creates a plain object from a GetIndexRequest message. Also converts values to other types if specified. + * @param message GetIndexRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetIndexRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetIndexRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteIndexRequest. */ + interface IDeleteIndexRequest { + + /** DeleteIndexRequest name */ + name?: (string|null); + } + + /** Represents a DeleteIndexRequest. */ + class DeleteIndexRequest implements IDeleteIndexRequest { + + /** + * Constructs a new DeleteIndexRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteIndexRequest); + + /** DeleteIndexRequest name. */ + public name: string; + + /** + * Creates a DeleteIndexRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteIndexRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteIndexRequest; + + /** + * Creates a plain object from a DeleteIndexRequest message. Also converts values to other types if specified. + * @param message DeleteIndexRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteIndexRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteIndexRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateFieldRequest. */ + interface IUpdateFieldRequest { + + /** UpdateFieldRequest field */ + field?: (google.firestore.admin.v1.IField|null); + + /** UpdateFieldRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateFieldRequest. */ + class UpdateFieldRequest implements IUpdateFieldRequest { + + /** + * Constructs a new UpdateFieldRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateFieldRequest); + + /** UpdateFieldRequest field. */ + public field?: (google.firestore.admin.v1.IField|null); + + /** UpdateFieldRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates an UpdateFieldRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateFieldRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateFieldRequest; + + /** + * Creates a plain object from an UpdateFieldRequest message. Also converts values to other types if specified. + * @param message UpdateFieldRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateFieldRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateFieldRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateFieldRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetFieldRequest. */ + interface IGetFieldRequest { + + /** GetFieldRequest name */ + name?: (string|null); + } + + /** Represents a GetFieldRequest. */ + class GetFieldRequest implements IGetFieldRequest { + + /** + * Constructs a new GetFieldRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetFieldRequest); + + /** GetFieldRequest name. */ + public name: string; + + /** + * Creates a GetFieldRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetFieldRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetFieldRequest; + + /** + * Creates a plain object from a GetFieldRequest message. Also converts values to other types if specified. + * @param message GetFieldRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetFieldRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetFieldRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetFieldRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListFieldsRequest. */ + interface IListFieldsRequest { + + /** ListFieldsRequest parent */ + parent?: (string|null); + + /** ListFieldsRequest filter */ + filter?: (string|null); + + /** ListFieldsRequest pageSize */ + pageSize?: (number|null); + + /** ListFieldsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListFieldsRequest. */ + class ListFieldsRequest implements IListFieldsRequest { + + /** + * Constructs a new ListFieldsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListFieldsRequest); + + /** ListFieldsRequest parent. */ + public parent: string; + + /** ListFieldsRequest filter. */ + public filter: string; + + /** ListFieldsRequest pageSize. */ + public pageSize: number; + + /** ListFieldsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListFieldsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListFieldsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListFieldsRequest; + + /** + * Creates a plain object from a ListFieldsRequest message. Also converts values to other types if specified. + * @param message ListFieldsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListFieldsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListFieldsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListFieldsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListFieldsResponse. */ + interface IListFieldsResponse { + + /** ListFieldsResponse fields */ + fields?: (google.firestore.admin.v1.IField[]|null); + + /** ListFieldsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListFieldsResponse. */ + class ListFieldsResponse implements IListFieldsResponse { + + /** + * Constructs a new ListFieldsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListFieldsResponse); + + /** ListFieldsResponse fields. */ + public fields: google.firestore.admin.v1.IField[]; + + /** ListFieldsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListFieldsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListFieldsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListFieldsResponse; + + /** + * Creates a plain object from a ListFieldsResponse message. Also converts values to other types if specified. + * @param message ListFieldsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListFieldsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListFieldsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListFieldsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExportDocumentsRequest. */ + interface IExportDocumentsRequest { + + /** ExportDocumentsRequest name */ + name?: (string|null); + + /** ExportDocumentsRequest collectionIds */ + collectionIds?: (string[]|null); + + /** ExportDocumentsRequest outputUriPrefix */ + outputUriPrefix?: (string|null); + + /** ExportDocumentsRequest namespaceIds */ + namespaceIds?: (string[]|null); + + /** ExportDocumentsRequest snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an ExportDocumentsRequest. */ + class ExportDocumentsRequest implements IExportDocumentsRequest { + + /** + * Constructs a new ExportDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IExportDocumentsRequest); + + /** ExportDocumentsRequest name. */ + public name: string; + + /** ExportDocumentsRequest collectionIds. */ + public collectionIds: string[]; + + /** ExportDocumentsRequest outputUriPrefix. */ + public outputUriPrefix: string; + + /** ExportDocumentsRequest namespaceIds. */ + public namespaceIds: string[]; + + /** ExportDocumentsRequest snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates an ExportDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExportDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsRequest; + + /** + * Creates a plain object from an ExportDocumentsRequest message. Also converts values to other types if specified. + * @param message ExportDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ExportDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExportDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExportDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ImportDocumentsRequest. */ + interface IImportDocumentsRequest { + + /** ImportDocumentsRequest name */ + name?: (string|null); + + /** ImportDocumentsRequest collectionIds */ + collectionIds?: (string[]|null); + + /** ImportDocumentsRequest inputUriPrefix */ + inputUriPrefix?: (string|null); + + /** ImportDocumentsRequest namespaceIds */ + namespaceIds?: (string[]|null); + } + + /** Represents an ImportDocumentsRequest. */ + class ImportDocumentsRequest implements IImportDocumentsRequest { + + /** + * Constructs a new ImportDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IImportDocumentsRequest); + + /** ImportDocumentsRequest name. */ + public name: string; + + /** ImportDocumentsRequest collectionIds. */ + public collectionIds: string[]; + + /** ImportDocumentsRequest inputUriPrefix. */ + public inputUriPrefix: string; + + /** ImportDocumentsRequest namespaceIds. */ + public namespaceIds: string[]; + + /** + * Creates an ImportDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ImportDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ImportDocumentsRequest; + + /** + * Creates a plain object from an ImportDocumentsRequest message. Also converts values to other types if specified. + * @param message ImportDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ImportDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ImportDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ImportDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BulkDeleteDocumentsRequest. */ + interface IBulkDeleteDocumentsRequest { + + /** BulkDeleteDocumentsRequest name */ + name?: (string|null); + + /** BulkDeleteDocumentsRequest collectionIds */ + collectionIds?: (string[]|null); + + /** BulkDeleteDocumentsRequest namespaceIds */ + namespaceIds?: (string[]|null); + } + + /** Represents a BulkDeleteDocumentsRequest. */ + class BulkDeleteDocumentsRequest implements IBulkDeleteDocumentsRequest { + + /** + * Constructs a new BulkDeleteDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsRequest); + + /** BulkDeleteDocumentsRequest name. */ + public name: string; + + /** BulkDeleteDocumentsRequest collectionIds. */ + public collectionIds: string[]; + + /** BulkDeleteDocumentsRequest namespaceIds. */ + public namespaceIds: string[]; + + /** + * Creates a BulkDeleteDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsRequest; + + /** + * Creates a plain object from a BulkDeleteDocumentsRequest message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BulkDeleteDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BulkDeleteDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BulkDeleteDocumentsResponse. */ + interface IBulkDeleteDocumentsResponse { + } + + /** Represents a BulkDeleteDocumentsResponse. */ + class BulkDeleteDocumentsResponse implements IBulkDeleteDocumentsResponse { + + /** + * Constructs a new BulkDeleteDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsResponse); + + /** + * Creates a BulkDeleteDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsResponse; + + /** + * Creates a plain object from a BulkDeleteDocumentsResponse message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BulkDeleteDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BulkDeleteDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetBackupRequest. */ + interface IGetBackupRequest { + + /** GetBackupRequest name */ + name?: (string|null); + } + + /** Represents a GetBackupRequest. */ + class GetBackupRequest implements IGetBackupRequest { + + /** + * Constructs a new GetBackupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetBackupRequest); + + /** GetBackupRequest name. */ + public name: string; + + /** + * Creates a GetBackupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetBackupRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetBackupRequest; + + /** + * Creates a plain object from a GetBackupRequest message. Also converts values to other types if specified. + * @param message GetBackupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetBackupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetBackupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupsRequest. */ + interface IListBackupsRequest { + + /** ListBackupsRequest parent */ + parent?: (string|null); + + /** ListBackupsRequest filter */ + filter?: (string|null); + } + + /** Represents a ListBackupsRequest. */ + class ListBackupsRequest implements IListBackupsRequest { + + /** + * Constructs a new ListBackupsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupsRequest); + + /** ListBackupsRequest parent. */ + public parent: string; + + /** ListBackupsRequest filter. */ + public filter: string; + + /** + * Creates a ListBackupsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupsRequest; + + /** + * Creates a plain object from a ListBackupsRequest message. Also converts values to other types if specified. + * @param message ListBackupsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupsResponse. */ + interface IListBackupsResponse { + + /** ListBackupsResponse backups */ + backups?: (google.firestore.admin.v1.IBackup[]|null); + + /** ListBackupsResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListBackupsResponse. */ + class ListBackupsResponse implements IListBackupsResponse { + + /** + * Constructs a new ListBackupsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupsResponse); + + /** ListBackupsResponse backups. */ + public backups: google.firestore.admin.v1.IBackup[]; + + /** ListBackupsResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a ListBackupsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupsResponse; + + /** + * Creates a plain object from a ListBackupsResponse message. Also converts values to other types if specified. + * @param message ListBackupsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteBackupRequest. */ + interface IDeleteBackupRequest { + + /** DeleteBackupRequest name */ + name?: (string|null); + } + + /** Represents a DeleteBackupRequest. */ + class DeleteBackupRequest implements IDeleteBackupRequest { + + /** + * Constructs a new DeleteBackupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteBackupRequest); + + /** DeleteBackupRequest name. */ + public name: string; + + /** + * Creates a DeleteBackupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteBackupRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteBackupRequest; + + /** + * Creates a plain object from a DeleteBackupRequest message. Also converts values to other types if specified. + * @param message DeleteBackupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteBackupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteBackupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RestoreDatabaseRequest. */ + interface IRestoreDatabaseRequest { + + /** RestoreDatabaseRequest parent */ + parent?: (string|null); + + /** RestoreDatabaseRequest databaseId */ + databaseId?: (string|null); + + /** RestoreDatabaseRequest backup */ + backup?: (string|null); + + /** RestoreDatabaseRequest encryptionConfig */ + encryptionConfig?: (google.firestore.admin.v1.Database.IEncryptionConfig|null); + + /** RestoreDatabaseRequest tags */ + tags?: ({ [k: string]: string }|null); + } + + /** Represents a RestoreDatabaseRequest. */ + class RestoreDatabaseRequest implements IRestoreDatabaseRequest { + + /** + * Constructs a new RestoreDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IRestoreDatabaseRequest); + + /** RestoreDatabaseRequest parent. */ + public parent: string; + + /** RestoreDatabaseRequest databaseId. */ + public databaseId: string; + + /** RestoreDatabaseRequest backup. */ + public backup: string; + + /** RestoreDatabaseRequest encryptionConfig. */ + public encryptionConfig?: (google.firestore.admin.v1.Database.IEncryptionConfig|null); + + /** RestoreDatabaseRequest tags. */ + public tags: { [k: string]: string }; + + /** + * Creates a RestoreDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RestoreDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.RestoreDatabaseRequest; + + /** + * Creates a plain object from a RestoreDatabaseRequest message. Also converts values to other types if specified. + * @param message RestoreDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.RestoreDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RestoreDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RestoreDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CloneDatabaseRequest. */ + interface ICloneDatabaseRequest { + + /** CloneDatabaseRequest parent */ + parent?: (string|null); + + /** CloneDatabaseRequest databaseId */ + databaseId?: (string|null); + + /** CloneDatabaseRequest pitrSnapshot */ + pitrSnapshot?: (google.firestore.admin.v1.IPitrSnapshot|null); + + /** CloneDatabaseRequest encryptionConfig */ + encryptionConfig?: (google.firestore.admin.v1.Database.IEncryptionConfig|null); + + /** CloneDatabaseRequest tags */ + tags?: ({ [k: string]: string }|null); + } + + /** Represents a CloneDatabaseRequest. */ + class CloneDatabaseRequest implements ICloneDatabaseRequest { + + /** + * Constructs a new CloneDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICloneDatabaseRequest); + + /** CloneDatabaseRequest parent. */ + public parent: string; + + /** CloneDatabaseRequest databaseId. */ + public databaseId: string; + + /** CloneDatabaseRequest pitrSnapshot. */ + public pitrSnapshot?: (google.firestore.admin.v1.IPitrSnapshot|null); + + /** CloneDatabaseRequest encryptionConfig. */ + public encryptionConfig?: (google.firestore.admin.v1.Database.IEncryptionConfig|null); + + /** CloneDatabaseRequest tags. */ + public tags: { [k: string]: string }; + + /** + * Creates a CloneDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CloneDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CloneDatabaseRequest; + + /** + * Creates a plain object from a CloneDatabaseRequest message. Also converts values to other types if specified. + * @param message CloneDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CloneDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CloneDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CloneDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an IndexOperationMetadata. */ + interface IIndexOperationMetadata { + + /** IndexOperationMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata index */ + index?: (string|null); + + /** IndexOperationMetadata state */ + state?: (google.firestore.admin.v1.OperationState|null); + + /** IndexOperationMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** IndexOperationMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + } + + /** Represents an IndexOperationMetadata. */ + class IndexOperationMetadata implements IIndexOperationMetadata { + + /** + * Constructs a new IndexOperationMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IIndexOperationMetadata); + + /** IndexOperationMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata index. */ + public index: string; + + /** IndexOperationMetadata state. */ + public state: google.firestore.admin.v1.OperationState; + + /** IndexOperationMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** IndexOperationMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** + * Creates an IndexOperationMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexOperationMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.IndexOperationMetadata; + + /** + * Creates a plain object from an IndexOperationMetadata message. Also converts values to other types if specified. + * @param message IndexOperationMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.IndexOperationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexOperationMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexOperationMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldOperationMetadata. */ + interface IFieldOperationMetadata { + + /** FieldOperationMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata field */ + field?: (string|null); + + /** FieldOperationMetadata indexConfigDeltas */ + indexConfigDeltas?: (google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta[]|null); + + /** FieldOperationMetadata state */ + state?: (google.firestore.admin.v1.OperationState|null); + + /** FieldOperationMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata ttlConfigDelta */ + ttlConfigDelta?: (google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta|null); + } + + /** Represents a FieldOperationMetadata. */ + class FieldOperationMetadata implements IFieldOperationMetadata { + + /** + * Constructs a new FieldOperationMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IFieldOperationMetadata); + + /** FieldOperationMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata field. */ + public field: string; + + /** FieldOperationMetadata indexConfigDeltas. */ + public indexConfigDeltas: google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta[]; + + /** FieldOperationMetadata state. */ + public state: google.firestore.admin.v1.OperationState; + + /** FieldOperationMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata ttlConfigDelta. */ + public ttlConfigDelta?: (google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta|null); + + /** + * Creates a FieldOperationMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOperationMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata; + + /** + * Creates a plain object from a FieldOperationMetadata message. Also converts values to other types if specified. + * @param message FieldOperationMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOperationMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOperationMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldOperationMetadata { + + /** Properties of an IndexConfigDelta. */ + interface IIndexConfigDelta { + + /** IndexConfigDelta changeType */ + changeType?: (google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType|null); + + /** IndexConfigDelta index */ + index?: (google.firestore.admin.v1.IIndex|null); + } + + /** Represents an IndexConfigDelta. */ + class IndexConfigDelta implements IIndexConfigDelta { + + /** + * Constructs a new IndexConfigDelta. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta); + + /** IndexConfigDelta changeType. */ + public changeType: google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType; + + /** IndexConfigDelta index. */ + public index?: (google.firestore.admin.v1.IIndex|null); + + /** + * Creates an IndexConfigDelta message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexConfigDelta + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta; + + /** + * Creates a plain object from an IndexConfigDelta message. Also converts values to other types if specified. + * @param message IndexConfigDelta + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexConfigDelta to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexConfigDelta + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace IndexConfigDelta { + + /** ChangeType enum. */ + type ChangeType = + "CHANGE_TYPE_UNSPECIFIED"| "ADD"| "REMOVE"; + } + + /** Properties of a TtlConfigDelta. */ + interface ITtlConfigDelta { + + /** TtlConfigDelta changeType */ + changeType?: (google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.ChangeType|null); + } + + /** Represents a TtlConfigDelta. */ + class TtlConfigDelta implements ITtlConfigDelta { + + /** + * Constructs a new TtlConfigDelta. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta); + + /** TtlConfigDelta changeType. */ + public changeType: google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.ChangeType; + + /** + * Creates a TtlConfigDelta message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TtlConfigDelta + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta; + + /** + * Creates a plain object from a TtlConfigDelta message. Also converts values to other types if specified. + * @param message TtlConfigDelta + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TtlConfigDelta to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TtlConfigDelta + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TtlConfigDelta { + + /** ChangeType enum. */ + type ChangeType = + "CHANGE_TYPE_UNSPECIFIED"| "ADD"| "REMOVE"; + } + } + + /** Properties of an ExportDocumentsMetadata. */ + interface IExportDocumentsMetadata { + + /** ExportDocumentsMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** ExportDocumentsMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata collectionIds */ + collectionIds?: (string[]|null); + + /** ExportDocumentsMetadata outputUriPrefix */ + outputUriPrefix?: (string|null); + + /** ExportDocumentsMetadata namespaceIds */ + namespaceIds?: (string[]|null); + + /** ExportDocumentsMetadata snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an ExportDocumentsMetadata. */ + class ExportDocumentsMetadata implements IExportDocumentsMetadata { + + /** + * Constructs a new ExportDocumentsMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IExportDocumentsMetadata); + + /** ExportDocumentsMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** ExportDocumentsMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata collectionIds. */ + public collectionIds: string[]; + + /** ExportDocumentsMetadata outputUriPrefix. */ + public outputUriPrefix: string; + + /** ExportDocumentsMetadata namespaceIds. */ + public namespaceIds: string[]; + + /** ExportDocumentsMetadata snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates an ExportDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExportDocumentsMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsMetadata; + + /** + * Creates a plain object from an ExportDocumentsMetadata message. Also converts values to other types if specified. + * @param message ExportDocumentsMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ExportDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExportDocumentsMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExportDocumentsMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ImportDocumentsMetadata. */ + interface IImportDocumentsMetadata { + + /** ImportDocumentsMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** ImportDocumentsMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata collectionIds */ + collectionIds?: (string[]|null); + + /** ImportDocumentsMetadata inputUriPrefix */ + inputUriPrefix?: (string|null); + + /** ImportDocumentsMetadata namespaceIds */ + namespaceIds?: (string[]|null); + } + + /** Represents an ImportDocumentsMetadata. */ + class ImportDocumentsMetadata implements IImportDocumentsMetadata { + + /** + * Constructs a new ImportDocumentsMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IImportDocumentsMetadata); + + /** ImportDocumentsMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** ImportDocumentsMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata collectionIds. */ + public collectionIds: string[]; + + /** ImportDocumentsMetadata inputUriPrefix. */ + public inputUriPrefix: string; + + /** ImportDocumentsMetadata namespaceIds. */ + public namespaceIds: string[]; + + /** + * Creates an ImportDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ImportDocumentsMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ImportDocumentsMetadata; + + /** + * Creates a plain object from an ImportDocumentsMetadata message. Also converts values to other types if specified. + * @param message ImportDocumentsMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ImportDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ImportDocumentsMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ImportDocumentsMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BulkDeleteDocumentsMetadata. */ + interface IBulkDeleteDocumentsMetadata { + + /** BulkDeleteDocumentsMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** BulkDeleteDocumentsMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata collectionIds */ + collectionIds?: (string[]|null); + + /** BulkDeleteDocumentsMetadata namespaceIds */ + namespaceIds?: (string[]|null); + + /** BulkDeleteDocumentsMetadata snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BulkDeleteDocumentsMetadata. */ + class BulkDeleteDocumentsMetadata implements IBulkDeleteDocumentsMetadata { + + /** + * Constructs a new BulkDeleteDocumentsMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsMetadata); + + /** BulkDeleteDocumentsMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** BulkDeleteDocumentsMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata collectionIds. */ + public collectionIds: string[]; + + /** BulkDeleteDocumentsMetadata namespaceIds. */ + public namespaceIds: string[]; + + /** BulkDeleteDocumentsMetadata snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a BulkDeleteDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsMetadata; + + /** + * Creates a plain object from a BulkDeleteDocumentsMetadata message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BulkDeleteDocumentsMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BulkDeleteDocumentsMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExportDocumentsResponse. */ + interface IExportDocumentsResponse { + + /** ExportDocumentsResponse outputUriPrefix */ + outputUriPrefix?: (string|null); + } + + /** Represents an ExportDocumentsResponse. */ + class ExportDocumentsResponse implements IExportDocumentsResponse { + + /** + * Constructs a new ExportDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IExportDocumentsResponse); + + /** ExportDocumentsResponse outputUriPrefix. */ + public outputUriPrefix: string; + + /** + * Creates an ExportDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExportDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsResponse; + + /** + * Creates a plain object from an ExportDocumentsResponse message. Also converts values to other types if specified. + * @param message ExportDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ExportDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExportDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExportDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RestoreDatabaseMetadata. */ + interface IRestoreDatabaseMetadata { + + /** RestoreDatabaseMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** RestoreDatabaseMetadata database */ + database?: (string|null); + + /** RestoreDatabaseMetadata backup */ + backup?: (string|null); + + /** RestoreDatabaseMetadata progressPercentage */ + progressPercentage?: (google.firestore.admin.v1.IProgress|null); + } + + /** Represents a RestoreDatabaseMetadata. */ + class RestoreDatabaseMetadata implements IRestoreDatabaseMetadata { + + /** + * Constructs a new RestoreDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IRestoreDatabaseMetadata); + + /** RestoreDatabaseMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** RestoreDatabaseMetadata database. */ + public database: string; + + /** RestoreDatabaseMetadata backup. */ + public backup: string; + + /** RestoreDatabaseMetadata progressPercentage. */ + public progressPercentage?: (google.firestore.admin.v1.IProgress|null); + + /** + * Creates a RestoreDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RestoreDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.RestoreDatabaseMetadata; + + /** + * Creates a plain object from a RestoreDatabaseMetadata message. Also converts values to other types if specified. + * @param message RestoreDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.RestoreDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RestoreDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RestoreDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CloneDatabaseMetadata. */ + interface ICloneDatabaseMetadata { + + /** CloneDatabaseMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** CloneDatabaseMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** CloneDatabaseMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** CloneDatabaseMetadata database */ + database?: (string|null); + + /** CloneDatabaseMetadata pitrSnapshot */ + pitrSnapshot?: (google.firestore.admin.v1.IPitrSnapshot|null); + + /** CloneDatabaseMetadata progressPercentage */ + progressPercentage?: (google.firestore.admin.v1.IProgress|null); + } + + /** Represents a CloneDatabaseMetadata. */ + class CloneDatabaseMetadata implements ICloneDatabaseMetadata { + + /** + * Constructs a new CloneDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICloneDatabaseMetadata); + + /** CloneDatabaseMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** CloneDatabaseMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** CloneDatabaseMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** CloneDatabaseMetadata database. */ + public database: string; + + /** CloneDatabaseMetadata pitrSnapshot. */ + public pitrSnapshot?: (google.firestore.admin.v1.IPitrSnapshot|null); + + /** CloneDatabaseMetadata progressPercentage. */ + public progressPercentage?: (google.firestore.admin.v1.IProgress|null); + + /** + * Creates a CloneDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CloneDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CloneDatabaseMetadata; + + /** + * Creates a plain object from a CloneDatabaseMetadata message. Also converts values to other types if specified. + * @param message CloneDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CloneDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CloneDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CloneDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Progress. */ + interface IProgress { + + /** Progress estimatedWork */ + estimatedWork?: (number|string|null); + + /** Progress completedWork */ + completedWork?: (number|string|null); + } + + /** Represents a Progress. */ + class Progress implements IProgress { + + /** + * Constructs a new Progress. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IProgress); + + /** Progress estimatedWork. */ + public estimatedWork: (number|string); + + /** Progress completedWork. */ + public completedWork: (number|string); + + /** + * Creates a Progress message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Progress + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Progress; + + /** + * Creates a plain object from a Progress message. Also converts values to other types if specified. + * @param message Progress + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Progress, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Progress to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Progress + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** OperationState enum. */ + type OperationState = + "OPERATION_STATE_UNSPECIFIED"| "INITIALIZING"| "PROCESSING"| "CANCELLING"| "FINALIZING"| "SUCCESSFUL"| "FAILED"| "CANCELLED"; + + /** Properties of a PitrSnapshot. */ + interface IPitrSnapshot { + + /** PitrSnapshot database */ + database?: (string|null); + + /** PitrSnapshot databaseUid */ + databaseUid?: (Uint8Array|null); + + /** PitrSnapshot snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a PitrSnapshot. */ + class PitrSnapshot implements IPitrSnapshot { + + /** + * Constructs a new PitrSnapshot. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IPitrSnapshot); + + /** PitrSnapshot database. */ + public database: string; + + /** PitrSnapshot databaseUid. */ + public databaseUid: Uint8Array; + + /** PitrSnapshot snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a PitrSnapshot message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PitrSnapshot + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.PitrSnapshot; + + /** + * Creates a plain object from a PitrSnapshot message. Also converts values to other types if specified. + * @param message PitrSnapshot + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.PitrSnapshot, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PitrSnapshot to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PitrSnapshot + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BackupSchedule. */ + interface IBackupSchedule { + + /** BackupSchedule name */ + name?: (string|null); + + /** BackupSchedule createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule retention */ + retention?: (google.protobuf.IDuration|null); + + /** BackupSchedule dailyRecurrence */ + dailyRecurrence?: (google.firestore.admin.v1.IDailyRecurrence|null); + + /** BackupSchedule weeklyRecurrence */ + weeklyRecurrence?: (google.firestore.admin.v1.IWeeklyRecurrence|null); + } + + /** Represents a BackupSchedule. */ + class BackupSchedule implements IBackupSchedule { + + /** + * Constructs a new BackupSchedule. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBackupSchedule); + + /** BackupSchedule name. */ + public name: string; + + /** BackupSchedule createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule retention. */ + public retention?: (google.protobuf.IDuration|null); + + /** BackupSchedule dailyRecurrence. */ + public dailyRecurrence?: (google.firestore.admin.v1.IDailyRecurrence|null); + + /** BackupSchedule weeklyRecurrence. */ + public weeklyRecurrence?: (google.firestore.admin.v1.IWeeklyRecurrence|null); + + /** BackupSchedule recurrence. */ + public recurrence?: ("dailyRecurrence"|"weeklyRecurrence"); + + /** + * Creates a BackupSchedule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BackupSchedule + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BackupSchedule; + + /** + * Creates a plain object from a BackupSchedule message. Also converts values to other types if specified. + * @param message BackupSchedule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BackupSchedule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BackupSchedule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BackupSchedule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DailyRecurrence. */ + interface IDailyRecurrence { + } + + /** Represents a DailyRecurrence. */ + class DailyRecurrence implements IDailyRecurrence { + + /** + * Constructs a new DailyRecurrence. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDailyRecurrence); + + /** + * Creates a DailyRecurrence message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DailyRecurrence + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DailyRecurrence; + + /** + * Creates a plain object from a DailyRecurrence message. Also converts values to other types if specified. + * @param message DailyRecurrence + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DailyRecurrence, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DailyRecurrence to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DailyRecurrence + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WeeklyRecurrence. */ + interface IWeeklyRecurrence { + + /** WeeklyRecurrence day */ + day?: (google.type.DayOfWeek|null); + } + + /** Represents a WeeklyRecurrence. */ + class WeeklyRecurrence implements IWeeklyRecurrence { + + /** + * Constructs a new WeeklyRecurrence. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IWeeklyRecurrence); + + /** WeeklyRecurrence day. */ + public day: google.type.DayOfWeek; + + /** + * Creates a WeeklyRecurrence message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WeeklyRecurrence + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.WeeklyRecurrence; + + /** + * Creates a plain object from a WeeklyRecurrence message. Also converts values to other types if specified. + * @param message WeeklyRecurrence + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.WeeklyRecurrence, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WeeklyRecurrence to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WeeklyRecurrence + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UserCreds. */ + interface IUserCreds { + + /** UserCreds name */ + name?: (string|null); + + /** UserCreds createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** UserCreds updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** UserCreds state */ + state?: (google.firestore.admin.v1.UserCreds.State|null); + + /** UserCreds securePassword */ + securePassword?: (string|null); + + /** UserCreds resourceIdentity */ + resourceIdentity?: (google.firestore.admin.v1.UserCreds.IResourceIdentity|null); + } + + /** Represents a UserCreds. */ + class UserCreds implements IUserCreds { + + /** + * Constructs a new UserCreds. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUserCreds); + + /** UserCreds name. */ + public name: string; + + /** UserCreds createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** UserCreds updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** UserCreds state. */ + public state: google.firestore.admin.v1.UserCreds.State; + + /** UserCreds securePassword. */ + public securePassword: string; + + /** UserCreds resourceIdentity. */ + public resourceIdentity?: (google.firestore.admin.v1.UserCreds.IResourceIdentity|null); + + /** UserCreds UserCredsIdentity. */ + public UserCredsIdentity?: "resourceIdentity"; + + /** + * Creates a UserCreds message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UserCreds + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UserCreds; + + /** + * Creates a plain object from a UserCreds message. Also converts values to other types if specified. + * @param message UserCreds + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UserCreds, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UserCreds to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UserCreds + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UserCreds { + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "ENABLED"| "DISABLED"; + + /** Properties of a ResourceIdentity. */ + interface IResourceIdentity { + + /** ResourceIdentity principal */ + principal?: (string|null); + } + + /** Represents a ResourceIdentity. */ + class ResourceIdentity implements IResourceIdentity { + + /** + * Constructs a new ResourceIdentity. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.UserCreds.IResourceIdentity); + + /** ResourceIdentity principal. */ + public principal: string; + + /** + * Creates a ResourceIdentity message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceIdentity + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UserCreds.ResourceIdentity; + + /** + * Creates a plain object from a ResourceIdentity message. Also converts values to other types if specified. + * @param message ResourceIdentity + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UserCreds.ResourceIdentity, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceIdentity to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceIdentity + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a LocationMetadata. */ + interface ILocationMetadata { + } + + /** Represents a LocationMetadata. */ + class LocationMetadata implements ILocationMetadata { + + /** + * Constructs a new LocationMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ILocationMetadata); + + /** + * Creates a LocationMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LocationMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.LocationMetadata; + + /** + * Creates a plain object from a LocationMetadata message. Also converts values to other types if specified. + * @param message LocationMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.LocationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LocationMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LocationMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + } + + /** Namespace api. */ + namespace api { + + /** FieldBehavior enum. */ + type FieldBehavior = + "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; + + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { + + /** ResourceDescriptor type */ + type?: (string|null); + + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); + + /** ResourceDescriptor nameField */ + nameField?: (string|null); + + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|null); + + /** ResourceDescriptor plural */ + plural?: (string|null); + + /** ResourceDescriptor singular */ + singular?: (string|null); + + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } + + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { + + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); + + /** ResourceDescriptor type. */ + public type: string; + + /** ResourceDescriptor pattern. */ + public pattern: string[]; + + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: google.api.ResourceDescriptor.History; + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ResourceDescriptor { + + /** History enum. */ + type History = + "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; + + /** Style enum. */ + type Style = + "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + } + + /** Properties of a ResourceReference. */ + interface IResourceReference { + + /** ResourceReference type */ + type?: (string|null); + + /** ResourceReference childType */ + childType?: (string|null); + } + + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { + + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); + + /** ResourceReference type. */ + public type: string; + + /** ResourceReference childType. */ + public childType: string; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { + + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); + + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + } + + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { + + /** + * Constructs a new CommonLanguageSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICommonLanguageSettings); + + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; + + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; + + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommonLanguageSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { + + /** ClientLibrarySettings version */ + version?: (string|null); + + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|null); + + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); + + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } + + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { + + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); + + /** ClientLibrarySettings version. */ + public version: string; + + /** ClientLibrarySettings launchStage. */ + public launchStage: google.api.LaunchStage; + + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; + + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Publishing. */ + interface IPublishing { + + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); + + /** Publishing newIssueUri */ + newIssueUri?: (string|null); + + /** Publishing documentationUri */ + documentationUri?: (string|null); + + /** Publishing apiShortName */ + apiShortName?: (string|null); + + /** Publishing githubLabel */ + githubLabel?: (string|null); + + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); + + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); + + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|null); + + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); + + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); + + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } + + /** Represents a Publishing. */ + class Publishing implements IPublishing { + + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); + + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; + + /** Publishing newIssueUri. */ + public newIssueUri: string; + + /** Publishing documentationUri. */ + public documentationUri: string; + + /** Publishing apiShortName. */ + public apiShortName: string; + + /** Publishing githubLabel. */ + public githubLabel: string; + + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; + + /** Publishing docTagPrefix. */ + public docTagPrefix: string; + + /** Publishing organization. */ + public organization: google.api.ClientLibraryOrganization; + + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; + + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; + + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a JavaSettings. */ + interface IJavaSettings { + + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); + + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); + + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { + + /** + * Constructs a new JavaSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IJavaSettings); + + /** JavaSettings libraryPackage. */ + public libraryPackage: string; + + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; + + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns JavaSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this JavaSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CppSettings. */ + interface ICppSettings { + + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { + + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); + + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PhpSettings. */ + interface IPhpSettings { + + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { + + /** + * Constructs a new PhpSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPhpSettings); + + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PythonSettings. */ + interface IPythonSettings { + + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + } + + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { + + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); + + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PythonSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PythonSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PythonSettings { + + /** Properties of an ExperimentalFeatures. */ + interface IExperimentalFeatures { + + /** ExperimentalFeatures restAsyncIoEnabled */ + restAsyncIoEnabled?: (boolean|null); + + /** ExperimentalFeatures protobufPythonicTypesEnabled */ + protobufPythonicTypesEnabled?: (boolean|null); + + /** ExperimentalFeatures unversionedPackageDisabled */ + unversionedPackageDisabled?: (boolean|null); + } + + /** Represents an ExperimentalFeatures. */ + class ExperimentalFeatures implements IExperimentalFeatures { + + /** + * Constructs a new ExperimentalFeatures. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.PythonSettings.IExperimentalFeatures); + + /** ExperimentalFeatures restAsyncIoEnabled. */ + public restAsyncIoEnabled: boolean; + + /** ExperimentalFeatures protobufPythonicTypesEnabled. */ + public protobufPythonicTypesEnabled: boolean; + + /** ExperimentalFeatures unversionedPackageDisabled. */ + public unversionedPackageDisabled: boolean; + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExperimentalFeatures + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @param message ExperimentalFeatures + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings.ExperimentalFeatures, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExperimentalFeatures + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a NodeSettings. */ + interface INodeSettings { + + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { + + /** + * Constructs a new NodeSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.INodeSettings); + + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NodeSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NodeSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { + + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); + + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); + + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); + + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); + } + + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { + + /** + * Constructs a new DotnetSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IDotnetSettings); + + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; + + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; + + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; + + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DotnetSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DotnetSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RubySettings. */ + interface IRubySettings { + + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { + + /** + * Constructs a new RubySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRubySettings); + + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GoSettings. */ + interface IGoSettings { + + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + } + + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { + + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); + + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodSettings. */ + interface IMethodSettings { + + /** MethodSettings selector */ + selector?: (string|null); + + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); + } + + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { + + /** + * Constructs a new MethodSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IMethodSettings); + + /** MethodSettings selector. */ + public selector: string; + + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodSettings { + + /** Properties of a LongRunning. */ + interface ILongRunning { + + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); + + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); + } + + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { + + /** + * Constructs a new LongRunning. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.MethodSettings.ILongRunning); + + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; + + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LongRunning + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LongRunning to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LongRunning + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** ClientLibraryOrganization enum. */ + type ClientLibraryOrganization = + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; + + /** ClientLibraryDestination enum. */ + type ClientLibraryDestination = + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; + + /** Properties of a SelectiveGapicGeneration. */ + interface ISelectiveGapicGeneration { + + /** SelectiveGapicGeneration methods */ + methods?: (string[]|null); + + /** SelectiveGapicGeneration generateOmittedAsInternal */ + generateOmittedAsInternal?: (boolean|null); + } + + /** Represents a SelectiveGapicGeneration. */ + class SelectiveGapicGeneration implements ISelectiveGapicGeneration { + + /** + * Constructs a new SelectiveGapicGeneration. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ISelectiveGapicGeneration); + + /** SelectiveGapicGeneration methods. */ + public methods: string[]; + + /** SelectiveGapicGeneration generateOmittedAsInternal. */ + public generateOmittedAsInternal: boolean; + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SelectiveGapicGeneration + */ + public static fromObject(object: { [k: string]: any }): google.api.SelectiveGapicGeneration; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @param message SelectiveGapicGeneration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.SelectiveGapicGeneration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; + + /** Properties of a RoutingRule. */ + interface IRoutingRule { + + /** RoutingRule routingParameters */ + routingParameters?: (google.api.IRoutingParameter[]|null); + } + + /** Represents a RoutingRule. */ + class RoutingRule implements IRoutingRule { + + /** + * Constructs a new RoutingRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRoutingRule); + + /** RoutingRule routingParameters. */ + public routingParameters: google.api.IRoutingParameter[]; + + /** + * Creates a RoutingRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingRule + */ + public static fromObject(object: { [k: string]: any }): google.api.RoutingRule; + + /** + * Creates a plain object from a RoutingRule message. Also converts values to other types if specified. + * @param message RoutingRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RoutingRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RoutingParameter. */ + interface IRoutingParameter { + + /** RoutingParameter field */ + field?: (string|null); + + /** RoutingParameter pathTemplate */ + pathTemplate?: (string|null); + } + + /** Represents a RoutingParameter. */ + class RoutingParameter implements IRoutingParameter { + + /** + * Constructs a new RoutingParameter. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRoutingParameter); + + /** RoutingParameter field. */ + public field: string; + + /** RoutingParameter pathTemplate. */ + public pathTemplate: string; + + /** + * Creates a RoutingParameter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingParameter + */ + public static fromObject(object: { [k: string]: any }): google.api.RoutingParameter; + + /** + * Creates a plain object from a RoutingParameter message. Also converts values to other types if specified. + * @param message RoutingParameter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RoutingParameter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingParameter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingParameter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); + + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Edition enum. */ + type Edition = + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; + + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { + + /** FileDescriptorProto name */ + name?: (string|null); + + /** FileDescriptorProto package */ + "package"?: (string|null); + + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); + + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); + + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); + + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); + + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); + + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax */ + syntax?: (string|null); + + /** FileDescriptorProto edition */ + edition?: (google.protobuf.Edition|null); + } + + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { + + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); + + /** FileDescriptorProto name. */ + public name: string; + + /** FileDescriptorProto package. */ + public package: string; + + /** FileDescriptorProto dependency. */ + public dependency: string[]; + + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; + + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; + + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; + + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; + + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax. */ + public syntax: string; + + /** FileDescriptorProto edition. */ + public edition: google.protobuf.Edition; + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { + + /** DescriptorProto name */ + name?: (string|null); + + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { + + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); + + /** DescriptorProto name. */ + public name: string; + + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; + + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + + /** DescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DescriptorProto { + + /** Properties of an ExtensionRange. */ + interface IExtensionRange { + + /** ExtensionRange start */ + start?: (number|null); + + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); + } + + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { + + /** + * Constructs a new ExtensionRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + + /** ExtensionRange start. */ + public start: number; + + /** ExtensionRange end. */ + public end: number; + + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReservedRange. */ + interface IReservedRange { + + /** ReservedRange start */ + start?: (number|null); + + /** ReservedRange end */ + end?: (number|null); + } + + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { + + /** + * Constructs a new ReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + + /** ReservedRange start. */ + public start: number; + + /** ReservedRange end. */ + public end: number; + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ExtensionRangeOptions declaration */ + declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); + + /** ExtensionRangeOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification */ + verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** ExtensionRangeOptions declaration. */ + public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; + + /** ExtensionRangeOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification. */ + public verification: google.protobuf.ExtensionRangeOptions.VerificationState; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExtensionRangeOptions { + + /** Properties of a Declaration. */ + interface IDeclaration { + + /** Declaration number */ + number?: (number|null); + + /** Declaration fullName */ + fullName?: (string|null); + + /** Declaration type */ + type?: (string|null); + + /** Declaration reserved */ + reserved?: (boolean|null); + + /** Declaration repeated */ + repeated?: (boolean|null); + } + + /** Represents a Declaration. */ + class Declaration implements IDeclaration { + + /** + * Constructs a new Declaration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); + + /** Declaration number. */ + public number: number; + + /** Declaration fullName. */ + public fullName: string; + + /** Declaration type. */ + public type: string; + + /** Declaration reserved. */ + public reserved: boolean; + + /** Declaration repeated. */ + public repeated: boolean; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Declaration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @param message Declaration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Declaration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Declaration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** VerificationState enum. */ + type VerificationState = + "DECLARATION"| "UNVERIFIED"; + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; + + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldDescriptorProto { + + /** Type enum. */ + type Type = + "TYPE_DOUBLE"| "TYPE_FLOAT"| "TYPE_INT64"| "TYPE_UINT64"| "TYPE_INT32"| "TYPE_FIXED64"| "TYPE_FIXED32"| "TYPE_BOOL"| "TYPE_STRING"| "TYPE_GROUP"| "TYPE_MESSAGE"| "TYPE_BYTES"| "TYPE_UINT32"| "TYPE_ENUM"| "TYPE_SFIXED32"| "TYPE_SFIXED64"| "TYPE_SINT32"| "TYPE_SINT64"; + + /** Label enum. */ + type Label = + "LABEL_OPTIONAL"| "LABEL_REPEATED"| "LABEL_REQUIRED"; + } + + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { + + /** OneofDescriptorProto name */ + name?: (string|null); + + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } + + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { + + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); + + /** OneofDescriptorProto name. */ + public name: string; + + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { + + /** EnumDescriptorProto name */ + name?: (string|null); + + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { + + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); + + /** EnumDescriptorProto name. */ + public name: string; + + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; + + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { + + /** EnumValueDescriptorProto name */ + name?: (string|null); + + /** EnumValueDescriptorProto number */ + number?: (number|null); + + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } + + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + + /** EnumValueDescriptorProto name. */ + public name: string; + + /** EnumValueDescriptorProto number. */ + public number: number; + + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { + + /** ServiceDescriptorProto name */ + name?: (string|null); + + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); + + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } + + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { + + /** FileOptions javaPackage */ + javaPackage?: (string|null); + + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); + + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); + + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); + + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); + + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + + /** FileOptions goPackage */ + goPackage?: (string|null); + + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); + + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); + + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); + + /** FileOptions deprecated */ + deprecated?: (boolean|null); + + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); + + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); + + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); + + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); + } + + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { + + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); + + /** FileOptions javaPackage. */ + public javaPackage: string; + + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; + + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; + + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; + + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; + + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + + /** FileOptions goPackage. */ + public goPackage: string; + + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; + + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; + + /** FileOptions deprecated. */ + public deprecated: boolean; + + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; + + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; + + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + type OptimizeMode = + "SPEED"| "CODE_SIZE"| "LITE_RUNTIME"; + } + + /** Properties of a MessageOptions. */ + interface IMessageOptions { + + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); + + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); + + /** MessageOptions deprecated */ + deprecated?: (boolean|null); + + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); + + /** MessageOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** MessageOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MessageOptions .google.api.resource */ + ".google.api.resource"?: (google.api.IResourceDescriptor|null); + } + + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { + + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); + + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; + + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; + + /** MessageOptions deprecated. */ + public deprecated: boolean; + + /** MessageOptions mapEntry. */ + public mapEntry: boolean; + + /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** MessageOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MessageOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldOptions. */ + interface IFieldOptions { + + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); + + /** FieldOptions packed */ + packed?: (boolean|null); + + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); + + /** FieldOptions lazy */ + lazy?: (boolean|null); + + /** FieldOptions unverifiedLazy */ + unverifiedLazy?: (boolean|null); + + /** FieldOptions deprecated */ + deprecated?: (boolean|null); + + /** FieldOptions weak */ + weak?: (boolean|null); + + /** FieldOptions debugRedact */ + debugRedact?: (boolean|null); + + /** FieldOptions retention */ + retention?: (google.protobuf.FieldOptions.OptionRetention|null); + + /** FieldOptions targets */ + targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); + + /** FieldOptions editionDefaults */ + editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); + + /** FieldOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FieldOptions .google.api.fieldBehavior */ + ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); + + /** FieldOptions .google.api.resourceReference */ + ".google.api.resourceReference"?: (google.api.IResourceReference|null); + } + + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { + + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); + + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; + + /** FieldOptions packed. */ + public packed: boolean; + + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; + + /** FieldOptions lazy. */ + public lazy: boolean; + + /** FieldOptions unverifiedLazy. */ + public unverifiedLazy: boolean; + + /** FieldOptions deprecated. */ + public deprecated: boolean; + + /** FieldOptions weak. */ + public weak: boolean; + + /** FieldOptions debugRedact. */ + public debugRedact: boolean; + + /** FieldOptions retention. */ + public retention: google.protobuf.FieldOptions.OptionRetention; + + /** FieldOptions targets. */ + public targets: google.protobuf.FieldOptions.OptionTargetType[]; + + /** FieldOptions editionDefaults. */ + public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; + + /** FieldOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldOptions { + + /** CType enum. */ + type CType = + "STRING"| "CORD"| "STRING_PIECE"; + + /** JSType enum. */ + type JSType = + "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; + + /** OptionRetention enum. */ + type OptionRetention = + "RETENTION_UNKNOWN"| "RETENTION_RUNTIME"| "RETENTION_SOURCE"; + + /** OptionTargetType enum. */ + type OptionTargetType = + "TARGET_TYPE_UNKNOWN"| "TARGET_TYPE_FILE"| "TARGET_TYPE_EXTENSION_RANGE"| "TARGET_TYPE_MESSAGE"| "TARGET_TYPE_FIELD"| "TARGET_TYPE_ONEOF"| "TARGET_TYPE_ENUM"| "TARGET_TYPE_ENUM_ENTRY"| "TARGET_TYPE_SERVICE"| "TARGET_TYPE_METHOD"; + + /** Properties of an EditionDefault. */ + interface IEditionDefault { + + /** EditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** EditionDefault value */ + value?: (string|null); + } + + /** Represents an EditionDefault. */ + class EditionDefault implements IEditionDefault { + + /** + * Constructs a new EditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); + + /** EditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** EditionDefault value. */ + public value: string; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @param message EditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an OneofOptions. */ + interface IOneofOptions { + + /** OneofOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { + + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); + + /** OneofOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumOptions. */ + interface IEnumOptions { + + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); + + /** EnumOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** EnumOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { + + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** EnumOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact */ + debugRedact?: (boolean|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { + + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); + + /** EnumValueOptions deprecated. */ + public deprecated: boolean; + + /** EnumValueOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact. */ + public debugRedact: boolean; + + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceOptions. */ + interface IServiceOptions { + + /** ServiceOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); + + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); + + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); + + /** ServiceOptions .google.api.apiVersion */ + ".google.api.apiVersion"?: (string|null); + } + + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { + + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); + + /** ServiceOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated. */ + public deprecated: boolean; + + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodOptions. */ + interface IMethodOptions { + + /** MethodOptions deprecated */ + deprecated?: (boolean|null); + + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); + + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); + + /** MethodOptions .google.api.routing */ + ".google.api.routing"?: (google.api.IRoutingRule|null); + + /** MethodOptions .google.longrunning.operationInfo */ + ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); + } + + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { + + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); + + /** MethodOptions deprecated. */ + public deprecated: boolean; + + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + type IdempotencyLevel = + "IDEMPOTENCY_UNKNOWN"| "NO_SIDE_EFFECTS"| "IDEMPOTENT"; + } + + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { + + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); + + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|string|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|string|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|string); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|string); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UninterpretedOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamePart + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a FeatureSet. */ + interface IFeatureSet { + + /** FeatureSet fieldPresence */ + fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|null); + + /** FeatureSet enumType */ + enumType?: (google.protobuf.FeatureSet.EnumType|null); + + /** FeatureSet repeatedFieldEncoding */ + repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|null); + + /** FeatureSet utf8Validation */ + utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|null); + + /** FeatureSet messageEncoding */ + messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|null); + + /** FeatureSet jsonFormat */ + jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|null); + } + + /** Represents a FeatureSet. */ + class FeatureSet implements IFeatureSet { + + /** + * Constructs a new FeatureSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSet); + + /** FeatureSet fieldPresence. */ + public fieldPresence: google.protobuf.FeatureSet.FieldPresence; + + /** FeatureSet enumType. */ + public enumType: google.protobuf.FeatureSet.EnumType; + + /** FeatureSet repeatedFieldEncoding. */ + public repeatedFieldEncoding: google.protobuf.FeatureSet.RepeatedFieldEncoding; + + /** FeatureSet utf8Validation. */ + public utf8Validation: google.protobuf.FeatureSet.Utf8Validation; + + /** FeatureSet messageEncoding. */ + public messageEncoding: google.protobuf.FeatureSet.MessageEncoding; + + /** FeatureSet jsonFormat. */ + public jsonFormat: google.protobuf.FeatureSet.JsonFormat; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @param message FeatureSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSet { + + /** FieldPresence enum. */ + type FieldPresence = + "FIELD_PRESENCE_UNKNOWN"| "EXPLICIT"| "IMPLICIT"| "LEGACY_REQUIRED"; + + /** EnumType enum. */ + type EnumType = + "ENUM_TYPE_UNKNOWN"| "OPEN"| "CLOSED"; + + /** RepeatedFieldEncoding enum. */ + type RepeatedFieldEncoding = + "REPEATED_FIELD_ENCODING_UNKNOWN"| "PACKED"| "EXPANDED"; + + /** Utf8Validation enum. */ + type Utf8Validation = + "UTF8_VALIDATION_UNKNOWN"| "VERIFY"| "NONE"; + + /** MessageEncoding enum. */ + type MessageEncoding = + "MESSAGE_ENCODING_UNKNOWN"| "LENGTH_PREFIXED"| "DELIMITED"; + + /** JsonFormat enum. */ + type JsonFormat = + "JSON_FORMAT_UNKNOWN"| "ALLOW"| "LEGACY_BEST_EFFORT"; + } + + /** Properties of a FeatureSetDefaults. */ + interface IFeatureSetDefaults { + + /** FeatureSetDefaults defaults */ + defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); + + /** FeatureSetDefaults minimumEdition */ + minimumEdition?: (google.protobuf.Edition|null); + + /** FeatureSetDefaults maximumEdition */ + maximumEdition?: (google.protobuf.Edition|null); + } + + /** Represents a FeatureSetDefaults. */ + class FeatureSetDefaults implements IFeatureSetDefaults { + + /** + * Constructs a new FeatureSetDefaults. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSetDefaults); + + /** FeatureSetDefaults defaults. */ + public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; + + /** FeatureSetDefaults minimumEdition. */ + public minimumEdition: google.protobuf.Edition; + + /** FeatureSetDefaults maximumEdition. */ + public maximumEdition: google.protobuf.Edition; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetDefaults + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @param message FeatureSetDefaults + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetDefaults + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSetDefaults { + + /** Properties of a FeatureSetEditionDefault. */ + interface IFeatureSetEditionDefault { + + /** FeatureSetEditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); + } + + /** Represents a FeatureSetEditionDefault. */ + class FeatureSetEditionDefault implements IFeatureSetEditionDefault { + + /** + * Constructs a new FeatureSetEditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); + + /** FeatureSetEditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetEditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @param message FeatureSetEditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { + + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } + + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { + + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); + + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SourceCodeInfo { + + /** Properties of a Location. */ + interface ILocation { + + /** Location path */ + path?: (number[]|null); + + /** Location span */ + span?: (number[]|null); + + /** Location leadingComments */ + leadingComments?: (string|null); + + /** Location trailingComments */ + trailingComments?: (string|null); + + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + + /** Location path. */ + public path: number[]; + + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Location + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { + + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } + + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { + + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); + + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + + /** Annotation semantic */ + semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); + } + + /** Represents an Annotation. */ + class Annotation implements IAnnotation { + + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); + + /** Annotation path. */ + public path: number[]; + + /** Annotation sourceFile. */ + public sourceFile: string; + + /** Annotation begin. */ + public begin: number; + + /** Annotation end. */ + public end: number; + + /** Annotation semantic. */ + public semantic: google.protobuf.GeneratedCodeInfo.Annotation.Semantic; + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Annotation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Annotation { + + /** Semantic enum. */ + type Semantic = + "NONE"| "SET"| "ALIAS"; + } + } + + /** Properties of a Timestamp. */ + interface ITimestamp { + + /** Timestamp seconds */ + seconds?: (number|string|null); + + /** Timestamp nanos */ + nanos?: (number|null); + } + + /** Represents a Timestamp. */ + class Timestamp implements ITimestamp { + + /** + * Constructs a new Timestamp. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ITimestamp); + + /** Timestamp seconds. */ + public seconds: (number|string); + + /** Timestamp nanos. */ + public nanos: number; + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Timestamp + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @param message Timestamp + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Timestamp to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Timestamp + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Duration. */ + interface IDuration { + + /** Duration seconds */ + seconds?: (number|string|null); + + /** Duration nanos */ + nanos?: (number|null); + } + + /** Represents a Duration. */ + class Duration implements IDuration { + + /** + * Constructs a new Duration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDuration); + + /** Duration seconds. */ + public seconds: (number|string); + + /** Duration nanos. */ + public nanos: number; + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Duration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Duration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Duration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Any. */ + interface IAny { + + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|null); + } + + /** Represents an Any. */ + class Any implements IAny { + + /** + * Constructs a new Any. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IAny); + + /** Any type_url. */ + public type_url: string; + + /** Any value. */ + public value: Uint8Array; + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Any + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Any to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Any + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Empty. */ + interface IEmpty { + } + + /** Represents an Empty. */ + class Empty implements IEmpty { + + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Empty + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldMask. */ + interface IFieldMask { + + /** FieldMask paths */ + paths?: (string[]|null); + } + + /** Represents a FieldMask. */ + class FieldMask implements IFieldMask { + + /** + * Constructs a new FieldMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldMask); + + /** FieldMask paths. */ + public paths: string[]; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldMask + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @param message FieldMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Struct. */ + interface IStruct { + + /** Struct fields */ + fields?: ({ [k: string]: google.protobuf.IValue }|null); + } + + /** Represents a Struct. */ + class Struct implements IStruct { + + /** + * Constructs a new Struct. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStruct); + + /** Struct fields. */ + public fields: { [k: string]: google.protobuf.IValue }; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Struct + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @param message Struct + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Struct to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Struct + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue */ + numberValue?: (number|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value boolValue */ + boolValue?: (boolean|null); + + /** Value structValue */ + structValue?: (google.protobuf.IStruct|null); + + /** Value listValue */ + listValue?: (google.protobuf.IListValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue. */ + public numberValue?: (number|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value boolValue. */ + public boolValue?: (boolean|null); + + /** Value structValue. */ + public structValue?: (google.protobuf.IStruct|null); + + /** Value listValue. */ + public listValue?: (google.protobuf.IListValue|null); + + /** Value kind. */ + public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** NullValue enum. */ + type NullValue = + "NULL_VALUE"; + + /** Properties of a ListValue. */ + interface IListValue { + + /** ListValue values */ + values?: (google.protobuf.IValue[]|null); + } + + /** Represents a ListValue. */ + class ListValue implements IListValue { + + /** + * Constructs a new ListValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IListValue); + + /** ListValue values. */ + public values: google.protobuf.IValue[]; + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @param message ListValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DoubleValue. */ + interface IDoubleValue { + + /** DoubleValue value */ + value?: (number|null); + } + + /** Represents a DoubleValue. */ + class DoubleValue implements IDoubleValue { + + /** + * Constructs a new DoubleValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDoubleValue); + + /** DoubleValue value. */ + public value: number; + + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DoubleValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; + + /** + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @param message DoubleValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DoubleValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DoubleValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FloatValue. */ + interface IFloatValue { + + /** FloatValue value */ + value?: (number|null); + } + + /** Represents a FloatValue. */ + class FloatValue implements IFloatValue { + + /** + * Constructs a new FloatValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFloatValue); + + /** FloatValue value. */ + public value: number; + + /** + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FloatValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; + + /** + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. + * @param message FloatValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FloatValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FloatValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int64Value. */ + interface IInt64Value { + + /** Int64Value value */ + value?: (number|string|null); + } + + /** Represents an Int64Value. */ + class Int64Value implements IInt64Value { + + /** + * Constructs a new Int64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt64Value); + + /** Int64Value value. */ + public value: (number|string); + + /** + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; + + /** + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. + * @param message Int64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt64Value. */ + interface IUInt64Value { + + /** UInt64Value value */ + value?: (number|string|null); + } + + /** Represents a UInt64Value. */ + class UInt64Value implements IUInt64Value { + + /** + * Constructs a new UInt64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt64Value); + + /** UInt64Value value. */ + public value: (number|string); + + /** + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; + + /** + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. + * @param message UInt64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int32Value. */ + interface IInt32Value { + + /** Int32Value value */ + value?: (number|null); + } + + /** Represents an Int32Value. */ + class Int32Value implements IInt32Value { + + /** + * Constructs a new Int32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt32Value); + + /** Int32Value value. */ + public value: number; + + /** + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; + + /** + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. + * @param message Int32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt32Value. */ + interface IUInt32Value { + + /** UInt32Value value */ + value?: (number|null); + } + + /** Represents a UInt32Value. */ + class UInt32Value implements IUInt32Value { + + /** + * Constructs a new UInt32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt32Value); + + /** UInt32Value value. */ + public value: number; + + /** + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; + + /** + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. + * @param message UInt32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BoolValue. */ + interface IBoolValue { + + /** BoolValue value */ + value?: (boolean|null); + } + + /** Represents a BoolValue. */ + class BoolValue implements IBoolValue { + + /** + * Constructs a new BoolValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBoolValue); + + /** BoolValue value. */ + public value: boolean; + + /** + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BoolValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; + + /** + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. + * @param message BoolValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BoolValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BoolValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StringValue. */ + interface IStringValue { + + /** StringValue value */ + value?: (string|null); + } + + /** Represents a StringValue. */ + class StringValue implements IStringValue { + + /** + * Constructs a new StringValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStringValue); + + /** StringValue value. */ + public value: string; + + /** + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StringValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; + + /** + * Creates a plain object from a StringValue message. Also converts values to other types if specified. + * @param message StringValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StringValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StringValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BytesValue. */ + interface IBytesValue { + + /** BytesValue value */ + value?: (Uint8Array|null); + } + + /** Represents a BytesValue. */ + class BytesValue implements IBytesValue { + + /** + * Constructs a new BytesValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBytesValue); + + /** BytesValue value. */ + public value: Uint8Array; + + /** + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BytesValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; + + /** + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. + * @param message BytesValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BytesValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BytesValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace type. */ + namespace type { + + /** DayOfWeek enum. */ + type DayOfWeek = + "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; + + /** Properties of a LatLng. */ + interface ILatLng { + + /** LatLng latitude */ + latitude?: (number|null); + + /** LatLng longitude */ + longitude?: (number|null); + } + + /** Represents a LatLng. */ + class LatLng implements ILatLng { + + /** + * Constructs a new LatLng. + * @param [properties] Properties to set + */ + constructor(properties?: google.type.ILatLng); + + /** LatLng latitude. */ + public latitude: number; + + /** LatLng longitude. */ + public longitude: number; + + /** + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LatLng + */ + public static fromObject(object: { [k: string]: any }): google.type.LatLng; + + /** + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @param message LatLng + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LatLng to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LatLng + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace longrunning. */ + namespace longrunning { + + /** Represents an Operations */ + class Operations extends $protobuf.rpc.Service { + + /** + * Constructs a new Operations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListOperationsResponse + */ + public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void; + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @returns Promise + */ + public listOperations(request: google.longrunning.IListOperationsRequest): Promise; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @returns Promise + */ + public getOperation(request: google.longrunning.IGetOperationRequest): Promise; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @returns Promise + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @returns Promise + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @returns Promise + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise; + } + + namespace Operations { + + /** + * Callback as used by {@link google.longrunning.Operations#listOperations}. + * @param error Error, if any + * @param [response] ListOperationsResponse + */ + type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#getOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#deleteOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#cancelOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#waitOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of an Operation. */ + interface IOperation { + + /** Operation name */ + name?: (string|null); + + /** Operation metadata */ + metadata?: (google.protobuf.IAny|null); + + /** Operation done */ + done?: (boolean|null); + + /** Operation error */ + error?: (google.rpc.IStatus|null); + + /** Operation response */ + response?: (google.protobuf.IAny|null); + } + + /** Represents an Operation. */ + class Operation implements IOperation { + + /** + * Constructs a new Operation. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperation); + + /** Operation name. */ + public name: string; + + /** Operation metadata. */ + public metadata?: (google.protobuf.IAny|null); + + /** Operation done. */ + public done: boolean; + + /** Operation error. */ + public error?: (google.rpc.IStatus|null); + + /** Operation response. */ + public response?: (google.protobuf.IAny|null); + + /** Operation result. */ + public result?: ("error"|"response"); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Operation + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.Operation; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @param message Operation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Operation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Operation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetOperationRequest. */ + interface IGetOperationRequest { + + /** GetOperationRequest name */ + name?: (string|null); + } + + /** Represents a GetOperationRequest. */ + class GetOperationRequest implements IGetOperationRequest { + + /** + * Constructs a new GetOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IGetOperationRequest); + + /** GetOperationRequest name. */ + public name: string; + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @param message GetOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsRequest. */ + interface IListOperationsRequest { + + /** ListOperationsRequest name */ + name?: (string|null); + + /** ListOperationsRequest filter */ + filter?: (string|null); + + /** ListOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListOperationsRequest pageToken */ + pageToken?: (string|null); + + /** ListOperationsRequest returnPartialSuccess */ + returnPartialSuccess?: (boolean|null); + } + + /** Represents a ListOperationsRequest. */ + class ListOperationsRequest implements IListOperationsRequest { + + /** + * Constructs a new ListOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsRequest); + + /** ListOperationsRequest name. */ + public name: string; + + /** ListOperationsRequest filter. */ + public filter: string; + + /** ListOperationsRequest pageSize. */ + public pageSize: number; + + /** ListOperationsRequest pageToken. */ + public pageToken: string; + + /** ListOperationsRequest returnPartialSuccess. */ + public returnPartialSuccess: boolean; + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @param message ListOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsResponse. */ + interface IListOperationsResponse { + + /** ListOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + + /** ListOperationsResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListOperationsResponse. */ + class ListOperationsResponse implements IListOperationsResponse { + + /** + * Constructs a new ListOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsResponse); + + /** ListOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** ListOperationsResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @param message ListOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CancelOperationRequest. */ + interface ICancelOperationRequest { + + /** CancelOperationRequest name */ + name?: (string|null); + } + + /** Represents a CancelOperationRequest. */ + class CancelOperationRequest implements ICancelOperationRequest { + + /** + * Constructs a new CancelOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.ICancelOperationRequest); + + /** CancelOperationRequest name. */ + public name: string; + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CancelOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @param message CancelOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CancelOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteOperationRequest. */ + interface IDeleteOperationRequest { + + /** DeleteOperationRequest name */ + name?: (string|null); + } + + /** Represents a DeleteOperationRequest. */ + class DeleteOperationRequest implements IDeleteOperationRequest { + + /** + * Constructs a new DeleteOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IDeleteOperationRequest); + + /** DeleteOperationRequest name. */ + public name: string; + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @param message DeleteOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WaitOperationRequest. */ + interface IWaitOperationRequest { + + /** WaitOperationRequest name */ + name?: (string|null); + + /** WaitOperationRequest timeout */ + timeout?: (google.protobuf.IDuration|null); + } + + /** Represents a WaitOperationRequest. */ + class WaitOperationRequest implements IWaitOperationRequest { + + /** + * Constructs a new WaitOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IWaitOperationRequest); + + /** WaitOperationRequest name. */ + public name: string; + + /** WaitOperationRequest timeout. */ + public timeout?: (google.protobuf.IDuration|null); + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @param message WaitOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WaitOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an OperationInfo. */ + interface IOperationInfo { + + /** OperationInfo responseType */ + responseType?: (string|null); + + /** OperationInfo metadataType */ + metadataType?: (string|null); + } + + /** Represents an OperationInfo. */ + class OperationInfo implements IOperationInfo { + + /** + * Constructs a new OperationInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperationInfo); + + /** OperationInfo responseType. */ + public responseType: string; + + /** OperationInfo metadataType. */ + public metadataType: string; + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationInfo + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @param message OperationInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace rpc. */ + namespace rpc { + + /** Properties of a Status. */ + interface IStatus { + + /** Status code */ + code?: (number|null); + + /** Status message */ + message?: (string|null); + + /** Status details */ + details?: (google.protobuf.IAny[]|null); + } + + /** Represents a Status. */ + class Status implements IStatus { + + /** + * Constructs a new Status. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IStatus); + + /** Status code. */ + public code: number; + + /** Status message. */ + public message: string; + + /** Status details. */ + public details: google.protobuf.IAny[]; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Status + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Status; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @param message Status + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Status to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Status + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } +} diff --git a/handwritten/firestore/dev/protos/firestore_admin_v1_proto_api.js b/handwritten/firestore/dev/protos/firestore_admin_v1_proto_api.js new file mode 100644 index 00000000000..86ef4cf7fcc --- /dev/null +++ b/handwritten/firestore/dev/protos/firestore_admin_v1_proto_api.js @@ -0,0 +1,25994 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/ +(function(global, factory) { /* global define, require, module */ + + /* AMD */ if (typeof define === 'function' && define.amd) + define(["protobufjs/minimal"], factory); + + /* CommonJS */ else if (typeof require === 'function' && typeof module === 'object' && module && module.exports) + module.exports = factory(require("protobufjs/minimal")); + +})(this, function($protobuf) { + "use strict"; + + // Common aliases + var $util = $protobuf.util; + + // Exported root namespace + var $root = $protobuf.roots.firestore_admin_v1 || ($protobuf.roots.firestore_admin_v1 = {}); + + $root.google = (function() { + + /** + * Namespace google. + * @exports google + * @namespace + */ + var google = {}; + + google.firestore = (function() { + + /** + * Namespace firestore. + * @memberof google + * @namespace + */ + var firestore = {}; + + firestore.admin = (function() { + + /** + * Namespace admin. + * @memberof google.firestore + * @namespace + */ + var admin = {}; + + admin.v1 = (function() { + + /** + * Namespace v1. + * @memberof google.firestore.admin + * @namespace + */ + var v1 = {}; + + v1.Backup = (function() { + + /** + * Properties of a Backup. + * @memberof google.firestore.admin.v1 + * @interface IBackup + * @property {string|null} [name] Backup name + * @property {string|null} [database] Backup database + * @property {string|null} [databaseUid] Backup databaseUid + * @property {google.protobuf.ITimestamp|null} [snapshotTime] Backup snapshotTime + * @property {google.protobuf.ITimestamp|null} [expireTime] Backup expireTime + * @property {google.firestore.admin.v1.Backup.IStats|null} [stats] Backup stats + * @property {google.firestore.admin.v1.Backup.State|null} [state] Backup state + */ + + /** + * Constructs a new Backup. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a Backup. + * @implements IBackup + * @constructor + * @param {google.firestore.admin.v1.IBackup=} [properties] Properties to set + */ + function Backup(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Backup name. + * @member {string} name + * @memberof google.firestore.admin.v1.Backup + * @instance + */ + Backup.prototype.name = ""; + + /** + * Backup database. + * @member {string} database + * @memberof google.firestore.admin.v1.Backup + * @instance + */ + Backup.prototype.database = ""; + + /** + * Backup databaseUid. + * @member {string} databaseUid + * @memberof google.firestore.admin.v1.Backup + * @instance + */ + Backup.prototype.databaseUid = ""; + + /** + * Backup snapshotTime. + * @member {google.protobuf.ITimestamp|null|undefined} snapshotTime + * @memberof google.firestore.admin.v1.Backup + * @instance + */ + Backup.prototype.snapshotTime = null; + + /** + * Backup expireTime. + * @member {google.protobuf.ITimestamp|null|undefined} expireTime + * @memberof google.firestore.admin.v1.Backup + * @instance + */ + Backup.prototype.expireTime = null; + + /** + * Backup stats. + * @member {google.firestore.admin.v1.Backup.IStats|null|undefined} stats + * @memberof google.firestore.admin.v1.Backup + * @instance + */ + Backup.prototype.stats = null; + + /** + * Backup state. + * @member {google.firestore.admin.v1.Backup.State} state + * @memberof google.firestore.admin.v1.Backup + * @instance + */ + Backup.prototype.state = 0; + + /** + * Creates a Backup message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Backup + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Backup} Backup + */ + Backup.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Backup) + return object; + var message = new $root.google.firestore.admin.v1.Backup(); + if (object.name != null) + message.name = String(object.name); + if (object.database != null) + message.database = String(object.database); + if (object.databaseUid != null) + message.databaseUid = String(object.databaseUid); + if (object.snapshotTime != null) { + if (typeof object.snapshotTime !== "object") + throw TypeError(".google.firestore.admin.v1.Backup.snapshotTime: object expected"); + message.snapshotTime = $root.google.protobuf.Timestamp.fromObject(object.snapshotTime); + } + if (object.expireTime != null) { + if (typeof object.expireTime !== "object") + throw TypeError(".google.firestore.admin.v1.Backup.expireTime: object expected"); + message.expireTime = $root.google.protobuf.Timestamp.fromObject(object.expireTime); + } + if (object.stats != null) { + if (typeof object.stats !== "object") + throw TypeError(".google.firestore.admin.v1.Backup.stats: object expected"); + message.stats = $root.google.firestore.admin.v1.Backup.Stats.fromObject(object.stats); + } + switch (object.state) { + default: + if (typeof object.state === "number") { + message.state = object.state; + break; + } + break; + case "STATE_UNSPECIFIED": + case 0: + message.state = 0; + break; + case "CREATING": + case 1: + message.state = 1; + break; + case "READY": + case 2: + message.state = 2; + break; + case "NOT_AVAILABLE": + case 3: + message.state = 3; + break; + } + return message; + }; + + /** + * Creates a plain object from a Backup message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Backup + * @static + * @param {google.firestore.admin.v1.Backup} message Backup + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Backup.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.database = ""; + object.snapshotTime = null; + object.expireTime = null; + object.stats = null; + object.databaseUid = ""; + object.state = options.enums === String ? "STATE_UNSPECIFIED" : 0; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.snapshotTime != null && message.hasOwnProperty("snapshotTime")) + object.snapshotTime = $root.google.protobuf.Timestamp.toObject(message.snapshotTime, options); + if (message.expireTime != null && message.hasOwnProperty("expireTime")) + object.expireTime = $root.google.protobuf.Timestamp.toObject(message.expireTime, options); + if (message.stats != null && message.hasOwnProperty("stats")) + object.stats = $root.google.firestore.admin.v1.Backup.Stats.toObject(message.stats, options); + if (message.databaseUid != null && message.hasOwnProperty("databaseUid")) + object.databaseUid = message.databaseUid; + if (message.state != null && message.hasOwnProperty("state")) + object.state = options.enums === String ? $root.google.firestore.admin.v1.Backup.State[message.state] === undefined ? message.state : $root.google.firestore.admin.v1.Backup.State[message.state] : message.state; + return object; + }; + + /** + * Converts this Backup to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Backup + * @instance + * @returns {Object.} JSON object + */ + Backup.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Backup + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Backup + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Backup.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Backup"; + }; + + Backup.Stats = (function() { + + /** + * Properties of a Stats. + * @memberof google.firestore.admin.v1.Backup + * @interface IStats + * @property {number|string|null} [sizeBytes] Stats sizeBytes + * @property {number|string|null} [documentCount] Stats documentCount + * @property {number|string|null} [indexCount] Stats indexCount + */ + + /** + * Constructs a new Stats. + * @memberof google.firestore.admin.v1.Backup + * @classdesc Represents a Stats. + * @implements IStats + * @constructor + * @param {google.firestore.admin.v1.Backup.IStats=} [properties] Properties to set + */ + function Stats(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Stats sizeBytes. + * @member {number|string} sizeBytes + * @memberof google.firestore.admin.v1.Backup.Stats + * @instance + */ + Stats.prototype.sizeBytes = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Stats documentCount. + * @member {number|string} documentCount + * @memberof google.firestore.admin.v1.Backup.Stats + * @instance + */ + Stats.prototype.documentCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Stats indexCount. + * @member {number|string} indexCount + * @memberof google.firestore.admin.v1.Backup.Stats + * @instance + */ + Stats.prototype.indexCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates a Stats message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Backup.Stats + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Backup.Stats} Stats + */ + Stats.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Backup.Stats) + return object; + var message = new $root.google.firestore.admin.v1.Backup.Stats(); + if (object.sizeBytes != null) + if ($util.Long) + (message.sizeBytes = $util.Long.fromValue(object.sizeBytes)).unsigned = false; + else if (typeof object.sizeBytes === "string") + message.sizeBytes = parseInt(object.sizeBytes, 10); + else if (typeof object.sizeBytes === "number") + message.sizeBytes = object.sizeBytes; + else if (typeof object.sizeBytes === "object") + message.sizeBytes = new $util.LongBits(object.sizeBytes.low >>> 0, object.sizeBytes.high >>> 0).toNumber(); + if (object.documentCount != null) + if ($util.Long) + (message.documentCount = $util.Long.fromValue(object.documentCount)).unsigned = false; + else if (typeof object.documentCount === "string") + message.documentCount = parseInt(object.documentCount, 10); + else if (typeof object.documentCount === "number") + message.documentCount = object.documentCount; + else if (typeof object.documentCount === "object") + message.documentCount = new $util.LongBits(object.documentCount.low >>> 0, object.documentCount.high >>> 0).toNumber(); + if (object.indexCount != null) + if ($util.Long) + (message.indexCount = $util.Long.fromValue(object.indexCount)).unsigned = false; + else if (typeof object.indexCount === "string") + message.indexCount = parseInt(object.indexCount, 10); + else if (typeof object.indexCount === "number") + message.indexCount = object.indexCount; + else if (typeof object.indexCount === "object") + message.indexCount = new $util.LongBits(object.indexCount.low >>> 0, object.indexCount.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a Stats message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Backup.Stats + * @static + * @param {google.firestore.admin.v1.Backup.Stats} message Stats + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Stats.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.sizeBytes = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.sizeBytes = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.documentCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.documentCount = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.indexCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.indexCount = options.longs === String ? "0" : 0; + } + if (message.sizeBytes != null && message.hasOwnProperty("sizeBytes")) + if (typeof message.sizeBytes === "number") + object.sizeBytes = options.longs === String ? String(message.sizeBytes) : message.sizeBytes; + else + object.sizeBytes = options.longs === String ? $util.Long.prototype.toString.call(message.sizeBytes) : options.longs === Number ? new $util.LongBits(message.sizeBytes.low >>> 0, message.sizeBytes.high >>> 0).toNumber() : message.sizeBytes; + if (message.documentCount != null && message.hasOwnProperty("documentCount")) + if (typeof message.documentCount === "number") + object.documentCount = options.longs === String ? String(message.documentCount) : message.documentCount; + else + object.documentCount = options.longs === String ? $util.Long.prototype.toString.call(message.documentCount) : options.longs === Number ? new $util.LongBits(message.documentCount.low >>> 0, message.documentCount.high >>> 0).toNumber() : message.documentCount; + if (message.indexCount != null && message.hasOwnProperty("indexCount")) + if (typeof message.indexCount === "number") + object.indexCount = options.longs === String ? String(message.indexCount) : message.indexCount; + else + object.indexCount = options.longs === String ? $util.Long.prototype.toString.call(message.indexCount) : options.longs === Number ? new $util.LongBits(message.indexCount.low >>> 0, message.indexCount.high >>> 0).toNumber() : message.indexCount; + return object; + }; + + /** + * Converts this Stats to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Backup.Stats + * @instance + * @returns {Object.} JSON object + */ + Stats.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Stats + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Backup.Stats + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Stats.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Backup.Stats"; + }; + + return Stats; + })(); + + /** + * State enum. + * @name google.firestore.admin.v1.Backup.State + * @enum {string} + * @property {string} STATE_UNSPECIFIED=STATE_UNSPECIFIED STATE_UNSPECIFIED value + * @property {string} CREATING=CREATING CREATING value + * @property {string} READY=READY READY value + * @property {string} NOT_AVAILABLE=NOT_AVAILABLE NOT_AVAILABLE value + */ + Backup.State = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + values[valuesById[1] = "CREATING"] = "CREATING"; + values[valuesById[2] = "READY"] = "READY"; + values[valuesById[3] = "NOT_AVAILABLE"] = "NOT_AVAILABLE"; + return values; + })(); + + return Backup; + })(); + + v1.Database = (function() { + + /** + * Properties of a Database. + * @memberof google.firestore.admin.v1 + * @interface IDatabase + * @property {string|null} [name] Database name + * @property {string|null} [uid] Database uid + * @property {google.protobuf.ITimestamp|null} [createTime] Database createTime + * @property {google.protobuf.ITimestamp|null} [updateTime] Database updateTime + * @property {google.protobuf.ITimestamp|null} [deleteTime] Database deleteTime + * @property {string|null} [locationId] Database locationId + * @property {google.firestore.admin.v1.Database.DatabaseType|null} [type] Database type + * @property {google.firestore.admin.v1.Database.ConcurrencyMode|null} [concurrencyMode] Database concurrencyMode + * @property {google.protobuf.IDuration|null} [versionRetentionPeriod] Database versionRetentionPeriod + * @property {google.protobuf.ITimestamp|null} [earliestVersionTime] Database earliestVersionTime + * @property {google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement|null} [pointInTimeRecoveryEnablement] Database pointInTimeRecoveryEnablement + * @property {google.firestore.admin.v1.Database.AppEngineIntegrationMode|null} [appEngineIntegrationMode] Database appEngineIntegrationMode + * @property {string|null} [keyPrefix] Database keyPrefix + * @property {google.firestore.admin.v1.Database.DeleteProtectionState|null} [deleteProtectionState] Database deleteProtectionState + * @property {google.firestore.admin.v1.Database.ICmekConfig|null} [cmekConfig] Database cmekConfig + * @property {string|null} [previousId] Database previousId + * @property {google.firestore.admin.v1.Database.ISourceInfo|null} [sourceInfo] Database sourceInfo + * @property {Object.|null} [tags] Database tags + * @property {boolean|null} [freeTier] Database freeTier + * @property {string|null} [etag] Database etag + * @property {google.firestore.admin.v1.Database.DatabaseEdition|null} [databaseEdition] Database databaseEdition + */ + + /** + * Constructs a new Database. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a Database. + * @implements IDatabase + * @constructor + * @param {google.firestore.admin.v1.IDatabase=} [properties] Properties to set + */ + function Database(properties) { + this.tags = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Database name. + * @member {string} name + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.name = ""; + + /** + * Database uid. + * @member {string} uid + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.uid = ""; + + /** + * Database createTime. + * @member {google.protobuf.ITimestamp|null|undefined} createTime + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.createTime = null; + + /** + * Database updateTime. + * @member {google.protobuf.ITimestamp|null|undefined} updateTime + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.updateTime = null; + + /** + * Database deleteTime. + * @member {google.protobuf.ITimestamp|null|undefined} deleteTime + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.deleteTime = null; + + /** + * Database locationId. + * @member {string} locationId + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.locationId = ""; + + /** + * Database type. + * @member {google.firestore.admin.v1.Database.DatabaseType} type + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.type = 0; + + /** + * Database concurrencyMode. + * @member {google.firestore.admin.v1.Database.ConcurrencyMode} concurrencyMode + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.concurrencyMode = 0; + + /** + * Database versionRetentionPeriod. + * @member {google.protobuf.IDuration|null|undefined} versionRetentionPeriod + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.versionRetentionPeriod = null; + + /** + * Database earliestVersionTime. + * @member {google.protobuf.ITimestamp|null|undefined} earliestVersionTime + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.earliestVersionTime = null; + + /** + * Database pointInTimeRecoveryEnablement. + * @member {google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement} pointInTimeRecoveryEnablement + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.pointInTimeRecoveryEnablement = 0; + + /** + * Database appEngineIntegrationMode. + * @member {google.firestore.admin.v1.Database.AppEngineIntegrationMode} appEngineIntegrationMode + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.appEngineIntegrationMode = 0; + + /** + * Database keyPrefix. + * @member {string} keyPrefix + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.keyPrefix = ""; + + /** + * Database deleteProtectionState. + * @member {google.firestore.admin.v1.Database.DeleteProtectionState} deleteProtectionState + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.deleteProtectionState = 0; + + /** + * Database cmekConfig. + * @member {google.firestore.admin.v1.Database.ICmekConfig|null|undefined} cmekConfig + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.cmekConfig = null; + + /** + * Database previousId. + * @member {string} previousId + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.previousId = ""; + + /** + * Database sourceInfo. + * @member {google.firestore.admin.v1.Database.ISourceInfo|null|undefined} sourceInfo + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.sourceInfo = null; + + /** + * Database tags. + * @member {Object.} tags + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.tags = $util.emptyObject; + + /** + * Database freeTier. + * @member {boolean|null|undefined} freeTier + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.freeTier = null; + + /** + * Database etag. + * @member {string} etag + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.etag = ""; + + /** + * Database databaseEdition. + * @member {google.firestore.admin.v1.Database.DatabaseEdition} databaseEdition + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.databaseEdition = 0; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(Database.prototype, "_freeTier", { + get: $util.oneOfGetter($oneOfFields = ["freeTier"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a Database message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Database + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Database} Database + */ + Database.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Database) + return object; + var message = new $root.google.firestore.admin.v1.Database(); + if (object.name != null) + message.name = String(object.name); + if (object.uid != null) + message.uid = String(object.uid); + if (object.createTime != null) { + if (typeof object.createTime !== "object") + throw TypeError(".google.firestore.admin.v1.Database.createTime: object expected"); + message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime); + } + if (object.updateTime != null) { + if (typeof object.updateTime !== "object") + throw TypeError(".google.firestore.admin.v1.Database.updateTime: object expected"); + message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + } + if (object.deleteTime != null) { + if (typeof object.deleteTime !== "object") + throw TypeError(".google.firestore.admin.v1.Database.deleteTime: object expected"); + message.deleteTime = $root.google.protobuf.Timestamp.fromObject(object.deleteTime); + } + if (object.locationId != null) + message.locationId = String(object.locationId); + switch (object.type) { + default: + if (typeof object.type === "number") { + message.type = object.type; + break; + } + break; + case "DATABASE_TYPE_UNSPECIFIED": + case 0: + message.type = 0; + break; + case "FIRESTORE_NATIVE": + case 1: + message.type = 1; + break; + case "DATASTORE_MODE": + case 2: + message.type = 2; + break; + } + switch (object.concurrencyMode) { + default: + if (typeof object.concurrencyMode === "number") { + message.concurrencyMode = object.concurrencyMode; + break; + } + break; + case "CONCURRENCY_MODE_UNSPECIFIED": + case 0: + message.concurrencyMode = 0; + break; + case "OPTIMISTIC": + case 1: + message.concurrencyMode = 1; + break; + case "PESSIMISTIC": + case 2: + message.concurrencyMode = 2; + break; + case "OPTIMISTIC_WITH_ENTITY_GROUPS": + case 3: + message.concurrencyMode = 3; + break; + } + if (object.versionRetentionPeriod != null) { + if (typeof object.versionRetentionPeriod !== "object") + throw TypeError(".google.firestore.admin.v1.Database.versionRetentionPeriod: object expected"); + message.versionRetentionPeriod = $root.google.protobuf.Duration.fromObject(object.versionRetentionPeriod); + } + if (object.earliestVersionTime != null) { + if (typeof object.earliestVersionTime !== "object") + throw TypeError(".google.firestore.admin.v1.Database.earliestVersionTime: object expected"); + message.earliestVersionTime = $root.google.protobuf.Timestamp.fromObject(object.earliestVersionTime); + } + switch (object.pointInTimeRecoveryEnablement) { + default: + if (typeof object.pointInTimeRecoveryEnablement === "number") { + message.pointInTimeRecoveryEnablement = object.pointInTimeRecoveryEnablement; + break; + } + break; + case "POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED": + case 0: + message.pointInTimeRecoveryEnablement = 0; + break; + case "POINT_IN_TIME_RECOVERY_ENABLED": + case 1: + message.pointInTimeRecoveryEnablement = 1; + break; + case "POINT_IN_TIME_RECOVERY_DISABLED": + case 2: + message.pointInTimeRecoveryEnablement = 2; + break; + } + switch (object.appEngineIntegrationMode) { + default: + if (typeof object.appEngineIntegrationMode === "number") { + message.appEngineIntegrationMode = object.appEngineIntegrationMode; + break; + } + break; + case "APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED": + case 0: + message.appEngineIntegrationMode = 0; + break; + case "ENABLED": + case 1: + message.appEngineIntegrationMode = 1; + break; + case "DISABLED": + case 2: + message.appEngineIntegrationMode = 2; + break; + } + if (object.keyPrefix != null) + message.keyPrefix = String(object.keyPrefix); + switch (object.deleteProtectionState) { + default: + if (typeof object.deleteProtectionState === "number") { + message.deleteProtectionState = object.deleteProtectionState; + break; + } + break; + case "DELETE_PROTECTION_STATE_UNSPECIFIED": + case 0: + message.deleteProtectionState = 0; + break; + case "DELETE_PROTECTION_DISABLED": + case 1: + message.deleteProtectionState = 1; + break; + case "DELETE_PROTECTION_ENABLED": + case 2: + message.deleteProtectionState = 2; + break; + } + if (object.cmekConfig != null) { + if (typeof object.cmekConfig !== "object") + throw TypeError(".google.firestore.admin.v1.Database.cmekConfig: object expected"); + message.cmekConfig = $root.google.firestore.admin.v1.Database.CmekConfig.fromObject(object.cmekConfig); + } + if (object.previousId != null) + message.previousId = String(object.previousId); + if (object.sourceInfo != null) { + if (typeof object.sourceInfo !== "object") + throw TypeError(".google.firestore.admin.v1.Database.sourceInfo: object expected"); + message.sourceInfo = $root.google.firestore.admin.v1.Database.SourceInfo.fromObject(object.sourceInfo); + } + if (object.tags) { + if (typeof object.tags !== "object") + throw TypeError(".google.firestore.admin.v1.Database.tags: object expected"); + message.tags = {}; + for (var keys = Object.keys(object.tags), i = 0; i < keys.length; ++i) + message.tags[keys[i]] = String(object.tags[keys[i]]); + } + if (object.freeTier != null) + message.freeTier = Boolean(object.freeTier); + if (object.etag != null) + message.etag = String(object.etag); + switch (object.databaseEdition) { + default: + if (typeof object.databaseEdition === "number") { + message.databaseEdition = object.databaseEdition; + break; + } + break; + case "DATABASE_EDITION_UNSPECIFIED": + case 0: + message.databaseEdition = 0; + break; + case "STANDARD": + case 1: + message.databaseEdition = 1; + break; + case "ENTERPRISE": + case 2: + message.databaseEdition = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from a Database message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Database + * @static + * @param {google.firestore.admin.v1.Database} message Database + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Database.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.tags = {}; + if (options.defaults) { + object.name = ""; + object.uid = ""; + object.createTime = null; + object.updateTime = null; + object.deleteTime = null; + object.locationId = ""; + object.type = options.enums === String ? "DATABASE_TYPE_UNSPECIFIED" : 0; + object.concurrencyMode = options.enums === String ? "CONCURRENCY_MODE_UNSPECIFIED" : 0; + object.versionRetentionPeriod = null; + object.earliestVersionTime = null; + object.appEngineIntegrationMode = options.enums === String ? "APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED" : 0; + object.keyPrefix = ""; + object.pointInTimeRecoveryEnablement = options.enums === String ? "POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED" : 0; + object.deleteProtectionState = options.enums === String ? "DELETE_PROTECTION_STATE_UNSPECIFIED" : 0; + object.cmekConfig = null; + object.previousId = ""; + object.sourceInfo = null; + object.databaseEdition = options.enums === String ? "DATABASE_EDITION_UNSPECIFIED" : 0; + object.etag = ""; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.uid != null && message.hasOwnProperty("uid")) + object.uid = message.uid; + if (message.createTime != null && message.hasOwnProperty("createTime")) + object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); + if (message.updateTime != null && message.hasOwnProperty("updateTime")) + object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + if (message.deleteTime != null && message.hasOwnProperty("deleteTime")) + object.deleteTime = $root.google.protobuf.Timestamp.toObject(message.deleteTime, options); + if (message.locationId != null && message.hasOwnProperty("locationId")) + object.locationId = message.locationId; + if (message.type != null && message.hasOwnProperty("type")) + object.type = options.enums === String ? $root.google.firestore.admin.v1.Database.DatabaseType[message.type] === undefined ? message.type : $root.google.firestore.admin.v1.Database.DatabaseType[message.type] : message.type; + if (message.concurrencyMode != null && message.hasOwnProperty("concurrencyMode")) + object.concurrencyMode = options.enums === String ? $root.google.firestore.admin.v1.Database.ConcurrencyMode[message.concurrencyMode] === undefined ? message.concurrencyMode : $root.google.firestore.admin.v1.Database.ConcurrencyMode[message.concurrencyMode] : message.concurrencyMode; + if (message.versionRetentionPeriod != null && message.hasOwnProperty("versionRetentionPeriod")) + object.versionRetentionPeriod = $root.google.protobuf.Duration.toObject(message.versionRetentionPeriod, options); + if (message.earliestVersionTime != null && message.hasOwnProperty("earliestVersionTime")) + object.earliestVersionTime = $root.google.protobuf.Timestamp.toObject(message.earliestVersionTime, options); + if (message.appEngineIntegrationMode != null && message.hasOwnProperty("appEngineIntegrationMode")) + object.appEngineIntegrationMode = options.enums === String ? $root.google.firestore.admin.v1.Database.AppEngineIntegrationMode[message.appEngineIntegrationMode] === undefined ? message.appEngineIntegrationMode : $root.google.firestore.admin.v1.Database.AppEngineIntegrationMode[message.appEngineIntegrationMode] : message.appEngineIntegrationMode; + if (message.keyPrefix != null && message.hasOwnProperty("keyPrefix")) + object.keyPrefix = message.keyPrefix; + if (message.pointInTimeRecoveryEnablement != null && message.hasOwnProperty("pointInTimeRecoveryEnablement")) + object.pointInTimeRecoveryEnablement = options.enums === String ? $root.google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement[message.pointInTimeRecoveryEnablement] === undefined ? message.pointInTimeRecoveryEnablement : $root.google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement[message.pointInTimeRecoveryEnablement] : message.pointInTimeRecoveryEnablement; + if (message.deleteProtectionState != null && message.hasOwnProperty("deleteProtectionState")) + object.deleteProtectionState = options.enums === String ? $root.google.firestore.admin.v1.Database.DeleteProtectionState[message.deleteProtectionState] === undefined ? message.deleteProtectionState : $root.google.firestore.admin.v1.Database.DeleteProtectionState[message.deleteProtectionState] : message.deleteProtectionState; + if (message.cmekConfig != null && message.hasOwnProperty("cmekConfig")) + object.cmekConfig = $root.google.firestore.admin.v1.Database.CmekConfig.toObject(message.cmekConfig, options); + if (message.previousId != null && message.hasOwnProperty("previousId")) + object.previousId = message.previousId; + if (message.sourceInfo != null && message.hasOwnProperty("sourceInfo")) + object.sourceInfo = $root.google.firestore.admin.v1.Database.SourceInfo.toObject(message.sourceInfo, options); + if (message.databaseEdition != null && message.hasOwnProperty("databaseEdition")) + object.databaseEdition = options.enums === String ? $root.google.firestore.admin.v1.Database.DatabaseEdition[message.databaseEdition] === undefined ? message.databaseEdition : $root.google.firestore.admin.v1.Database.DatabaseEdition[message.databaseEdition] : message.databaseEdition; + var keys2; + if (message.tags && (keys2 = Object.keys(message.tags)).length) { + object.tags = {}; + for (var j = 0; j < keys2.length; ++j) + object.tags[keys2[j]] = message.tags[keys2[j]]; + } + if (message.freeTier != null && message.hasOwnProperty("freeTier")) { + object.freeTier = message.freeTier; + if (options.oneofs) + object._freeTier = "freeTier"; + } + if (message.etag != null && message.hasOwnProperty("etag")) + object.etag = message.etag; + return object; + }; + + /** + * Converts this Database to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Database + * @instance + * @returns {Object.} JSON object + */ + Database.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Database + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Database + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Database.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Database"; + }; + + /** + * DatabaseType enum. + * @name google.firestore.admin.v1.Database.DatabaseType + * @enum {string} + * @property {string} DATABASE_TYPE_UNSPECIFIED=DATABASE_TYPE_UNSPECIFIED DATABASE_TYPE_UNSPECIFIED value + * @property {string} FIRESTORE_NATIVE=FIRESTORE_NATIVE FIRESTORE_NATIVE value + * @property {string} DATASTORE_MODE=DATASTORE_MODE DATASTORE_MODE value + */ + Database.DatabaseType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DATABASE_TYPE_UNSPECIFIED"] = "DATABASE_TYPE_UNSPECIFIED"; + values[valuesById[1] = "FIRESTORE_NATIVE"] = "FIRESTORE_NATIVE"; + values[valuesById[2] = "DATASTORE_MODE"] = "DATASTORE_MODE"; + return values; + })(); + + /** + * ConcurrencyMode enum. + * @name google.firestore.admin.v1.Database.ConcurrencyMode + * @enum {string} + * @property {string} CONCURRENCY_MODE_UNSPECIFIED=CONCURRENCY_MODE_UNSPECIFIED CONCURRENCY_MODE_UNSPECIFIED value + * @property {string} OPTIMISTIC=OPTIMISTIC OPTIMISTIC value + * @property {string} PESSIMISTIC=PESSIMISTIC PESSIMISTIC value + * @property {string} OPTIMISTIC_WITH_ENTITY_GROUPS=OPTIMISTIC_WITH_ENTITY_GROUPS OPTIMISTIC_WITH_ENTITY_GROUPS value + */ + Database.ConcurrencyMode = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "CONCURRENCY_MODE_UNSPECIFIED"] = "CONCURRENCY_MODE_UNSPECIFIED"; + values[valuesById[1] = "OPTIMISTIC"] = "OPTIMISTIC"; + values[valuesById[2] = "PESSIMISTIC"] = "PESSIMISTIC"; + values[valuesById[3] = "OPTIMISTIC_WITH_ENTITY_GROUPS"] = "OPTIMISTIC_WITH_ENTITY_GROUPS"; + return values; + })(); + + /** + * PointInTimeRecoveryEnablement enum. + * @name google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement + * @enum {string} + * @property {string} POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED=POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED value + * @property {string} POINT_IN_TIME_RECOVERY_ENABLED=POINT_IN_TIME_RECOVERY_ENABLED POINT_IN_TIME_RECOVERY_ENABLED value + * @property {string} POINT_IN_TIME_RECOVERY_DISABLED=POINT_IN_TIME_RECOVERY_DISABLED POINT_IN_TIME_RECOVERY_DISABLED value + */ + Database.PointInTimeRecoveryEnablement = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED"] = "POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED"; + values[valuesById[1] = "POINT_IN_TIME_RECOVERY_ENABLED"] = "POINT_IN_TIME_RECOVERY_ENABLED"; + values[valuesById[2] = "POINT_IN_TIME_RECOVERY_DISABLED"] = "POINT_IN_TIME_RECOVERY_DISABLED"; + return values; + })(); + + /** + * AppEngineIntegrationMode enum. + * @name google.firestore.admin.v1.Database.AppEngineIntegrationMode + * @enum {string} + * @property {string} APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED=APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED value + * @property {string} ENABLED=ENABLED ENABLED value + * @property {string} DISABLED=DISABLED DISABLED value + */ + Database.AppEngineIntegrationMode = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED"] = "APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED"; + values[valuesById[1] = "ENABLED"] = "ENABLED"; + values[valuesById[2] = "DISABLED"] = "DISABLED"; + return values; + })(); + + /** + * DeleteProtectionState enum. + * @name google.firestore.admin.v1.Database.DeleteProtectionState + * @enum {string} + * @property {string} DELETE_PROTECTION_STATE_UNSPECIFIED=DELETE_PROTECTION_STATE_UNSPECIFIED DELETE_PROTECTION_STATE_UNSPECIFIED value + * @property {string} DELETE_PROTECTION_DISABLED=DELETE_PROTECTION_DISABLED DELETE_PROTECTION_DISABLED value + * @property {string} DELETE_PROTECTION_ENABLED=DELETE_PROTECTION_ENABLED DELETE_PROTECTION_ENABLED value + */ + Database.DeleteProtectionState = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DELETE_PROTECTION_STATE_UNSPECIFIED"] = "DELETE_PROTECTION_STATE_UNSPECIFIED"; + values[valuesById[1] = "DELETE_PROTECTION_DISABLED"] = "DELETE_PROTECTION_DISABLED"; + values[valuesById[2] = "DELETE_PROTECTION_ENABLED"] = "DELETE_PROTECTION_ENABLED"; + return values; + })(); + + Database.CmekConfig = (function() { + + /** + * Properties of a CmekConfig. + * @memberof google.firestore.admin.v1.Database + * @interface ICmekConfig + * @property {string|null} [kmsKeyName] CmekConfig kmsKeyName + * @property {Array.|null} [activeKeyVersion] CmekConfig activeKeyVersion + */ + + /** + * Constructs a new CmekConfig. + * @memberof google.firestore.admin.v1.Database + * @classdesc Represents a CmekConfig. + * @implements ICmekConfig + * @constructor + * @param {google.firestore.admin.v1.Database.ICmekConfig=} [properties] Properties to set + */ + function CmekConfig(properties) { + this.activeKeyVersion = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CmekConfig kmsKeyName. + * @member {string} kmsKeyName + * @memberof google.firestore.admin.v1.Database.CmekConfig + * @instance + */ + CmekConfig.prototype.kmsKeyName = ""; + + /** + * CmekConfig activeKeyVersion. + * @member {Array.} activeKeyVersion + * @memberof google.firestore.admin.v1.Database.CmekConfig + * @instance + */ + CmekConfig.prototype.activeKeyVersion = $util.emptyArray; + + /** + * Creates a CmekConfig message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Database.CmekConfig + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Database.CmekConfig} CmekConfig + */ + CmekConfig.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Database.CmekConfig) + return object; + var message = new $root.google.firestore.admin.v1.Database.CmekConfig(); + if (object.kmsKeyName != null) + message.kmsKeyName = String(object.kmsKeyName); + if (object.activeKeyVersion) { + if (!Array.isArray(object.activeKeyVersion)) + throw TypeError(".google.firestore.admin.v1.Database.CmekConfig.activeKeyVersion: array expected"); + message.activeKeyVersion = []; + for (var i = 0; i < object.activeKeyVersion.length; ++i) + message.activeKeyVersion[i] = String(object.activeKeyVersion[i]); + } + return message; + }; + + /** + * Creates a plain object from a CmekConfig message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Database.CmekConfig + * @static + * @param {google.firestore.admin.v1.Database.CmekConfig} message CmekConfig + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CmekConfig.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.activeKeyVersion = []; + if (options.defaults) + object.kmsKeyName = ""; + if (message.kmsKeyName != null && message.hasOwnProperty("kmsKeyName")) + object.kmsKeyName = message.kmsKeyName; + if (message.activeKeyVersion && message.activeKeyVersion.length) { + object.activeKeyVersion = []; + for (var j = 0; j < message.activeKeyVersion.length; ++j) + object.activeKeyVersion[j] = message.activeKeyVersion[j]; + } + return object; + }; + + /** + * Converts this CmekConfig to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Database.CmekConfig + * @instance + * @returns {Object.} JSON object + */ + CmekConfig.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CmekConfig + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Database.CmekConfig + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CmekConfig.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Database.CmekConfig"; + }; + + return CmekConfig; + })(); + + Database.SourceInfo = (function() { + + /** + * Properties of a SourceInfo. + * @memberof google.firestore.admin.v1.Database + * @interface ISourceInfo + * @property {google.firestore.admin.v1.Database.SourceInfo.IBackupSource|null} [backup] SourceInfo backup + * @property {string|null} [operation] SourceInfo operation + */ + + /** + * Constructs a new SourceInfo. + * @memberof google.firestore.admin.v1.Database + * @classdesc Represents a SourceInfo. + * @implements ISourceInfo + * @constructor + * @param {google.firestore.admin.v1.Database.ISourceInfo=} [properties] Properties to set + */ + function SourceInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SourceInfo backup. + * @member {google.firestore.admin.v1.Database.SourceInfo.IBackupSource|null|undefined} backup + * @memberof google.firestore.admin.v1.Database.SourceInfo + * @instance + */ + SourceInfo.prototype.backup = null; + + /** + * SourceInfo operation. + * @member {string} operation + * @memberof google.firestore.admin.v1.Database.SourceInfo + * @instance + */ + SourceInfo.prototype.operation = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * SourceInfo source. + * @member {"backup"|undefined} source + * @memberof google.firestore.admin.v1.Database.SourceInfo + * @instance + */ + Object.defineProperty(SourceInfo.prototype, "source", { + get: $util.oneOfGetter($oneOfFields = ["backup"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a SourceInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Database.SourceInfo + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Database.SourceInfo} SourceInfo + */ + SourceInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Database.SourceInfo) + return object; + var message = new $root.google.firestore.admin.v1.Database.SourceInfo(); + if (object.backup != null) { + if (typeof object.backup !== "object") + throw TypeError(".google.firestore.admin.v1.Database.SourceInfo.backup: object expected"); + message.backup = $root.google.firestore.admin.v1.Database.SourceInfo.BackupSource.fromObject(object.backup); + } + if (object.operation != null) + message.operation = String(object.operation); + return message; + }; + + /** + * Creates a plain object from a SourceInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Database.SourceInfo + * @static + * @param {google.firestore.admin.v1.Database.SourceInfo} message SourceInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SourceInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.operation = ""; + if (message.backup != null && message.hasOwnProperty("backup")) { + object.backup = $root.google.firestore.admin.v1.Database.SourceInfo.BackupSource.toObject(message.backup, options); + if (options.oneofs) + object.source = "backup"; + } + if (message.operation != null && message.hasOwnProperty("operation")) + object.operation = message.operation; + return object; + }; + + /** + * Converts this SourceInfo to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Database.SourceInfo + * @instance + * @returns {Object.} JSON object + */ + SourceInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SourceInfo + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Database.SourceInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SourceInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Database.SourceInfo"; + }; + + SourceInfo.BackupSource = (function() { + + /** + * Properties of a BackupSource. + * @memberof google.firestore.admin.v1.Database.SourceInfo + * @interface IBackupSource + * @property {string|null} [backup] BackupSource backup + */ + + /** + * Constructs a new BackupSource. + * @memberof google.firestore.admin.v1.Database.SourceInfo + * @classdesc Represents a BackupSource. + * @implements IBackupSource + * @constructor + * @param {google.firestore.admin.v1.Database.SourceInfo.IBackupSource=} [properties] Properties to set + */ + function BackupSource(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BackupSource backup. + * @member {string} backup + * @memberof google.firestore.admin.v1.Database.SourceInfo.BackupSource + * @instance + */ + BackupSource.prototype.backup = ""; + + /** + * Creates a BackupSource message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Database.SourceInfo.BackupSource + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Database.SourceInfo.BackupSource} BackupSource + */ + BackupSource.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Database.SourceInfo.BackupSource) + return object; + var message = new $root.google.firestore.admin.v1.Database.SourceInfo.BackupSource(); + if (object.backup != null) + message.backup = String(object.backup); + return message; + }; + + /** + * Creates a plain object from a BackupSource message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Database.SourceInfo.BackupSource + * @static + * @param {google.firestore.admin.v1.Database.SourceInfo.BackupSource} message BackupSource + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BackupSource.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.backup = ""; + if (message.backup != null && message.hasOwnProperty("backup")) + object.backup = message.backup; + return object; + }; + + /** + * Converts this BackupSource to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Database.SourceInfo.BackupSource + * @instance + * @returns {Object.} JSON object + */ + BackupSource.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BackupSource + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Database.SourceInfo.BackupSource + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BackupSource.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Database.SourceInfo.BackupSource"; + }; + + return BackupSource; + })(); + + return SourceInfo; + })(); + + Database.EncryptionConfig = (function() { + + /** + * Properties of an EncryptionConfig. + * @memberof google.firestore.admin.v1.Database + * @interface IEncryptionConfig + * @property {google.firestore.admin.v1.Database.EncryptionConfig.IGoogleDefaultEncryptionOptions|null} [googleDefaultEncryption] EncryptionConfig googleDefaultEncryption + * @property {google.firestore.admin.v1.Database.EncryptionConfig.ISourceEncryptionOptions|null} [useSourceEncryption] EncryptionConfig useSourceEncryption + * @property {google.firestore.admin.v1.Database.EncryptionConfig.ICustomerManagedEncryptionOptions|null} [customerManagedEncryption] EncryptionConfig customerManagedEncryption + */ + + /** + * Constructs a new EncryptionConfig. + * @memberof google.firestore.admin.v1.Database + * @classdesc Represents an EncryptionConfig. + * @implements IEncryptionConfig + * @constructor + * @param {google.firestore.admin.v1.Database.IEncryptionConfig=} [properties] Properties to set + */ + function EncryptionConfig(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EncryptionConfig googleDefaultEncryption. + * @member {google.firestore.admin.v1.Database.EncryptionConfig.IGoogleDefaultEncryptionOptions|null|undefined} googleDefaultEncryption + * @memberof google.firestore.admin.v1.Database.EncryptionConfig + * @instance + */ + EncryptionConfig.prototype.googleDefaultEncryption = null; + + /** + * EncryptionConfig useSourceEncryption. + * @member {google.firestore.admin.v1.Database.EncryptionConfig.ISourceEncryptionOptions|null|undefined} useSourceEncryption + * @memberof google.firestore.admin.v1.Database.EncryptionConfig + * @instance + */ + EncryptionConfig.prototype.useSourceEncryption = null; + + /** + * EncryptionConfig customerManagedEncryption. + * @member {google.firestore.admin.v1.Database.EncryptionConfig.ICustomerManagedEncryptionOptions|null|undefined} customerManagedEncryption + * @memberof google.firestore.admin.v1.Database.EncryptionConfig + * @instance + */ + EncryptionConfig.prototype.customerManagedEncryption = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * EncryptionConfig encryptionType. + * @member {"googleDefaultEncryption"|"useSourceEncryption"|"customerManagedEncryption"|undefined} encryptionType + * @memberof google.firestore.admin.v1.Database.EncryptionConfig + * @instance + */ + Object.defineProperty(EncryptionConfig.prototype, "encryptionType", { + get: $util.oneOfGetter($oneOfFields = ["googleDefaultEncryption", "useSourceEncryption", "customerManagedEncryption"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates an EncryptionConfig message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Database.EncryptionConfig + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Database.EncryptionConfig} EncryptionConfig + */ + EncryptionConfig.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Database.EncryptionConfig) + return object; + var message = new $root.google.firestore.admin.v1.Database.EncryptionConfig(); + if (object.googleDefaultEncryption != null) { + if (typeof object.googleDefaultEncryption !== "object") + throw TypeError(".google.firestore.admin.v1.Database.EncryptionConfig.googleDefaultEncryption: object expected"); + message.googleDefaultEncryption = $root.google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions.fromObject(object.googleDefaultEncryption); + } + if (object.useSourceEncryption != null) { + if (typeof object.useSourceEncryption !== "object") + throw TypeError(".google.firestore.admin.v1.Database.EncryptionConfig.useSourceEncryption: object expected"); + message.useSourceEncryption = $root.google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions.fromObject(object.useSourceEncryption); + } + if (object.customerManagedEncryption != null) { + if (typeof object.customerManagedEncryption !== "object") + throw TypeError(".google.firestore.admin.v1.Database.EncryptionConfig.customerManagedEncryption: object expected"); + message.customerManagedEncryption = $root.google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions.fromObject(object.customerManagedEncryption); + } + return message; + }; + + /** + * Creates a plain object from an EncryptionConfig message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Database.EncryptionConfig + * @static + * @param {google.firestore.admin.v1.Database.EncryptionConfig} message EncryptionConfig + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EncryptionConfig.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.googleDefaultEncryption != null && message.hasOwnProperty("googleDefaultEncryption")) { + object.googleDefaultEncryption = $root.google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions.toObject(message.googleDefaultEncryption, options); + if (options.oneofs) + object.encryptionType = "googleDefaultEncryption"; + } + if (message.useSourceEncryption != null && message.hasOwnProperty("useSourceEncryption")) { + object.useSourceEncryption = $root.google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions.toObject(message.useSourceEncryption, options); + if (options.oneofs) + object.encryptionType = "useSourceEncryption"; + } + if (message.customerManagedEncryption != null && message.hasOwnProperty("customerManagedEncryption")) { + object.customerManagedEncryption = $root.google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions.toObject(message.customerManagedEncryption, options); + if (options.oneofs) + object.encryptionType = "customerManagedEncryption"; + } + return object; + }; + + /** + * Converts this EncryptionConfig to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Database.EncryptionConfig + * @instance + * @returns {Object.} JSON object + */ + EncryptionConfig.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EncryptionConfig + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Database.EncryptionConfig + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EncryptionConfig.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Database.EncryptionConfig"; + }; + + EncryptionConfig.GoogleDefaultEncryptionOptions = (function() { + + /** + * Properties of a GoogleDefaultEncryptionOptions. + * @memberof google.firestore.admin.v1.Database.EncryptionConfig + * @interface IGoogleDefaultEncryptionOptions + */ + + /** + * Constructs a new GoogleDefaultEncryptionOptions. + * @memberof google.firestore.admin.v1.Database.EncryptionConfig + * @classdesc Represents a GoogleDefaultEncryptionOptions. + * @implements IGoogleDefaultEncryptionOptions + * @constructor + * @param {google.firestore.admin.v1.Database.EncryptionConfig.IGoogleDefaultEncryptionOptions=} [properties] Properties to set + */ + function GoogleDefaultEncryptionOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a GoogleDefaultEncryptionOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions} GoogleDefaultEncryptionOptions + */ + GoogleDefaultEncryptionOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions) + return object; + return new $root.google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions(); + }; + + /** + * Creates a plain object from a GoogleDefaultEncryptionOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions + * @static + * @param {google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions} message GoogleDefaultEncryptionOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GoogleDefaultEncryptionOptions.toObject = function toObject() { + return {}; + }; + + /** + * Converts this GoogleDefaultEncryptionOptions to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions + * @instance + * @returns {Object.} JSON object + */ + GoogleDefaultEncryptionOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GoogleDefaultEncryptionOptions + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GoogleDefaultEncryptionOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions"; + }; + + return GoogleDefaultEncryptionOptions; + })(); + + EncryptionConfig.SourceEncryptionOptions = (function() { + + /** + * Properties of a SourceEncryptionOptions. + * @memberof google.firestore.admin.v1.Database.EncryptionConfig + * @interface ISourceEncryptionOptions + */ + + /** + * Constructs a new SourceEncryptionOptions. + * @memberof google.firestore.admin.v1.Database.EncryptionConfig + * @classdesc Represents a SourceEncryptionOptions. + * @implements ISourceEncryptionOptions + * @constructor + * @param {google.firestore.admin.v1.Database.EncryptionConfig.ISourceEncryptionOptions=} [properties] Properties to set + */ + function SourceEncryptionOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a SourceEncryptionOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions} SourceEncryptionOptions + */ + SourceEncryptionOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions) + return object; + return new $root.google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions(); + }; + + /** + * Creates a plain object from a SourceEncryptionOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions + * @static + * @param {google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions} message SourceEncryptionOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SourceEncryptionOptions.toObject = function toObject() { + return {}; + }; + + /** + * Converts this SourceEncryptionOptions to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions + * @instance + * @returns {Object.} JSON object + */ + SourceEncryptionOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SourceEncryptionOptions + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SourceEncryptionOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions"; + }; + + return SourceEncryptionOptions; + })(); + + EncryptionConfig.CustomerManagedEncryptionOptions = (function() { + + /** + * Properties of a CustomerManagedEncryptionOptions. + * @memberof google.firestore.admin.v1.Database.EncryptionConfig + * @interface ICustomerManagedEncryptionOptions + * @property {string|null} [kmsKeyName] CustomerManagedEncryptionOptions kmsKeyName + */ + + /** + * Constructs a new CustomerManagedEncryptionOptions. + * @memberof google.firestore.admin.v1.Database.EncryptionConfig + * @classdesc Represents a CustomerManagedEncryptionOptions. + * @implements ICustomerManagedEncryptionOptions + * @constructor + * @param {google.firestore.admin.v1.Database.EncryptionConfig.ICustomerManagedEncryptionOptions=} [properties] Properties to set + */ + function CustomerManagedEncryptionOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CustomerManagedEncryptionOptions kmsKeyName. + * @member {string} kmsKeyName + * @memberof google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions + * @instance + */ + CustomerManagedEncryptionOptions.prototype.kmsKeyName = ""; + + /** + * Creates a CustomerManagedEncryptionOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions} CustomerManagedEncryptionOptions + */ + CustomerManagedEncryptionOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions) + return object; + var message = new $root.google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions(); + if (object.kmsKeyName != null) + message.kmsKeyName = String(object.kmsKeyName); + return message; + }; + + /** + * Creates a plain object from a CustomerManagedEncryptionOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions + * @static + * @param {google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions} message CustomerManagedEncryptionOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CustomerManagedEncryptionOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.kmsKeyName = ""; + if (message.kmsKeyName != null && message.hasOwnProperty("kmsKeyName")) + object.kmsKeyName = message.kmsKeyName; + return object; + }; + + /** + * Converts this CustomerManagedEncryptionOptions to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions + * @instance + * @returns {Object.} JSON object + */ + CustomerManagedEncryptionOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CustomerManagedEncryptionOptions + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CustomerManagedEncryptionOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions"; + }; + + return CustomerManagedEncryptionOptions; + })(); + + return EncryptionConfig; + })(); + + /** + * DatabaseEdition enum. + * @name google.firestore.admin.v1.Database.DatabaseEdition + * @enum {string} + * @property {string} DATABASE_EDITION_UNSPECIFIED=DATABASE_EDITION_UNSPECIFIED DATABASE_EDITION_UNSPECIFIED value + * @property {string} STANDARD=STANDARD STANDARD value + * @property {string} ENTERPRISE=ENTERPRISE ENTERPRISE value + */ + Database.DatabaseEdition = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DATABASE_EDITION_UNSPECIFIED"] = "DATABASE_EDITION_UNSPECIFIED"; + values[valuesById[1] = "STANDARD"] = "STANDARD"; + values[valuesById[2] = "ENTERPRISE"] = "ENTERPRISE"; + return values; + })(); + + return Database; + })(); + + v1.Field = (function() { + + /** + * Properties of a Field. + * @memberof google.firestore.admin.v1 + * @interface IField + * @property {string|null} [name] Field name + * @property {google.firestore.admin.v1.Field.IIndexConfig|null} [indexConfig] Field indexConfig + * @property {google.firestore.admin.v1.Field.ITtlConfig|null} [ttlConfig] Field ttlConfig + */ + + /** + * Constructs a new Field. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a Field. + * @implements IField + * @constructor + * @param {google.firestore.admin.v1.IField=} [properties] Properties to set + */ + function Field(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Field name. + * @member {string} name + * @memberof google.firestore.admin.v1.Field + * @instance + */ + Field.prototype.name = ""; + + /** + * Field indexConfig. + * @member {google.firestore.admin.v1.Field.IIndexConfig|null|undefined} indexConfig + * @memberof google.firestore.admin.v1.Field + * @instance + */ + Field.prototype.indexConfig = null; + + /** + * Field ttlConfig. + * @member {google.firestore.admin.v1.Field.ITtlConfig|null|undefined} ttlConfig + * @memberof google.firestore.admin.v1.Field + * @instance + */ + Field.prototype.ttlConfig = null; + + /** + * Creates a Field message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Field + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Field} Field + */ + Field.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Field) + return object; + var message = new $root.google.firestore.admin.v1.Field(); + if (object.name != null) + message.name = String(object.name); + if (object.indexConfig != null) { + if (typeof object.indexConfig !== "object") + throw TypeError(".google.firestore.admin.v1.Field.indexConfig: object expected"); + message.indexConfig = $root.google.firestore.admin.v1.Field.IndexConfig.fromObject(object.indexConfig); + } + if (object.ttlConfig != null) { + if (typeof object.ttlConfig !== "object") + throw TypeError(".google.firestore.admin.v1.Field.ttlConfig: object expected"); + message.ttlConfig = $root.google.firestore.admin.v1.Field.TtlConfig.fromObject(object.ttlConfig); + } + return message; + }; + + /** + * Creates a plain object from a Field message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Field + * @static + * @param {google.firestore.admin.v1.Field} message Field + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Field.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.indexConfig = null; + object.ttlConfig = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.indexConfig != null && message.hasOwnProperty("indexConfig")) + object.indexConfig = $root.google.firestore.admin.v1.Field.IndexConfig.toObject(message.indexConfig, options); + if (message.ttlConfig != null && message.hasOwnProperty("ttlConfig")) + object.ttlConfig = $root.google.firestore.admin.v1.Field.TtlConfig.toObject(message.ttlConfig, options); + return object; + }; + + /** + * Converts this Field to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Field + * @instance + * @returns {Object.} JSON object + */ + Field.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Field + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Field + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Field.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Field"; + }; + + Field.IndexConfig = (function() { + + /** + * Properties of an IndexConfig. + * @memberof google.firestore.admin.v1.Field + * @interface IIndexConfig + * @property {Array.|null} [indexes] IndexConfig indexes + * @property {boolean|null} [usesAncestorConfig] IndexConfig usesAncestorConfig + * @property {string|null} [ancestorField] IndexConfig ancestorField + * @property {boolean|null} [reverting] IndexConfig reverting + */ + + /** + * Constructs a new IndexConfig. + * @memberof google.firestore.admin.v1.Field + * @classdesc Represents an IndexConfig. + * @implements IIndexConfig + * @constructor + * @param {google.firestore.admin.v1.Field.IIndexConfig=} [properties] Properties to set + */ + function IndexConfig(properties) { + this.indexes = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * IndexConfig indexes. + * @member {Array.} indexes + * @memberof google.firestore.admin.v1.Field.IndexConfig + * @instance + */ + IndexConfig.prototype.indexes = $util.emptyArray; + + /** + * IndexConfig usesAncestorConfig. + * @member {boolean} usesAncestorConfig + * @memberof google.firestore.admin.v1.Field.IndexConfig + * @instance + */ + IndexConfig.prototype.usesAncestorConfig = false; + + /** + * IndexConfig ancestorField. + * @member {string} ancestorField + * @memberof google.firestore.admin.v1.Field.IndexConfig + * @instance + */ + IndexConfig.prototype.ancestorField = ""; + + /** + * IndexConfig reverting. + * @member {boolean} reverting + * @memberof google.firestore.admin.v1.Field.IndexConfig + * @instance + */ + IndexConfig.prototype.reverting = false; + + /** + * Creates an IndexConfig message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Field.IndexConfig + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Field.IndexConfig} IndexConfig + */ + IndexConfig.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Field.IndexConfig) + return object; + var message = new $root.google.firestore.admin.v1.Field.IndexConfig(); + if (object.indexes) { + if (!Array.isArray(object.indexes)) + throw TypeError(".google.firestore.admin.v1.Field.IndexConfig.indexes: array expected"); + message.indexes = []; + for (var i = 0; i < object.indexes.length; ++i) { + if (typeof object.indexes[i] !== "object") + throw TypeError(".google.firestore.admin.v1.Field.IndexConfig.indexes: object expected"); + message.indexes[i] = $root.google.firestore.admin.v1.Index.fromObject(object.indexes[i]); + } + } + if (object.usesAncestorConfig != null) + message.usesAncestorConfig = Boolean(object.usesAncestorConfig); + if (object.ancestorField != null) + message.ancestorField = String(object.ancestorField); + if (object.reverting != null) + message.reverting = Boolean(object.reverting); + return message; + }; + + /** + * Creates a plain object from an IndexConfig message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Field.IndexConfig + * @static + * @param {google.firestore.admin.v1.Field.IndexConfig} message IndexConfig + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + IndexConfig.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.indexes = []; + if (options.defaults) { + object.usesAncestorConfig = false; + object.ancestorField = ""; + object.reverting = false; + } + if (message.indexes && message.indexes.length) { + object.indexes = []; + for (var j = 0; j < message.indexes.length; ++j) + object.indexes[j] = $root.google.firestore.admin.v1.Index.toObject(message.indexes[j], options); + } + if (message.usesAncestorConfig != null && message.hasOwnProperty("usesAncestorConfig")) + object.usesAncestorConfig = message.usesAncestorConfig; + if (message.ancestorField != null && message.hasOwnProperty("ancestorField")) + object.ancestorField = message.ancestorField; + if (message.reverting != null && message.hasOwnProperty("reverting")) + object.reverting = message.reverting; + return object; + }; + + /** + * Converts this IndexConfig to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Field.IndexConfig + * @instance + * @returns {Object.} JSON object + */ + IndexConfig.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for IndexConfig + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Field.IndexConfig + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + IndexConfig.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Field.IndexConfig"; + }; + + return IndexConfig; + })(); + + Field.TtlConfig = (function() { + + /** + * Properties of a TtlConfig. + * @memberof google.firestore.admin.v1.Field + * @interface ITtlConfig + * @property {google.firestore.admin.v1.Field.TtlConfig.State|null} [state] TtlConfig state + */ + + /** + * Constructs a new TtlConfig. + * @memberof google.firestore.admin.v1.Field + * @classdesc Represents a TtlConfig. + * @implements ITtlConfig + * @constructor + * @param {google.firestore.admin.v1.Field.ITtlConfig=} [properties] Properties to set + */ + function TtlConfig(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TtlConfig state. + * @member {google.firestore.admin.v1.Field.TtlConfig.State} state + * @memberof google.firestore.admin.v1.Field.TtlConfig + * @instance + */ + TtlConfig.prototype.state = 0; + + /** + * Creates a TtlConfig message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Field.TtlConfig + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Field.TtlConfig} TtlConfig + */ + TtlConfig.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Field.TtlConfig) + return object; + var message = new $root.google.firestore.admin.v1.Field.TtlConfig(); + switch (object.state) { + default: + if (typeof object.state === "number") { + message.state = object.state; + break; + } + break; + case "STATE_UNSPECIFIED": + case 0: + message.state = 0; + break; + case "CREATING": + case 1: + message.state = 1; + break; + case "ACTIVE": + case 2: + message.state = 2; + break; + case "NEEDS_REPAIR": + case 3: + message.state = 3; + break; + } + return message; + }; + + /** + * Creates a plain object from a TtlConfig message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Field.TtlConfig + * @static + * @param {google.firestore.admin.v1.Field.TtlConfig} message TtlConfig + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TtlConfig.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.state = options.enums === String ? "STATE_UNSPECIFIED" : 0; + if (message.state != null && message.hasOwnProperty("state")) + object.state = options.enums === String ? $root.google.firestore.admin.v1.Field.TtlConfig.State[message.state] === undefined ? message.state : $root.google.firestore.admin.v1.Field.TtlConfig.State[message.state] : message.state; + return object; + }; + + /** + * Converts this TtlConfig to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Field.TtlConfig + * @instance + * @returns {Object.} JSON object + */ + TtlConfig.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TtlConfig + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Field.TtlConfig + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TtlConfig.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Field.TtlConfig"; + }; + + /** + * State enum. + * @name google.firestore.admin.v1.Field.TtlConfig.State + * @enum {string} + * @property {string} STATE_UNSPECIFIED=STATE_UNSPECIFIED STATE_UNSPECIFIED value + * @property {string} CREATING=CREATING CREATING value + * @property {string} ACTIVE=ACTIVE ACTIVE value + * @property {string} NEEDS_REPAIR=NEEDS_REPAIR NEEDS_REPAIR value + */ + TtlConfig.State = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + values[valuesById[1] = "CREATING"] = "CREATING"; + values[valuesById[2] = "ACTIVE"] = "ACTIVE"; + values[valuesById[3] = "NEEDS_REPAIR"] = "NEEDS_REPAIR"; + return values; + })(); + + return TtlConfig; + })(); + + return Field; + })(); + + v1.Index = (function() { + + /** + * Properties of an Index. + * @memberof google.firestore.admin.v1 + * @interface IIndex + * @property {string|null} [name] Index name + * @property {google.firestore.admin.v1.Index.QueryScope|null} [queryScope] Index queryScope + * @property {google.firestore.admin.v1.Index.ApiScope|null} [apiScope] Index apiScope + * @property {Array.|null} [fields] Index fields + * @property {google.firestore.admin.v1.Index.State|null} [state] Index state + * @property {google.firestore.admin.v1.Index.Density|null} [density] Index density + * @property {boolean|null} [multikey] Index multikey + * @property {number|null} [shardCount] Index shardCount + */ + + /** + * Constructs a new Index. + * @memberof google.firestore.admin.v1 + * @classdesc Represents an Index. + * @implements IIndex + * @constructor + * @param {google.firestore.admin.v1.IIndex=} [properties] Properties to set + */ + function Index(properties) { + this.fields = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Index name. + * @member {string} name + * @memberof google.firestore.admin.v1.Index + * @instance + */ + Index.prototype.name = ""; + + /** + * Index queryScope. + * @member {google.firestore.admin.v1.Index.QueryScope} queryScope + * @memberof google.firestore.admin.v1.Index + * @instance + */ + Index.prototype.queryScope = 0; + + /** + * Index apiScope. + * @member {google.firestore.admin.v1.Index.ApiScope} apiScope + * @memberof google.firestore.admin.v1.Index + * @instance + */ + Index.prototype.apiScope = 0; + + /** + * Index fields. + * @member {Array.} fields + * @memberof google.firestore.admin.v1.Index + * @instance + */ + Index.prototype.fields = $util.emptyArray; + + /** + * Index state. + * @member {google.firestore.admin.v1.Index.State} state + * @memberof google.firestore.admin.v1.Index + * @instance + */ + Index.prototype.state = 0; + + /** + * Index density. + * @member {google.firestore.admin.v1.Index.Density} density + * @memberof google.firestore.admin.v1.Index + * @instance + */ + Index.prototype.density = 0; + + /** + * Index multikey. + * @member {boolean} multikey + * @memberof google.firestore.admin.v1.Index + * @instance + */ + Index.prototype.multikey = false; + + /** + * Index shardCount. + * @member {number} shardCount + * @memberof google.firestore.admin.v1.Index + * @instance + */ + Index.prototype.shardCount = 0; + + /** + * Creates an Index message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Index + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Index} Index + */ + Index.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Index) + return object; + var message = new $root.google.firestore.admin.v1.Index(); + if (object.name != null) + message.name = String(object.name); + switch (object.queryScope) { + default: + if (typeof object.queryScope === "number") { + message.queryScope = object.queryScope; + break; + } + break; + case "QUERY_SCOPE_UNSPECIFIED": + case 0: + message.queryScope = 0; + break; + case "COLLECTION": + case 1: + message.queryScope = 1; + break; + case "COLLECTION_GROUP": + case 2: + message.queryScope = 2; + break; + case "COLLECTION_RECURSIVE": + case 3: + message.queryScope = 3; + break; + } + switch (object.apiScope) { + default: + if (typeof object.apiScope === "number") { + message.apiScope = object.apiScope; + break; + } + break; + case "ANY_API": + case 0: + message.apiScope = 0; + break; + case "DATASTORE_MODE_API": + case 1: + message.apiScope = 1; + break; + case "MONGODB_COMPATIBLE_API": + case 2: + message.apiScope = 2; + break; + } + if (object.fields) { + if (!Array.isArray(object.fields)) + throw TypeError(".google.firestore.admin.v1.Index.fields: array expected"); + message.fields = []; + for (var i = 0; i < object.fields.length; ++i) { + if (typeof object.fields[i] !== "object") + throw TypeError(".google.firestore.admin.v1.Index.fields: object expected"); + message.fields[i] = $root.google.firestore.admin.v1.Index.IndexField.fromObject(object.fields[i]); + } + } + switch (object.state) { + default: + if (typeof object.state === "number") { + message.state = object.state; + break; + } + break; + case "STATE_UNSPECIFIED": + case 0: + message.state = 0; + break; + case "CREATING": + case 1: + message.state = 1; + break; + case "READY": + case 2: + message.state = 2; + break; + case "NEEDS_REPAIR": + case 3: + message.state = 3; + break; + } + switch (object.density) { + default: + if (typeof object.density === "number") { + message.density = object.density; + break; + } + break; + case "DENSITY_UNSPECIFIED": + case 0: + message.density = 0; + break; + case "SPARSE_ALL": + case 1: + message.density = 1; + break; + case "SPARSE_ANY": + case 2: + message.density = 2; + break; + case "DENSE": + case 3: + message.density = 3; + break; + } + if (object.multikey != null) + message.multikey = Boolean(object.multikey); + if (object.shardCount != null) + message.shardCount = object.shardCount | 0; + return message; + }; + + /** + * Creates a plain object from an Index message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Index + * @static + * @param {google.firestore.admin.v1.Index} message Index + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Index.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.fields = []; + if (options.defaults) { + object.name = ""; + object.queryScope = options.enums === String ? "QUERY_SCOPE_UNSPECIFIED" : 0; + object.state = options.enums === String ? "STATE_UNSPECIFIED" : 0; + object.apiScope = options.enums === String ? "ANY_API" : 0; + object.density = options.enums === String ? "DENSITY_UNSPECIFIED" : 0; + object.multikey = false; + object.shardCount = 0; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.queryScope != null && message.hasOwnProperty("queryScope")) + object.queryScope = options.enums === String ? $root.google.firestore.admin.v1.Index.QueryScope[message.queryScope] === undefined ? message.queryScope : $root.google.firestore.admin.v1.Index.QueryScope[message.queryScope] : message.queryScope; + if (message.fields && message.fields.length) { + object.fields = []; + for (var j = 0; j < message.fields.length; ++j) + object.fields[j] = $root.google.firestore.admin.v1.Index.IndexField.toObject(message.fields[j], options); + } + if (message.state != null && message.hasOwnProperty("state")) + object.state = options.enums === String ? $root.google.firestore.admin.v1.Index.State[message.state] === undefined ? message.state : $root.google.firestore.admin.v1.Index.State[message.state] : message.state; + if (message.apiScope != null && message.hasOwnProperty("apiScope")) + object.apiScope = options.enums === String ? $root.google.firestore.admin.v1.Index.ApiScope[message.apiScope] === undefined ? message.apiScope : $root.google.firestore.admin.v1.Index.ApiScope[message.apiScope] : message.apiScope; + if (message.density != null && message.hasOwnProperty("density")) + object.density = options.enums === String ? $root.google.firestore.admin.v1.Index.Density[message.density] === undefined ? message.density : $root.google.firestore.admin.v1.Index.Density[message.density] : message.density; + if (message.multikey != null && message.hasOwnProperty("multikey")) + object.multikey = message.multikey; + if (message.shardCount != null && message.hasOwnProperty("shardCount")) + object.shardCount = message.shardCount; + return object; + }; + + /** + * Converts this Index to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Index + * @instance + * @returns {Object.} JSON object + */ + Index.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Index + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Index + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Index.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Index"; + }; + + /** + * QueryScope enum. + * @name google.firestore.admin.v1.Index.QueryScope + * @enum {string} + * @property {string} QUERY_SCOPE_UNSPECIFIED=QUERY_SCOPE_UNSPECIFIED QUERY_SCOPE_UNSPECIFIED value + * @property {string} COLLECTION=COLLECTION COLLECTION value + * @property {string} COLLECTION_GROUP=COLLECTION_GROUP COLLECTION_GROUP value + * @property {string} COLLECTION_RECURSIVE=COLLECTION_RECURSIVE COLLECTION_RECURSIVE value + */ + Index.QueryScope = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "QUERY_SCOPE_UNSPECIFIED"] = "QUERY_SCOPE_UNSPECIFIED"; + values[valuesById[1] = "COLLECTION"] = "COLLECTION"; + values[valuesById[2] = "COLLECTION_GROUP"] = "COLLECTION_GROUP"; + values[valuesById[3] = "COLLECTION_RECURSIVE"] = "COLLECTION_RECURSIVE"; + return values; + })(); + + /** + * ApiScope enum. + * @name google.firestore.admin.v1.Index.ApiScope + * @enum {string} + * @property {string} ANY_API=ANY_API ANY_API value + * @property {string} DATASTORE_MODE_API=DATASTORE_MODE_API DATASTORE_MODE_API value + * @property {string} MONGODB_COMPATIBLE_API=MONGODB_COMPATIBLE_API MONGODB_COMPATIBLE_API value + */ + Index.ApiScope = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ANY_API"] = "ANY_API"; + values[valuesById[1] = "DATASTORE_MODE_API"] = "DATASTORE_MODE_API"; + values[valuesById[2] = "MONGODB_COMPATIBLE_API"] = "MONGODB_COMPATIBLE_API"; + return values; + })(); + + Index.IndexField = (function() { + + /** + * Properties of an IndexField. + * @memberof google.firestore.admin.v1.Index + * @interface IIndexField + * @property {string|null} [fieldPath] IndexField fieldPath + * @property {google.firestore.admin.v1.Index.IndexField.Order|null} [order] IndexField order + * @property {google.firestore.admin.v1.Index.IndexField.ArrayConfig|null} [arrayConfig] IndexField arrayConfig + * @property {google.firestore.admin.v1.Index.IndexField.IVectorConfig|null} [vectorConfig] IndexField vectorConfig + */ + + /** + * Constructs a new IndexField. + * @memberof google.firestore.admin.v1.Index + * @classdesc Represents an IndexField. + * @implements IIndexField + * @constructor + * @param {google.firestore.admin.v1.Index.IIndexField=} [properties] Properties to set + */ + function IndexField(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * IndexField fieldPath. + * @member {string} fieldPath + * @memberof google.firestore.admin.v1.Index.IndexField + * @instance + */ + IndexField.prototype.fieldPath = ""; + + /** + * IndexField order. + * @member {google.firestore.admin.v1.Index.IndexField.Order|null|undefined} order + * @memberof google.firestore.admin.v1.Index.IndexField + * @instance + */ + IndexField.prototype.order = null; + + /** + * IndexField arrayConfig. + * @member {google.firestore.admin.v1.Index.IndexField.ArrayConfig|null|undefined} arrayConfig + * @memberof google.firestore.admin.v1.Index.IndexField + * @instance + */ + IndexField.prototype.arrayConfig = null; + + /** + * IndexField vectorConfig. + * @member {google.firestore.admin.v1.Index.IndexField.IVectorConfig|null|undefined} vectorConfig + * @memberof google.firestore.admin.v1.Index.IndexField + * @instance + */ + IndexField.prototype.vectorConfig = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * IndexField valueMode. + * @member {"order"|"arrayConfig"|"vectorConfig"|undefined} valueMode + * @memberof google.firestore.admin.v1.Index.IndexField + * @instance + */ + Object.defineProperty(IndexField.prototype, "valueMode", { + get: $util.oneOfGetter($oneOfFields = ["order", "arrayConfig", "vectorConfig"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates an IndexField message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Index.IndexField + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Index.IndexField} IndexField + */ + IndexField.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Index.IndexField) + return object; + var message = new $root.google.firestore.admin.v1.Index.IndexField(); + if (object.fieldPath != null) + message.fieldPath = String(object.fieldPath); + switch (object.order) { + default: + if (typeof object.order === "number") { + message.order = object.order; + break; + } + break; + case "ORDER_UNSPECIFIED": + case 0: + message.order = 0; + break; + case "ASCENDING": + case 1: + message.order = 1; + break; + case "DESCENDING": + case 2: + message.order = 2; + break; + } + switch (object.arrayConfig) { + default: + if (typeof object.arrayConfig === "number") { + message.arrayConfig = object.arrayConfig; + break; + } + break; + case "ARRAY_CONFIG_UNSPECIFIED": + case 0: + message.arrayConfig = 0; + break; + case "CONTAINS": + case 1: + message.arrayConfig = 1; + break; + } + if (object.vectorConfig != null) { + if (typeof object.vectorConfig !== "object") + throw TypeError(".google.firestore.admin.v1.Index.IndexField.vectorConfig: object expected"); + message.vectorConfig = $root.google.firestore.admin.v1.Index.IndexField.VectorConfig.fromObject(object.vectorConfig); + } + return message; + }; + + /** + * Creates a plain object from an IndexField message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Index.IndexField + * @static + * @param {google.firestore.admin.v1.Index.IndexField} message IndexField + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + IndexField.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.fieldPath = ""; + if (message.fieldPath != null && message.hasOwnProperty("fieldPath")) + object.fieldPath = message.fieldPath; + if (message.order != null && message.hasOwnProperty("order")) { + object.order = options.enums === String ? $root.google.firestore.admin.v1.Index.IndexField.Order[message.order] === undefined ? message.order : $root.google.firestore.admin.v1.Index.IndexField.Order[message.order] : message.order; + if (options.oneofs) + object.valueMode = "order"; + } + if (message.arrayConfig != null && message.hasOwnProperty("arrayConfig")) { + object.arrayConfig = options.enums === String ? $root.google.firestore.admin.v1.Index.IndexField.ArrayConfig[message.arrayConfig] === undefined ? message.arrayConfig : $root.google.firestore.admin.v1.Index.IndexField.ArrayConfig[message.arrayConfig] : message.arrayConfig; + if (options.oneofs) + object.valueMode = "arrayConfig"; + } + if (message.vectorConfig != null && message.hasOwnProperty("vectorConfig")) { + object.vectorConfig = $root.google.firestore.admin.v1.Index.IndexField.VectorConfig.toObject(message.vectorConfig, options); + if (options.oneofs) + object.valueMode = "vectorConfig"; + } + return object; + }; + + /** + * Converts this IndexField to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Index.IndexField + * @instance + * @returns {Object.} JSON object + */ + IndexField.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for IndexField + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Index.IndexField + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + IndexField.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Index.IndexField"; + }; + + /** + * Order enum. + * @name google.firestore.admin.v1.Index.IndexField.Order + * @enum {string} + * @property {string} ORDER_UNSPECIFIED=ORDER_UNSPECIFIED ORDER_UNSPECIFIED value + * @property {string} ASCENDING=ASCENDING ASCENDING value + * @property {string} DESCENDING=DESCENDING DESCENDING value + */ + IndexField.Order = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ORDER_UNSPECIFIED"] = "ORDER_UNSPECIFIED"; + values[valuesById[1] = "ASCENDING"] = "ASCENDING"; + values[valuesById[2] = "DESCENDING"] = "DESCENDING"; + return values; + })(); + + /** + * ArrayConfig enum. + * @name google.firestore.admin.v1.Index.IndexField.ArrayConfig + * @enum {string} + * @property {string} ARRAY_CONFIG_UNSPECIFIED=ARRAY_CONFIG_UNSPECIFIED ARRAY_CONFIG_UNSPECIFIED value + * @property {string} CONTAINS=CONTAINS CONTAINS value + */ + IndexField.ArrayConfig = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ARRAY_CONFIG_UNSPECIFIED"] = "ARRAY_CONFIG_UNSPECIFIED"; + values[valuesById[1] = "CONTAINS"] = "CONTAINS"; + return values; + })(); + + IndexField.VectorConfig = (function() { + + /** + * Properties of a VectorConfig. + * @memberof google.firestore.admin.v1.Index.IndexField + * @interface IVectorConfig + * @property {number|null} [dimension] VectorConfig dimension + * @property {google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex|null} [flat] VectorConfig flat + */ + + /** + * Constructs a new VectorConfig. + * @memberof google.firestore.admin.v1.Index.IndexField + * @classdesc Represents a VectorConfig. + * @implements IVectorConfig + * @constructor + * @param {google.firestore.admin.v1.Index.IndexField.IVectorConfig=} [properties] Properties to set + */ + function VectorConfig(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * VectorConfig dimension. + * @member {number} dimension + * @memberof google.firestore.admin.v1.Index.IndexField.VectorConfig + * @instance + */ + VectorConfig.prototype.dimension = 0; + + /** + * VectorConfig flat. + * @member {google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex|null|undefined} flat + * @memberof google.firestore.admin.v1.Index.IndexField.VectorConfig + * @instance + */ + VectorConfig.prototype.flat = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * VectorConfig type. + * @member {"flat"|undefined} type + * @memberof google.firestore.admin.v1.Index.IndexField.VectorConfig + * @instance + */ + Object.defineProperty(VectorConfig.prototype, "type", { + get: $util.oneOfGetter($oneOfFields = ["flat"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a VectorConfig message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Index.IndexField.VectorConfig + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Index.IndexField.VectorConfig} VectorConfig + */ + VectorConfig.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Index.IndexField.VectorConfig) + return object; + var message = new $root.google.firestore.admin.v1.Index.IndexField.VectorConfig(); + if (object.dimension != null) + message.dimension = object.dimension | 0; + if (object.flat != null) { + if (typeof object.flat !== "object") + throw TypeError(".google.firestore.admin.v1.Index.IndexField.VectorConfig.flat: object expected"); + message.flat = $root.google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex.fromObject(object.flat); + } + return message; + }; + + /** + * Creates a plain object from a VectorConfig message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Index.IndexField.VectorConfig + * @static + * @param {google.firestore.admin.v1.Index.IndexField.VectorConfig} message VectorConfig + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + VectorConfig.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.dimension = 0; + if (message.dimension != null && message.hasOwnProperty("dimension")) + object.dimension = message.dimension; + if (message.flat != null && message.hasOwnProperty("flat")) { + object.flat = $root.google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex.toObject(message.flat, options); + if (options.oneofs) + object.type = "flat"; + } + return object; + }; + + /** + * Converts this VectorConfig to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Index.IndexField.VectorConfig + * @instance + * @returns {Object.} JSON object + */ + VectorConfig.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for VectorConfig + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Index.IndexField.VectorConfig + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + VectorConfig.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Index.IndexField.VectorConfig"; + }; + + VectorConfig.FlatIndex = (function() { + + /** + * Properties of a FlatIndex. + * @memberof google.firestore.admin.v1.Index.IndexField.VectorConfig + * @interface IFlatIndex + */ + + /** + * Constructs a new FlatIndex. + * @memberof google.firestore.admin.v1.Index.IndexField.VectorConfig + * @classdesc Represents a FlatIndex. + * @implements IFlatIndex + * @constructor + * @param {google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex=} [properties] Properties to set + */ + function FlatIndex(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a FlatIndex message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex} FlatIndex + */ + FlatIndex.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex) + return object; + return new $root.google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex(); + }; + + /** + * Creates a plain object from a FlatIndex message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex + * @static + * @param {google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex} message FlatIndex + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FlatIndex.toObject = function toObject() { + return {}; + }; + + /** + * Converts this FlatIndex to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex + * @instance + * @returns {Object.} JSON object + */ + FlatIndex.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FlatIndex + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FlatIndex.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex"; + }; + + return FlatIndex; + })(); + + return VectorConfig; + })(); + + return IndexField; + })(); + + /** + * State enum. + * @name google.firestore.admin.v1.Index.State + * @enum {string} + * @property {string} STATE_UNSPECIFIED=STATE_UNSPECIFIED STATE_UNSPECIFIED value + * @property {string} CREATING=CREATING CREATING value + * @property {string} READY=READY READY value + * @property {string} NEEDS_REPAIR=NEEDS_REPAIR NEEDS_REPAIR value + */ + Index.State = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + values[valuesById[1] = "CREATING"] = "CREATING"; + values[valuesById[2] = "READY"] = "READY"; + values[valuesById[3] = "NEEDS_REPAIR"] = "NEEDS_REPAIR"; + return values; + })(); + + /** + * Density enum. + * @name google.firestore.admin.v1.Index.Density + * @enum {string} + * @property {string} DENSITY_UNSPECIFIED=DENSITY_UNSPECIFIED DENSITY_UNSPECIFIED value + * @property {string} SPARSE_ALL=SPARSE_ALL SPARSE_ALL value + * @property {string} SPARSE_ANY=SPARSE_ANY SPARSE_ANY value + * @property {string} DENSE=DENSE DENSE value + */ + Index.Density = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DENSITY_UNSPECIFIED"] = "DENSITY_UNSPECIFIED"; + values[valuesById[1] = "SPARSE_ALL"] = "SPARSE_ALL"; + values[valuesById[2] = "SPARSE_ANY"] = "SPARSE_ANY"; + values[valuesById[3] = "DENSE"] = "DENSE"; + return values; + })(); + + return Index; + })(); + + v1.FirestoreAdmin = (function() { + + /** + * Constructs a new FirestoreAdmin service. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a FirestoreAdmin + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function FirestoreAdmin(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (FirestoreAdmin.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = FirestoreAdmin; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createIndex}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef CreateIndexCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls CreateIndex. + * @function createIndex + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.ICreateIndexRequest} request CreateIndexRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.CreateIndexCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.createIndex = function createIndex(request, callback) { + return this.rpcCall(createIndex, $root.google.firestore.admin.v1.CreateIndexRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "CreateIndex" }); + + /** + * Calls CreateIndex. + * @function createIndex + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.ICreateIndexRequest} request CreateIndexRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listIndexes}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef ListIndexesCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.ListIndexesResponse} [response] ListIndexesResponse + */ + + /** + * Calls ListIndexes. + * @function listIndexes + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IListIndexesRequest} request ListIndexesRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.ListIndexesCallback} callback Node-style callback called with the error, if any, and ListIndexesResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.listIndexes = function listIndexes(request, callback) { + return this.rpcCall(listIndexes, $root.google.firestore.admin.v1.ListIndexesRequest, $root.google.firestore.admin.v1.ListIndexesResponse, request, callback); + }, "name", { value: "ListIndexes" }); + + /** + * Calls ListIndexes. + * @function listIndexes + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IListIndexesRequest} request ListIndexesRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getIndex}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef GetIndexCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.Index} [response] Index + */ + + /** + * Calls GetIndex. + * @function getIndex + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IGetIndexRequest} request GetIndexRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.GetIndexCallback} callback Node-style callback called with the error, if any, and Index + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.getIndex = function getIndex(request, callback) { + return this.rpcCall(getIndex, $root.google.firestore.admin.v1.GetIndexRequest, $root.google.firestore.admin.v1.Index, request, callback); + }, "name", { value: "GetIndex" }); + + /** + * Calls GetIndex. + * @function getIndex + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IGetIndexRequest} request GetIndexRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteIndex}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef DeleteIndexCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteIndex. + * @function deleteIndex + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IDeleteIndexRequest} request DeleteIndexRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.DeleteIndexCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.deleteIndex = function deleteIndex(request, callback) { + return this.rpcCall(deleteIndex, $root.google.firestore.admin.v1.DeleteIndexRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteIndex" }); + + /** + * Calls DeleteIndex. + * @function deleteIndex + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IDeleteIndexRequest} request DeleteIndexRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getField}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef GetFieldCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.Field} [response] Field + */ + + /** + * Calls GetField. + * @function getField + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IGetFieldRequest} request GetFieldRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.GetFieldCallback} callback Node-style callback called with the error, if any, and Field + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.getField = function getField(request, callback) { + return this.rpcCall(getField, $root.google.firestore.admin.v1.GetFieldRequest, $root.google.firestore.admin.v1.Field, request, callback); + }, "name", { value: "GetField" }); + + /** + * Calls GetField. + * @function getField + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IGetFieldRequest} request GetFieldRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateField}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef UpdateFieldCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls UpdateField. + * @function updateField + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IUpdateFieldRequest} request UpdateFieldRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.UpdateFieldCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.updateField = function updateField(request, callback) { + return this.rpcCall(updateField, $root.google.firestore.admin.v1.UpdateFieldRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "UpdateField" }); + + /** + * Calls UpdateField. + * @function updateField + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IUpdateFieldRequest} request UpdateFieldRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listFields}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef ListFieldsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.ListFieldsResponse} [response] ListFieldsResponse + */ + + /** + * Calls ListFields. + * @function listFields + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IListFieldsRequest} request ListFieldsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.ListFieldsCallback} callback Node-style callback called with the error, if any, and ListFieldsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.listFields = function listFields(request, callback) { + return this.rpcCall(listFields, $root.google.firestore.admin.v1.ListFieldsRequest, $root.google.firestore.admin.v1.ListFieldsResponse, request, callback); + }, "name", { value: "ListFields" }); + + /** + * Calls ListFields. + * @function listFields + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IListFieldsRequest} request ListFieldsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#exportDocuments}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef ExportDocumentsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls ExportDocuments. + * @function exportDocuments + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IExportDocumentsRequest} request ExportDocumentsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.ExportDocumentsCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.exportDocuments = function exportDocuments(request, callback) { + return this.rpcCall(exportDocuments, $root.google.firestore.admin.v1.ExportDocumentsRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "ExportDocuments" }); + + /** + * Calls ExportDocuments. + * @function exportDocuments + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IExportDocumentsRequest} request ExportDocumentsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#importDocuments}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef ImportDocumentsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls ImportDocuments. + * @function importDocuments + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IImportDocumentsRequest} request ImportDocumentsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.ImportDocumentsCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.importDocuments = function importDocuments(request, callback) { + return this.rpcCall(importDocuments, $root.google.firestore.admin.v1.ImportDocumentsRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "ImportDocuments" }); + + /** + * Calls ImportDocuments. + * @function importDocuments + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IImportDocumentsRequest} request ImportDocumentsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#bulkDeleteDocuments}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef BulkDeleteDocumentsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls BulkDeleteDocuments. + * @function bulkDeleteDocuments + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IBulkDeleteDocumentsRequest} request BulkDeleteDocumentsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocumentsCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.bulkDeleteDocuments = function bulkDeleteDocuments(request, callback) { + return this.rpcCall(bulkDeleteDocuments, $root.google.firestore.admin.v1.BulkDeleteDocumentsRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "BulkDeleteDocuments" }); + + /** + * Calls BulkDeleteDocuments. + * @function bulkDeleteDocuments + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IBulkDeleteDocumentsRequest} request BulkDeleteDocumentsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createDatabase}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef CreateDatabaseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls CreateDatabase. + * @function createDatabase + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.ICreateDatabaseRequest} request CreateDatabaseRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.CreateDatabaseCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.createDatabase = function createDatabase(request, callback) { + return this.rpcCall(createDatabase, $root.google.firestore.admin.v1.CreateDatabaseRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "CreateDatabase" }); + + /** + * Calls CreateDatabase. + * @function createDatabase + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.ICreateDatabaseRequest} request CreateDatabaseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getDatabase}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef GetDatabaseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.Database} [response] Database + */ + + /** + * Calls GetDatabase. + * @function getDatabase + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IGetDatabaseRequest} request GetDatabaseRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.GetDatabaseCallback} callback Node-style callback called with the error, if any, and Database + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.getDatabase = function getDatabase(request, callback) { + return this.rpcCall(getDatabase, $root.google.firestore.admin.v1.GetDatabaseRequest, $root.google.firestore.admin.v1.Database, request, callback); + }, "name", { value: "GetDatabase" }); + + /** + * Calls GetDatabase. + * @function getDatabase + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IGetDatabaseRequest} request GetDatabaseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listDatabases}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef ListDatabasesCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.ListDatabasesResponse} [response] ListDatabasesResponse + */ + + /** + * Calls ListDatabases. + * @function listDatabases + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IListDatabasesRequest} request ListDatabasesRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.ListDatabasesCallback} callback Node-style callback called with the error, if any, and ListDatabasesResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.listDatabases = function listDatabases(request, callback) { + return this.rpcCall(listDatabases, $root.google.firestore.admin.v1.ListDatabasesRequest, $root.google.firestore.admin.v1.ListDatabasesResponse, request, callback); + }, "name", { value: "ListDatabases" }); + + /** + * Calls ListDatabases. + * @function listDatabases + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IListDatabasesRequest} request ListDatabasesRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateDatabase}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef UpdateDatabaseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls UpdateDatabase. + * @function updateDatabase + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IUpdateDatabaseRequest} request UpdateDatabaseRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.UpdateDatabaseCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.updateDatabase = function updateDatabase(request, callback) { + return this.rpcCall(updateDatabase, $root.google.firestore.admin.v1.UpdateDatabaseRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "UpdateDatabase" }); + + /** + * Calls UpdateDatabase. + * @function updateDatabase + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IUpdateDatabaseRequest} request UpdateDatabaseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteDatabase}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef DeleteDatabaseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls DeleteDatabase. + * @function deleteDatabase + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IDeleteDatabaseRequest} request DeleteDatabaseRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.DeleteDatabaseCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.deleteDatabase = function deleteDatabase(request, callback) { + return this.rpcCall(deleteDatabase, $root.google.firestore.admin.v1.DeleteDatabaseRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "DeleteDatabase" }); + + /** + * Calls DeleteDatabase. + * @function deleteDatabase + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IDeleteDatabaseRequest} request DeleteDatabaseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createUserCreds}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef CreateUserCredsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.UserCreds} [response] UserCreds + */ + + /** + * Calls CreateUserCreds. + * @function createUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.ICreateUserCredsRequest} request CreateUserCredsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.CreateUserCredsCallback} callback Node-style callback called with the error, if any, and UserCreds + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.createUserCreds = function createUserCreds(request, callback) { + return this.rpcCall(createUserCreds, $root.google.firestore.admin.v1.CreateUserCredsRequest, $root.google.firestore.admin.v1.UserCreds, request, callback); + }, "name", { value: "CreateUserCreds" }); + + /** + * Calls CreateUserCreds. + * @function createUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.ICreateUserCredsRequest} request CreateUserCredsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getUserCreds}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef GetUserCredsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.UserCreds} [response] UserCreds + */ + + /** + * Calls GetUserCreds. + * @function getUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IGetUserCredsRequest} request GetUserCredsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.GetUserCredsCallback} callback Node-style callback called with the error, if any, and UserCreds + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.getUserCreds = function getUserCreds(request, callback) { + return this.rpcCall(getUserCreds, $root.google.firestore.admin.v1.GetUserCredsRequest, $root.google.firestore.admin.v1.UserCreds, request, callback); + }, "name", { value: "GetUserCreds" }); + + /** + * Calls GetUserCreds. + * @function getUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IGetUserCredsRequest} request GetUserCredsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listUserCreds}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef ListUserCredsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.ListUserCredsResponse} [response] ListUserCredsResponse + */ + + /** + * Calls ListUserCreds. + * @function listUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IListUserCredsRequest} request ListUserCredsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.ListUserCredsCallback} callback Node-style callback called with the error, if any, and ListUserCredsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.listUserCreds = function listUserCreds(request, callback) { + return this.rpcCall(listUserCreds, $root.google.firestore.admin.v1.ListUserCredsRequest, $root.google.firestore.admin.v1.ListUserCredsResponse, request, callback); + }, "name", { value: "ListUserCreds" }); + + /** + * Calls ListUserCreds. + * @function listUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IListUserCredsRequest} request ListUserCredsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#enableUserCreds}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef EnableUserCredsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.UserCreds} [response] UserCreds + */ + + /** + * Calls EnableUserCreds. + * @function enableUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IEnableUserCredsRequest} request EnableUserCredsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.EnableUserCredsCallback} callback Node-style callback called with the error, if any, and UserCreds + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.enableUserCreds = function enableUserCreds(request, callback) { + return this.rpcCall(enableUserCreds, $root.google.firestore.admin.v1.EnableUserCredsRequest, $root.google.firestore.admin.v1.UserCreds, request, callback); + }, "name", { value: "EnableUserCreds" }); + + /** + * Calls EnableUserCreds. + * @function enableUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IEnableUserCredsRequest} request EnableUserCredsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#disableUserCreds}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef DisableUserCredsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.UserCreds} [response] UserCreds + */ + + /** + * Calls DisableUserCreds. + * @function disableUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IDisableUserCredsRequest} request DisableUserCredsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.DisableUserCredsCallback} callback Node-style callback called with the error, if any, and UserCreds + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.disableUserCreds = function disableUserCreds(request, callback) { + return this.rpcCall(disableUserCreds, $root.google.firestore.admin.v1.DisableUserCredsRequest, $root.google.firestore.admin.v1.UserCreds, request, callback); + }, "name", { value: "DisableUserCreds" }); + + /** + * Calls DisableUserCreds. + * @function disableUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IDisableUserCredsRequest} request DisableUserCredsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#resetUserPassword}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef ResetUserPasswordCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.UserCreds} [response] UserCreds + */ + + /** + * Calls ResetUserPassword. + * @function resetUserPassword + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IResetUserPasswordRequest} request ResetUserPasswordRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.ResetUserPasswordCallback} callback Node-style callback called with the error, if any, and UserCreds + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.resetUserPassword = function resetUserPassword(request, callback) { + return this.rpcCall(resetUserPassword, $root.google.firestore.admin.v1.ResetUserPasswordRequest, $root.google.firestore.admin.v1.UserCreds, request, callback); + }, "name", { value: "ResetUserPassword" }); + + /** + * Calls ResetUserPassword. + * @function resetUserPassword + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IResetUserPasswordRequest} request ResetUserPasswordRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteUserCreds}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef DeleteUserCredsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteUserCreds. + * @function deleteUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IDeleteUserCredsRequest} request DeleteUserCredsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.DeleteUserCredsCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.deleteUserCreds = function deleteUserCreds(request, callback) { + return this.rpcCall(deleteUserCreds, $root.google.firestore.admin.v1.DeleteUserCredsRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteUserCreds" }); + + /** + * Calls DeleteUserCreds. + * @function deleteUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IDeleteUserCredsRequest} request DeleteUserCredsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getBackup}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef GetBackupCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.Backup} [response] Backup + */ + + /** + * Calls GetBackup. + * @function getBackup + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IGetBackupRequest} request GetBackupRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.GetBackupCallback} callback Node-style callback called with the error, if any, and Backup + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.getBackup = function getBackup(request, callback) { + return this.rpcCall(getBackup, $root.google.firestore.admin.v1.GetBackupRequest, $root.google.firestore.admin.v1.Backup, request, callback); + }, "name", { value: "GetBackup" }); + + /** + * Calls GetBackup. + * @function getBackup + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IGetBackupRequest} request GetBackupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listBackups}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef ListBackupsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.ListBackupsResponse} [response] ListBackupsResponse + */ + + /** + * Calls ListBackups. + * @function listBackups + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IListBackupsRequest} request ListBackupsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.ListBackupsCallback} callback Node-style callback called with the error, if any, and ListBackupsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.listBackups = function listBackups(request, callback) { + return this.rpcCall(listBackups, $root.google.firestore.admin.v1.ListBackupsRequest, $root.google.firestore.admin.v1.ListBackupsResponse, request, callback); + }, "name", { value: "ListBackups" }); + + /** + * Calls ListBackups. + * @function listBackups + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IListBackupsRequest} request ListBackupsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteBackup}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef DeleteBackupCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteBackup. + * @function deleteBackup + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IDeleteBackupRequest} request DeleteBackupRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.DeleteBackupCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.deleteBackup = function deleteBackup(request, callback) { + return this.rpcCall(deleteBackup, $root.google.firestore.admin.v1.DeleteBackupRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteBackup" }); + + /** + * Calls DeleteBackup. + * @function deleteBackup + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IDeleteBackupRequest} request DeleteBackupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#restoreDatabase}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef RestoreDatabaseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls RestoreDatabase. + * @function restoreDatabase + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IRestoreDatabaseRequest} request RestoreDatabaseRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.RestoreDatabaseCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.restoreDatabase = function restoreDatabase(request, callback) { + return this.rpcCall(restoreDatabase, $root.google.firestore.admin.v1.RestoreDatabaseRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "RestoreDatabase" }); + + /** + * Calls RestoreDatabase. + * @function restoreDatabase + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IRestoreDatabaseRequest} request RestoreDatabaseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createBackupSchedule}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef CreateBackupScheduleCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.BackupSchedule} [response] BackupSchedule + */ + + /** + * Calls CreateBackupSchedule. + * @function createBackupSchedule + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.ICreateBackupScheduleRequest} request CreateBackupScheduleRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.CreateBackupScheduleCallback} callback Node-style callback called with the error, if any, and BackupSchedule + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.createBackupSchedule = function createBackupSchedule(request, callback) { + return this.rpcCall(createBackupSchedule, $root.google.firestore.admin.v1.CreateBackupScheduleRequest, $root.google.firestore.admin.v1.BackupSchedule, request, callback); + }, "name", { value: "CreateBackupSchedule" }); + + /** + * Calls CreateBackupSchedule. + * @function createBackupSchedule + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.ICreateBackupScheduleRequest} request CreateBackupScheduleRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getBackupSchedule}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef GetBackupScheduleCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.BackupSchedule} [response] BackupSchedule + */ + + /** + * Calls GetBackupSchedule. + * @function getBackupSchedule + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IGetBackupScheduleRequest} request GetBackupScheduleRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.GetBackupScheduleCallback} callback Node-style callback called with the error, if any, and BackupSchedule + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.getBackupSchedule = function getBackupSchedule(request, callback) { + return this.rpcCall(getBackupSchedule, $root.google.firestore.admin.v1.GetBackupScheduleRequest, $root.google.firestore.admin.v1.BackupSchedule, request, callback); + }, "name", { value: "GetBackupSchedule" }); + + /** + * Calls GetBackupSchedule. + * @function getBackupSchedule + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IGetBackupScheduleRequest} request GetBackupScheduleRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listBackupSchedules}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef ListBackupSchedulesCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.ListBackupSchedulesResponse} [response] ListBackupSchedulesResponse + */ + + /** + * Calls ListBackupSchedules. + * @function listBackupSchedules + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IListBackupSchedulesRequest} request ListBackupSchedulesRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.ListBackupSchedulesCallback} callback Node-style callback called with the error, if any, and ListBackupSchedulesResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.listBackupSchedules = function listBackupSchedules(request, callback) { + return this.rpcCall(listBackupSchedules, $root.google.firestore.admin.v1.ListBackupSchedulesRequest, $root.google.firestore.admin.v1.ListBackupSchedulesResponse, request, callback); + }, "name", { value: "ListBackupSchedules" }); + + /** + * Calls ListBackupSchedules. + * @function listBackupSchedules + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IListBackupSchedulesRequest} request ListBackupSchedulesRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateBackupSchedule}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef UpdateBackupScheduleCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.BackupSchedule} [response] BackupSchedule + */ + + /** + * Calls UpdateBackupSchedule. + * @function updateBackupSchedule + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IUpdateBackupScheduleRequest} request UpdateBackupScheduleRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.UpdateBackupScheduleCallback} callback Node-style callback called with the error, if any, and BackupSchedule + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.updateBackupSchedule = function updateBackupSchedule(request, callback) { + return this.rpcCall(updateBackupSchedule, $root.google.firestore.admin.v1.UpdateBackupScheduleRequest, $root.google.firestore.admin.v1.BackupSchedule, request, callback); + }, "name", { value: "UpdateBackupSchedule" }); + + /** + * Calls UpdateBackupSchedule. + * @function updateBackupSchedule + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IUpdateBackupScheduleRequest} request UpdateBackupScheduleRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteBackupSchedule}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef DeleteBackupScheduleCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteBackupSchedule. + * @function deleteBackupSchedule + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IDeleteBackupScheduleRequest} request DeleteBackupScheduleRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.DeleteBackupScheduleCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.deleteBackupSchedule = function deleteBackupSchedule(request, callback) { + return this.rpcCall(deleteBackupSchedule, $root.google.firestore.admin.v1.DeleteBackupScheduleRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteBackupSchedule" }); + + /** + * Calls DeleteBackupSchedule. + * @function deleteBackupSchedule + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IDeleteBackupScheduleRequest} request DeleteBackupScheduleRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#cloneDatabase}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef CloneDatabaseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls CloneDatabase. + * @function cloneDatabase + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.ICloneDatabaseRequest} request CloneDatabaseRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.CloneDatabaseCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.cloneDatabase = function cloneDatabase(request, callback) { + return this.rpcCall(cloneDatabase, $root.google.firestore.admin.v1.CloneDatabaseRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "CloneDatabase" }); + + /** + * Calls CloneDatabase. + * @function cloneDatabase + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.ICloneDatabaseRequest} request CloneDatabaseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return FirestoreAdmin; + })(); + + v1.ListDatabasesRequest = (function() { + + /** + * Properties of a ListDatabasesRequest. + * @memberof google.firestore.admin.v1 + * @interface IListDatabasesRequest + * @property {string|null} [parent] ListDatabasesRequest parent + * @property {boolean|null} [showDeleted] ListDatabasesRequest showDeleted + */ + + /** + * Constructs a new ListDatabasesRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a ListDatabasesRequest. + * @implements IListDatabasesRequest + * @constructor + * @param {google.firestore.admin.v1.IListDatabasesRequest=} [properties] Properties to set + */ + function ListDatabasesRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListDatabasesRequest parent. + * @member {string} parent + * @memberof google.firestore.admin.v1.ListDatabasesRequest + * @instance + */ + ListDatabasesRequest.prototype.parent = ""; + + /** + * ListDatabasesRequest showDeleted. + * @member {boolean} showDeleted + * @memberof google.firestore.admin.v1.ListDatabasesRequest + * @instance + */ + ListDatabasesRequest.prototype.showDeleted = false; + + /** + * Creates a ListDatabasesRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ListDatabasesRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ListDatabasesRequest} ListDatabasesRequest + */ + ListDatabasesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ListDatabasesRequest) + return object; + var message = new $root.google.firestore.admin.v1.ListDatabasesRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.showDeleted != null) + message.showDeleted = Boolean(object.showDeleted); + return message; + }; + + /** + * Creates a plain object from a ListDatabasesRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ListDatabasesRequest + * @static + * @param {google.firestore.admin.v1.ListDatabasesRequest} message ListDatabasesRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListDatabasesRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.showDeleted = false; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.showDeleted != null && message.hasOwnProperty("showDeleted")) + object.showDeleted = message.showDeleted; + return object; + }; + + /** + * Converts this ListDatabasesRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ListDatabasesRequest + * @instance + * @returns {Object.} JSON object + */ + ListDatabasesRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListDatabasesRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ListDatabasesRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListDatabasesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ListDatabasesRequest"; + }; + + return ListDatabasesRequest; + })(); + + v1.CreateDatabaseRequest = (function() { + + /** + * Properties of a CreateDatabaseRequest. + * @memberof google.firestore.admin.v1 + * @interface ICreateDatabaseRequest + * @property {string|null} [parent] CreateDatabaseRequest parent + * @property {google.firestore.admin.v1.IDatabase|null} [database] CreateDatabaseRequest database + * @property {string|null} [databaseId] CreateDatabaseRequest databaseId + */ + + /** + * Constructs a new CreateDatabaseRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a CreateDatabaseRequest. + * @implements ICreateDatabaseRequest + * @constructor + * @param {google.firestore.admin.v1.ICreateDatabaseRequest=} [properties] Properties to set + */ + function CreateDatabaseRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateDatabaseRequest parent. + * @member {string} parent + * @memberof google.firestore.admin.v1.CreateDatabaseRequest + * @instance + */ + CreateDatabaseRequest.prototype.parent = ""; + + /** + * CreateDatabaseRequest database. + * @member {google.firestore.admin.v1.IDatabase|null|undefined} database + * @memberof google.firestore.admin.v1.CreateDatabaseRequest + * @instance + */ + CreateDatabaseRequest.prototype.database = null; + + /** + * CreateDatabaseRequest databaseId. + * @member {string} databaseId + * @memberof google.firestore.admin.v1.CreateDatabaseRequest + * @instance + */ + CreateDatabaseRequest.prototype.databaseId = ""; + + /** + * Creates a CreateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.CreateDatabaseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.CreateDatabaseRequest} CreateDatabaseRequest + */ + CreateDatabaseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.CreateDatabaseRequest) + return object; + var message = new $root.google.firestore.admin.v1.CreateDatabaseRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.database != null) { + if (typeof object.database !== "object") + throw TypeError(".google.firestore.admin.v1.CreateDatabaseRequest.database: object expected"); + message.database = $root.google.firestore.admin.v1.Database.fromObject(object.database); + } + if (object.databaseId != null) + message.databaseId = String(object.databaseId); + return message; + }; + + /** + * Creates a plain object from a CreateDatabaseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.CreateDatabaseRequest + * @static + * @param {google.firestore.admin.v1.CreateDatabaseRequest} message CreateDatabaseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateDatabaseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.database = null; + object.databaseId = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.database != null && message.hasOwnProperty("database")) + object.database = $root.google.firestore.admin.v1.Database.toObject(message.database, options); + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + object.databaseId = message.databaseId; + return object; + }; + + /** + * Converts this CreateDatabaseRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.CreateDatabaseRequest + * @instance + * @returns {Object.} JSON object + */ + CreateDatabaseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateDatabaseRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.CreateDatabaseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateDatabaseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.CreateDatabaseRequest"; + }; + + return CreateDatabaseRequest; + })(); + + v1.CreateDatabaseMetadata = (function() { + + /** + * Properties of a CreateDatabaseMetadata. + * @memberof google.firestore.admin.v1 + * @interface ICreateDatabaseMetadata + */ + + /** + * Constructs a new CreateDatabaseMetadata. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a CreateDatabaseMetadata. + * @implements ICreateDatabaseMetadata + * @constructor + * @param {google.firestore.admin.v1.ICreateDatabaseMetadata=} [properties] Properties to set + */ + function CreateDatabaseMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a CreateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.CreateDatabaseMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.CreateDatabaseMetadata} CreateDatabaseMetadata + */ + CreateDatabaseMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.CreateDatabaseMetadata) + return object; + return new $root.google.firestore.admin.v1.CreateDatabaseMetadata(); + }; + + /** + * Creates a plain object from a CreateDatabaseMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.CreateDatabaseMetadata + * @static + * @param {google.firestore.admin.v1.CreateDatabaseMetadata} message CreateDatabaseMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateDatabaseMetadata.toObject = function toObject() { + return {}; + }; + + /** + * Converts this CreateDatabaseMetadata to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.CreateDatabaseMetadata + * @instance + * @returns {Object.} JSON object + */ + CreateDatabaseMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateDatabaseMetadata + * @function getTypeUrl + * @memberof google.firestore.admin.v1.CreateDatabaseMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateDatabaseMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.CreateDatabaseMetadata"; + }; + + return CreateDatabaseMetadata; + })(); + + v1.ListDatabasesResponse = (function() { + + /** + * Properties of a ListDatabasesResponse. + * @memberof google.firestore.admin.v1 + * @interface IListDatabasesResponse + * @property {Array.|null} [databases] ListDatabasesResponse databases + * @property {Array.|null} [unreachable] ListDatabasesResponse unreachable + */ + + /** + * Constructs a new ListDatabasesResponse. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a ListDatabasesResponse. + * @implements IListDatabasesResponse + * @constructor + * @param {google.firestore.admin.v1.IListDatabasesResponse=} [properties] Properties to set + */ + function ListDatabasesResponse(properties) { + this.databases = []; + this.unreachable = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListDatabasesResponse databases. + * @member {Array.} databases + * @memberof google.firestore.admin.v1.ListDatabasesResponse + * @instance + */ + ListDatabasesResponse.prototype.databases = $util.emptyArray; + + /** + * ListDatabasesResponse unreachable. + * @member {Array.} unreachable + * @memberof google.firestore.admin.v1.ListDatabasesResponse + * @instance + */ + ListDatabasesResponse.prototype.unreachable = $util.emptyArray; + + /** + * Creates a ListDatabasesResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ListDatabasesResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ListDatabasesResponse} ListDatabasesResponse + */ + ListDatabasesResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ListDatabasesResponse) + return object; + var message = new $root.google.firestore.admin.v1.ListDatabasesResponse(); + if (object.databases) { + if (!Array.isArray(object.databases)) + throw TypeError(".google.firestore.admin.v1.ListDatabasesResponse.databases: array expected"); + message.databases = []; + for (var i = 0; i < object.databases.length; ++i) { + if (typeof object.databases[i] !== "object") + throw TypeError(".google.firestore.admin.v1.ListDatabasesResponse.databases: object expected"); + message.databases[i] = $root.google.firestore.admin.v1.Database.fromObject(object.databases[i]); + } + } + if (object.unreachable) { + if (!Array.isArray(object.unreachable)) + throw TypeError(".google.firestore.admin.v1.ListDatabasesResponse.unreachable: array expected"); + message.unreachable = []; + for (var i = 0; i < object.unreachable.length; ++i) + message.unreachable[i] = String(object.unreachable[i]); + } + return message; + }; + + /** + * Creates a plain object from a ListDatabasesResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ListDatabasesResponse + * @static + * @param {google.firestore.admin.v1.ListDatabasesResponse} message ListDatabasesResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListDatabasesResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.databases = []; + object.unreachable = []; + } + if (message.databases && message.databases.length) { + object.databases = []; + for (var j = 0; j < message.databases.length; ++j) + object.databases[j] = $root.google.firestore.admin.v1.Database.toObject(message.databases[j], options); + } + if (message.unreachable && message.unreachable.length) { + object.unreachable = []; + for (var j = 0; j < message.unreachable.length; ++j) + object.unreachable[j] = message.unreachable[j]; + } + return object; + }; + + /** + * Converts this ListDatabasesResponse to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ListDatabasesResponse + * @instance + * @returns {Object.} JSON object + */ + ListDatabasesResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListDatabasesResponse + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ListDatabasesResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListDatabasesResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ListDatabasesResponse"; + }; + + return ListDatabasesResponse; + })(); + + v1.GetDatabaseRequest = (function() { + + /** + * Properties of a GetDatabaseRequest. + * @memberof google.firestore.admin.v1 + * @interface IGetDatabaseRequest + * @property {string|null} [name] GetDatabaseRequest name + */ + + /** + * Constructs a new GetDatabaseRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a GetDatabaseRequest. + * @implements IGetDatabaseRequest + * @constructor + * @param {google.firestore.admin.v1.IGetDatabaseRequest=} [properties] Properties to set + */ + function GetDatabaseRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetDatabaseRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.GetDatabaseRequest + * @instance + */ + GetDatabaseRequest.prototype.name = ""; + + /** + * Creates a GetDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.GetDatabaseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.GetDatabaseRequest} GetDatabaseRequest + */ + GetDatabaseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.GetDatabaseRequest) + return object; + var message = new $root.google.firestore.admin.v1.GetDatabaseRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetDatabaseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.GetDatabaseRequest + * @static + * @param {google.firestore.admin.v1.GetDatabaseRequest} message GetDatabaseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetDatabaseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetDatabaseRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.GetDatabaseRequest + * @instance + * @returns {Object.} JSON object + */ + GetDatabaseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetDatabaseRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.GetDatabaseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetDatabaseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.GetDatabaseRequest"; + }; + + return GetDatabaseRequest; + })(); + + v1.UpdateDatabaseRequest = (function() { + + /** + * Properties of an UpdateDatabaseRequest. + * @memberof google.firestore.admin.v1 + * @interface IUpdateDatabaseRequest + * @property {google.firestore.admin.v1.IDatabase|null} [database] UpdateDatabaseRequest database + * @property {google.protobuf.IFieldMask|null} [updateMask] UpdateDatabaseRequest updateMask + */ + + /** + * Constructs a new UpdateDatabaseRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents an UpdateDatabaseRequest. + * @implements IUpdateDatabaseRequest + * @constructor + * @param {google.firestore.admin.v1.IUpdateDatabaseRequest=} [properties] Properties to set + */ + function UpdateDatabaseRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateDatabaseRequest database. + * @member {google.firestore.admin.v1.IDatabase|null|undefined} database + * @memberof google.firestore.admin.v1.UpdateDatabaseRequest + * @instance + */ + UpdateDatabaseRequest.prototype.database = null; + + /** + * UpdateDatabaseRequest updateMask. + * @member {google.protobuf.IFieldMask|null|undefined} updateMask + * @memberof google.firestore.admin.v1.UpdateDatabaseRequest + * @instance + */ + UpdateDatabaseRequest.prototype.updateMask = null; + + /** + * Creates an UpdateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.UpdateDatabaseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.UpdateDatabaseRequest} UpdateDatabaseRequest + */ + UpdateDatabaseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.UpdateDatabaseRequest) + return object; + var message = new $root.google.firestore.admin.v1.UpdateDatabaseRequest(); + if (object.database != null) { + if (typeof object.database !== "object") + throw TypeError(".google.firestore.admin.v1.UpdateDatabaseRequest.database: object expected"); + message.database = $root.google.firestore.admin.v1.Database.fromObject(object.database); + } + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.firestore.admin.v1.UpdateDatabaseRequest.updateMask: object expected"); + message.updateMask = $root.google.protobuf.FieldMask.fromObject(object.updateMask); + } + return message; + }; + + /** + * Creates a plain object from an UpdateDatabaseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.UpdateDatabaseRequest + * @static + * @param {google.firestore.admin.v1.UpdateDatabaseRequest} message UpdateDatabaseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateDatabaseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.database = null; + object.updateMask = null; + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = $root.google.firestore.admin.v1.Database.toObject(message.database, options); + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.protobuf.FieldMask.toObject(message.updateMask, options); + return object; + }; + + /** + * Converts this UpdateDatabaseRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.UpdateDatabaseRequest + * @instance + * @returns {Object.} JSON object + */ + UpdateDatabaseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateDatabaseRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.UpdateDatabaseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateDatabaseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.UpdateDatabaseRequest"; + }; + + return UpdateDatabaseRequest; + })(); + + v1.UpdateDatabaseMetadata = (function() { + + /** + * Properties of an UpdateDatabaseMetadata. + * @memberof google.firestore.admin.v1 + * @interface IUpdateDatabaseMetadata + */ + + /** + * Constructs a new UpdateDatabaseMetadata. + * @memberof google.firestore.admin.v1 + * @classdesc Represents an UpdateDatabaseMetadata. + * @implements IUpdateDatabaseMetadata + * @constructor + * @param {google.firestore.admin.v1.IUpdateDatabaseMetadata=} [properties] Properties to set + */ + function UpdateDatabaseMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates an UpdateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.UpdateDatabaseMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.UpdateDatabaseMetadata} UpdateDatabaseMetadata + */ + UpdateDatabaseMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.UpdateDatabaseMetadata) + return object; + return new $root.google.firestore.admin.v1.UpdateDatabaseMetadata(); + }; + + /** + * Creates a plain object from an UpdateDatabaseMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.UpdateDatabaseMetadata + * @static + * @param {google.firestore.admin.v1.UpdateDatabaseMetadata} message UpdateDatabaseMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateDatabaseMetadata.toObject = function toObject() { + return {}; + }; + + /** + * Converts this UpdateDatabaseMetadata to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.UpdateDatabaseMetadata + * @instance + * @returns {Object.} JSON object + */ + UpdateDatabaseMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateDatabaseMetadata + * @function getTypeUrl + * @memberof google.firestore.admin.v1.UpdateDatabaseMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateDatabaseMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.UpdateDatabaseMetadata"; + }; + + return UpdateDatabaseMetadata; + })(); + + v1.DeleteDatabaseRequest = (function() { + + /** + * Properties of a DeleteDatabaseRequest. + * @memberof google.firestore.admin.v1 + * @interface IDeleteDatabaseRequest + * @property {string|null} [name] DeleteDatabaseRequest name + * @property {string|null} [etag] DeleteDatabaseRequest etag + */ + + /** + * Constructs a new DeleteDatabaseRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a DeleteDatabaseRequest. + * @implements IDeleteDatabaseRequest + * @constructor + * @param {google.firestore.admin.v1.IDeleteDatabaseRequest=} [properties] Properties to set + */ + function DeleteDatabaseRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteDatabaseRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.DeleteDatabaseRequest + * @instance + */ + DeleteDatabaseRequest.prototype.name = ""; + + /** + * DeleteDatabaseRequest etag. + * @member {string} etag + * @memberof google.firestore.admin.v1.DeleteDatabaseRequest + * @instance + */ + DeleteDatabaseRequest.prototype.etag = ""; + + /** + * Creates a DeleteDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.DeleteDatabaseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.DeleteDatabaseRequest} DeleteDatabaseRequest + */ + DeleteDatabaseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.DeleteDatabaseRequest) + return object; + var message = new $root.google.firestore.admin.v1.DeleteDatabaseRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.etag != null) + message.etag = String(object.etag); + return message; + }; + + /** + * Creates a plain object from a DeleteDatabaseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.DeleteDatabaseRequest + * @static + * @param {google.firestore.admin.v1.DeleteDatabaseRequest} message DeleteDatabaseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteDatabaseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.etag = ""; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.etag != null && message.hasOwnProperty("etag")) + object.etag = message.etag; + return object; + }; + + /** + * Converts this DeleteDatabaseRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.DeleteDatabaseRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteDatabaseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteDatabaseRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.DeleteDatabaseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteDatabaseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.DeleteDatabaseRequest"; + }; + + return DeleteDatabaseRequest; + })(); + + v1.DeleteDatabaseMetadata = (function() { + + /** + * Properties of a DeleteDatabaseMetadata. + * @memberof google.firestore.admin.v1 + * @interface IDeleteDatabaseMetadata + */ + + /** + * Constructs a new DeleteDatabaseMetadata. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a DeleteDatabaseMetadata. + * @implements IDeleteDatabaseMetadata + * @constructor + * @param {google.firestore.admin.v1.IDeleteDatabaseMetadata=} [properties] Properties to set + */ + function DeleteDatabaseMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a DeleteDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.DeleteDatabaseMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.DeleteDatabaseMetadata} DeleteDatabaseMetadata + */ + DeleteDatabaseMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.DeleteDatabaseMetadata) + return object; + return new $root.google.firestore.admin.v1.DeleteDatabaseMetadata(); + }; + + /** + * Creates a plain object from a DeleteDatabaseMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.DeleteDatabaseMetadata + * @static + * @param {google.firestore.admin.v1.DeleteDatabaseMetadata} message DeleteDatabaseMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteDatabaseMetadata.toObject = function toObject() { + return {}; + }; + + /** + * Converts this DeleteDatabaseMetadata to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.DeleteDatabaseMetadata + * @instance + * @returns {Object.} JSON object + */ + DeleteDatabaseMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteDatabaseMetadata + * @function getTypeUrl + * @memberof google.firestore.admin.v1.DeleteDatabaseMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteDatabaseMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.DeleteDatabaseMetadata"; + }; + + return DeleteDatabaseMetadata; + })(); + + v1.CreateUserCredsRequest = (function() { + + /** + * Properties of a CreateUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @interface ICreateUserCredsRequest + * @property {string|null} [parent] CreateUserCredsRequest parent + * @property {google.firestore.admin.v1.IUserCreds|null} [userCreds] CreateUserCredsRequest userCreds + * @property {string|null} [userCredsId] CreateUserCredsRequest userCredsId + */ + + /** + * Constructs a new CreateUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a CreateUserCredsRequest. + * @implements ICreateUserCredsRequest + * @constructor + * @param {google.firestore.admin.v1.ICreateUserCredsRequest=} [properties] Properties to set + */ + function CreateUserCredsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateUserCredsRequest parent. + * @member {string} parent + * @memberof google.firestore.admin.v1.CreateUserCredsRequest + * @instance + */ + CreateUserCredsRequest.prototype.parent = ""; + + /** + * CreateUserCredsRequest userCreds. + * @member {google.firestore.admin.v1.IUserCreds|null|undefined} userCreds + * @memberof google.firestore.admin.v1.CreateUserCredsRequest + * @instance + */ + CreateUserCredsRequest.prototype.userCreds = null; + + /** + * CreateUserCredsRequest userCredsId. + * @member {string} userCredsId + * @memberof google.firestore.admin.v1.CreateUserCredsRequest + * @instance + */ + CreateUserCredsRequest.prototype.userCredsId = ""; + + /** + * Creates a CreateUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.CreateUserCredsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.CreateUserCredsRequest} CreateUserCredsRequest + */ + CreateUserCredsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.CreateUserCredsRequest) + return object; + var message = new $root.google.firestore.admin.v1.CreateUserCredsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.userCreds != null) { + if (typeof object.userCreds !== "object") + throw TypeError(".google.firestore.admin.v1.CreateUserCredsRequest.userCreds: object expected"); + message.userCreds = $root.google.firestore.admin.v1.UserCreds.fromObject(object.userCreds); + } + if (object.userCredsId != null) + message.userCredsId = String(object.userCredsId); + return message; + }; + + /** + * Creates a plain object from a CreateUserCredsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.CreateUserCredsRequest + * @static + * @param {google.firestore.admin.v1.CreateUserCredsRequest} message CreateUserCredsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateUserCredsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.userCreds = null; + object.userCredsId = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.userCreds != null && message.hasOwnProperty("userCreds")) + object.userCreds = $root.google.firestore.admin.v1.UserCreds.toObject(message.userCreds, options); + if (message.userCredsId != null && message.hasOwnProperty("userCredsId")) + object.userCredsId = message.userCredsId; + return object; + }; + + /** + * Converts this CreateUserCredsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.CreateUserCredsRequest + * @instance + * @returns {Object.} JSON object + */ + CreateUserCredsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateUserCredsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.CreateUserCredsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateUserCredsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.CreateUserCredsRequest"; + }; + + return CreateUserCredsRequest; + })(); + + v1.GetUserCredsRequest = (function() { + + /** + * Properties of a GetUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @interface IGetUserCredsRequest + * @property {string|null} [name] GetUserCredsRequest name + */ + + /** + * Constructs a new GetUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a GetUserCredsRequest. + * @implements IGetUserCredsRequest + * @constructor + * @param {google.firestore.admin.v1.IGetUserCredsRequest=} [properties] Properties to set + */ + function GetUserCredsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetUserCredsRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.GetUserCredsRequest + * @instance + */ + GetUserCredsRequest.prototype.name = ""; + + /** + * Creates a GetUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.GetUserCredsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.GetUserCredsRequest} GetUserCredsRequest + */ + GetUserCredsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.GetUserCredsRequest) + return object; + var message = new $root.google.firestore.admin.v1.GetUserCredsRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetUserCredsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.GetUserCredsRequest + * @static + * @param {google.firestore.admin.v1.GetUserCredsRequest} message GetUserCredsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetUserCredsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetUserCredsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.GetUserCredsRequest + * @instance + * @returns {Object.} JSON object + */ + GetUserCredsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetUserCredsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.GetUserCredsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetUserCredsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.GetUserCredsRequest"; + }; + + return GetUserCredsRequest; + })(); + + v1.ListUserCredsRequest = (function() { + + /** + * Properties of a ListUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @interface IListUserCredsRequest + * @property {string|null} [parent] ListUserCredsRequest parent + */ + + /** + * Constructs a new ListUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a ListUserCredsRequest. + * @implements IListUserCredsRequest + * @constructor + * @param {google.firestore.admin.v1.IListUserCredsRequest=} [properties] Properties to set + */ + function ListUserCredsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListUserCredsRequest parent. + * @member {string} parent + * @memberof google.firestore.admin.v1.ListUserCredsRequest + * @instance + */ + ListUserCredsRequest.prototype.parent = ""; + + /** + * Creates a ListUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ListUserCredsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ListUserCredsRequest} ListUserCredsRequest + */ + ListUserCredsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ListUserCredsRequest) + return object; + var message = new $root.google.firestore.admin.v1.ListUserCredsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + return message; + }; + + /** + * Creates a plain object from a ListUserCredsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ListUserCredsRequest + * @static + * @param {google.firestore.admin.v1.ListUserCredsRequest} message ListUserCredsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListUserCredsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.parent = ""; + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + return object; + }; + + /** + * Converts this ListUserCredsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ListUserCredsRequest + * @instance + * @returns {Object.} JSON object + */ + ListUserCredsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListUserCredsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ListUserCredsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListUserCredsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ListUserCredsRequest"; + }; + + return ListUserCredsRequest; + })(); + + v1.ListUserCredsResponse = (function() { + + /** + * Properties of a ListUserCredsResponse. + * @memberof google.firestore.admin.v1 + * @interface IListUserCredsResponse + * @property {Array.|null} [userCreds] ListUserCredsResponse userCreds + */ + + /** + * Constructs a new ListUserCredsResponse. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a ListUserCredsResponse. + * @implements IListUserCredsResponse + * @constructor + * @param {google.firestore.admin.v1.IListUserCredsResponse=} [properties] Properties to set + */ + function ListUserCredsResponse(properties) { + this.userCreds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListUserCredsResponse userCreds. + * @member {Array.} userCreds + * @memberof google.firestore.admin.v1.ListUserCredsResponse + * @instance + */ + ListUserCredsResponse.prototype.userCreds = $util.emptyArray; + + /** + * Creates a ListUserCredsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ListUserCredsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ListUserCredsResponse} ListUserCredsResponse + */ + ListUserCredsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ListUserCredsResponse) + return object; + var message = new $root.google.firestore.admin.v1.ListUserCredsResponse(); + if (object.userCreds) { + if (!Array.isArray(object.userCreds)) + throw TypeError(".google.firestore.admin.v1.ListUserCredsResponse.userCreds: array expected"); + message.userCreds = []; + for (var i = 0; i < object.userCreds.length; ++i) { + if (typeof object.userCreds[i] !== "object") + throw TypeError(".google.firestore.admin.v1.ListUserCredsResponse.userCreds: object expected"); + message.userCreds[i] = $root.google.firestore.admin.v1.UserCreds.fromObject(object.userCreds[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a ListUserCredsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ListUserCredsResponse + * @static + * @param {google.firestore.admin.v1.ListUserCredsResponse} message ListUserCredsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListUserCredsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.userCreds = []; + if (message.userCreds && message.userCreds.length) { + object.userCreds = []; + for (var j = 0; j < message.userCreds.length; ++j) + object.userCreds[j] = $root.google.firestore.admin.v1.UserCreds.toObject(message.userCreds[j], options); + } + return object; + }; + + /** + * Converts this ListUserCredsResponse to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ListUserCredsResponse + * @instance + * @returns {Object.} JSON object + */ + ListUserCredsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListUserCredsResponse + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ListUserCredsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListUserCredsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ListUserCredsResponse"; + }; + + return ListUserCredsResponse; + })(); + + v1.EnableUserCredsRequest = (function() { + + /** + * Properties of an EnableUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @interface IEnableUserCredsRequest + * @property {string|null} [name] EnableUserCredsRequest name + */ + + /** + * Constructs a new EnableUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents an EnableUserCredsRequest. + * @implements IEnableUserCredsRequest + * @constructor + * @param {google.firestore.admin.v1.IEnableUserCredsRequest=} [properties] Properties to set + */ + function EnableUserCredsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnableUserCredsRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.EnableUserCredsRequest + * @instance + */ + EnableUserCredsRequest.prototype.name = ""; + + /** + * Creates an EnableUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.EnableUserCredsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.EnableUserCredsRequest} EnableUserCredsRequest + */ + EnableUserCredsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.EnableUserCredsRequest) + return object; + var message = new $root.google.firestore.admin.v1.EnableUserCredsRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from an EnableUserCredsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.EnableUserCredsRequest + * @static + * @param {google.firestore.admin.v1.EnableUserCredsRequest} message EnableUserCredsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnableUserCredsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this EnableUserCredsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.EnableUserCredsRequest + * @instance + * @returns {Object.} JSON object + */ + EnableUserCredsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnableUserCredsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.EnableUserCredsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnableUserCredsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.EnableUserCredsRequest"; + }; + + return EnableUserCredsRequest; + })(); + + v1.DisableUserCredsRequest = (function() { + + /** + * Properties of a DisableUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @interface IDisableUserCredsRequest + * @property {string|null} [name] DisableUserCredsRequest name + */ + + /** + * Constructs a new DisableUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a DisableUserCredsRequest. + * @implements IDisableUserCredsRequest + * @constructor + * @param {google.firestore.admin.v1.IDisableUserCredsRequest=} [properties] Properties to set + */ + function DisableUserCredsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DisableUserCredsRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.DisableUserCredsRequest + * @instance + */ + DisableUserCredsRequest.prototype.name = ""; + + /** + * Creates a DisableUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.DisableUserCredsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.DisableUserCredsRequest} DisableUserCredsRequest + */ + DisableUserCredsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.DisableUserCredsRequest) + return object; + var message = new $root.google.firestore.admin.v1.DisableUserCredsRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a DisableUserCredsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.DisableUserCredsRequest + * @static + * @param {google.firestore.admin.v1.DisableUserCredsRequest} message DisableUserCredsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DisableUserCredsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this DisableUserCredsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.DisableUserCredsRequest + * @instance + * @returns {Object.} JSON object + */ + DisableUserCredsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DisableUserCredsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.DisableUserCredsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DisableUserCredsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.DisableUserCredsRequest"; + }; + + return DisableUserCredsRequest; + })(); + + v1.ResetUserPasswordRequest = (function() { + + /** + * Properties of a ResetUserPasswordRequest. + * @memberof google.firestore.admin.v1 + * @interface IResetUserPasswordRequest + * @property {string|null} [name] ResetUserPasswordRequest name + */ + + /** + * Constructs a new ResetUserPasswordRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a ResetUserPasswordRequest. + * @implements IResetUserPasswordRequest + * @constructor + * @param {google.firestore.admin.v1.IResetUserPasswordRequest=} [properties] Properties to set + */ + function ResetUserPasswordRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResetUserPasswordRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.ResetUserPasswordRequest + * @instance + */ + ResetUserPasswordRequest.prototype.name = ""; + + /** + * Creates a ResetUserPasswordRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ResetUserPasswordRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ResetUserPasswordRequest} ResetUserPasswordRequest + */ + ResetUserPasswordRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ResetUserPasswordRequest) + return object; + var message = new $root.google.firestore.admin.v1.ResetUserPasswordRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a ResetUserPasswordRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ResetUserPasswordRequest + * @static + * @param {google.firestore.admin.v1.ResetUserPasswordRequest} message ResetUserPasswordRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResetUserPasswordRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this ResetUserPasswordRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ResetUserPasswordRequest + * @instance + * @returns {Object.} JSON object + */ + ResetUserPasswordRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResetUserPasswordRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ResetUserPasswordRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResetUserPasswordRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ResetUserPasswordRequest"; + }; + + return ResetUserPasswordRequest; + })(); + + v1.DeleteUserCredsRequest = (function() { + + /** + * Properties of a DeleteUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @interface IDeleteUserCredsRequest + * @property {string|null} [name] DeleteUserCredsRequest name + */ + + /** + * Constructs a new DeleteUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a DeleteUserCredsRequest. + * @implements IDeleteUserCredsRequest + * @constructor + * @param {google.firestore.admin.v1.IDeleteUserCredsRequest=} [properties] Properties to set + */ + function DeleteUserCredsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteUserCredsRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.DeleteUserCredsRequest + * @instance + */ + DeleteUserCredsRequest.prototype.name = ""; + + /** + * Creates a DeleteUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.DeleteUserCredsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.DeleteUserCredsRequest} DeleteUserCredsRequest + */ + DeleteUserCredsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.DeleteUserCredsRequest) + return object; + var message = new $root.google.firestore.admin.v1.DeleteUserCredsRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a DeleteUserCredsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.DeleteUserCredsRequest + * @static + * @param {google.firestore.admin.v1.DeleteUserCredsRequest} message DeleteUserCredsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteUserCredsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this DeleteUserCredsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.DeleteUserCredsRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteUserCredsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteUserCredsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.DeleteUserCredsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteUserCredsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.DeleteUserCredsRequest"; + }; + + return DeleteUserCredsRequest; + })(); + + v1.CreateBackupScheduleRequest = (function() { + + /** + * Properties of a CreateBackupScheduleRequest. + * @memberof google.firestore.admin.v1 + * @interface ICreateBackupScheduleRequest + * @property {string|null} [parent] CreateBackupScheduleRequest parent + * @property {google.firestore.admin.v1.IBackupSchedule|null} [backupSchedule] CreateBackupScheduleRequest backupSchedule + */ + + /** + * Constructs a new CreateBackupScheduleRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a CreateBackupScheduleRequest. + * @implements ICreateBackupScheduleRequest + * @constructor + * @param {google.firestore.admin.v1.ICreateBackupScheduleRequest=} [properties] Properties to set + */ + function CreateBackupScheduleRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateBackupScheduleRequest parent. + * @member {string} parent + * @memberof google.firestore.admin.v1.CreateBackupScheduleRequest + * @instance + */ + CreateBackupScheduleRequest.prototype.parent = ""; + + /** + * CreateBackupScheduleRequest backupSchedule. + * @member {google.firestore.admin.v1.IBackupSchedule|null|undefined} backupSchedule + * @memberof google.firestore.admin.v1.CreateBackupScheduleRequest + * @instance + */ + CreateBackupScheduleRequest.prototype.backupSchedule = null; + + /** + * Creates a CreateBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.CreateBackupScheduleRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.CreateBackupScheduleRequest} CreateBackupScheduleRequest + */ + CreateBackupScheduleRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.CreateBackupScheduleRequest) + return object; + var message = new $root.google.firestore.admin.v1.CreateBackupScheduleRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.backupSchedule != null) { + if (typeof object.backupSchedule !== "object") + throw TypeError(".google.firestore.admin.v1.CreateBackupScheduleRequest.backupSchedule: object expected"); + message.backupSchedule = $root.google.firestore.admin.v1.BackupSchedule.fromObject(object.backupSchedule); + } + return message; + }; + + /** + * Creates a plain object from a CreateBackupScheduleRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.CreateBackupScheduleRequest + * @static + * @param {google.firestore.admin.v1.CreateBackupScheduleRequest} message CreateBackupScheduleRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateBackupScheduleRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.backupSchedule = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.backupSchedule != null && message.hasOwnProperty("backupSchedule")) + object.backupSchedule = $root.google.firestore.admin.v1.BackupSchedule.toObject(message.backupSchedule, options); + return object; + }; + + /** + * Converts this CreateBackupScheduleRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.CreateBackupScheduleRequest + * @instance + * @returns {Object.} JSON object + */ + CreateBackupScheduleRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateBackupScheduleRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.CreateBackupScheduleRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateBackupScheduleRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.CreateBackupScheduleRequest"; + }; + + return CreateBackupScheduleRequest; + })(); + + v1.GetBackupScheduleRequest = (function() { + + /** + * Properties of a GetBackupScheduleRequest. + * @memberof google.firestore.admin.v1 + * @interface IGetBackupScheduleRequest + * @property {string|null} [name] GetBackupScheduleRequest name + */ + + /** + * Constructs a new GetBackupScheduleRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a GetBackupScheduleRequest. + * @implements IGetBackupScheduleRequest + * @constructor + * @param {google.firestore.admin.v1.IGetBackupScheduleRequest=} [properties] Properties to set + */ + function GetBackupScheduleRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetBackupScheduleRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.GetBackupScheduleRequest + * @instance + */ + GetBackupScheduleRequest.prototype.name = ""; + + /** + * Creates a GetBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.GetBackupScheduleRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.GetBackupScheduleRequest} GetBackupScheduleRequest + */ + GetBackupScheduleRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.GetBackupScheduleRequest) + return object; + var message = new $root.google.firestore.admin.v1.GetBackupScheduleRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetBackupScheduleRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.GetBackupScheduleRequest + * @static + * @param {google.firestore.admin.v1.GetBackupScheduleRequest} message GetBackupScheduleRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetBackupScheduleRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetBackupScheduleRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.GetBackupScheduleRequest + * @instance + * @returns {Object.} JSON object + */ + GetBackupScheduleRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetBackupScheduleRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.GetBackupScheduleRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetBackupScheduleRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.GetBackupScheduleRequest"; + }; + + return GetBackupScheduleRequest; + })(); + + v1.UpdateBackupScheduleRequest = (function() { + + /** + * Properties of an UpdateBackupScheduleRequest. + * @memberof google.firestore.admin.v1 + * @interface IUpdateBackupScheduleRequest + * @property {google.firestore.admin.v1.IBackupSchedule|null} [backupSchedule] UpdateBackupScheduleRequest backupSchedule + * @property {google.protobuf.IFieldMask|null} [updateMask] UpdateBackupScheduleRequest updateMask + */ + + /** + * Constructs a new UpdateBackupScheduleRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents an UpdateBackupScheduleRequest. + * @implements IUpdateBackupScheduleRequest + * @constructor + * @param {google.firestore.admin.v1.IUpdateBackupScheduleRequest=} [properties] Properties to set + */ + function UpdateBackupScheduleRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateBackupScheduleRequest backupSchedule. + * @member {google.firestore.admin.v1.IBackupSchedule|null|undefined} backupSchedule + * @memberof google.firestore.admin.v1.UpdateBackupScheduleRequest + * @instance + */ + UpdateBackupScheduleRequest.prototype.backupSchedule = null; + + /** + * UpdateBackupScheduleRequest updateMask. + * @member {google.protobuf.IFieldMask|null|undefined} updateMask + * @memberof google.firestore.admin.v1.UpdateBackupScheduleRequest + * @instance + */ + UpdateBackupScheduleRequest.prototype.updateMask = null; + + /** + * Creates an UpdateBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.UpdateBackupScheduleRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.UpdateBackupScheduleRequest} UpdateBackupScheduleRequest + */ + UpdateBackupScheduleRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.UpdateBackupScheduleRequest) + return object; + var message = new $root.google.firestore.admin.v1.UpdateBackupScheduleRequest(); + if (object.backupSchedule != null) { + if (typeof object.backupSchedule !== "object") + throw TypeError(".google.firestore.admin.v1.UpdateBackupScheduleRequest.backupSchedule: object expected"); + message.backupSchedule = $root.google.firestore.admin.v1.BackupSchedule.fromObject(object.backupSchedule); + } + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.firestore.admin.v1.UpdateBackupScheduleRequest.updateMask: object expected"); + message.updateMask = $root.google.protobuf.FieldMask.fromObject(object.updateMask); + } + return message; + }; + + /** + * Creates a plain object from an UpdateBackupScheduleRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.UpdateBackupScheduleRequest + * @static + * @param {google.firestore.admin.v1.UpdateBackupScheduleRequest} message UpdateBackupScheduleRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateBackupScheduleRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.backupSchedule = null; + object.updateMask = null; + } + if (message.backupSchedule != null && message.hasOwnProperty("backupSchedule")) + object.backupSchedule = $root.google.firestore.admin.v1.BackupSchedule.toObject(message.backupSchedule, options); + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.protobuf.FieldMask.toObject(message.updateMask, options); + return object; + }; + + /** + * Converts this UpdateBackupScheduleRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.UpdateBackupScheduleRequest + * @instance + * @returns {Object.} JSON object + */ + UpdateBackupScheduleRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateBackupScheduleRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.UpdateBackupScheduleRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateBackupScheduleRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.UpdateBackupScheduleRequest"; + }; + + return UpdateBackupScheduleRequest; + })(); + + v1.ListBackupSchedulesRequest = (function() { + + /** + * Properties of a ListBackupSchedulesRequest. + * @memberof google.firestore.admin.v1 + * @interface IListBackupSchedulesRequest + * @property {string|null} [parent] ListBackupSchedulesRequest parent + */ + + /** + * Constructs a new ListBackupSchedulesRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a ListBackupSchedulesRequest. + * @implements IListBackupSchedulesRequest + * @constructor + * @param {google.firestore.admin.v1.IListBackupSchedulesRequest=} [properties] Properties to set + */ + function ListBackupSchedulesRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListBackupSchedulesRequest parent. + * @member {string} parent + * @memberof google.firestore.admin.v1.ListBackupSchedulesRequest + * @instance + */ + ListBackupSchedulesRequest.prototype.parent = ""; + + /** + * Creates a ListBackupSchedulesRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ListBackupSchedulesRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ListBackupSchedulesRequest} ListBackupSchedulesRequest + */ + ListBackupSchedulesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ListBackupSchedulesRequest) + return object; + var message = new $root.google.firestore.admin.v1.ListBackupSchedulesRequest(); + if (object.parent != null) + message.parent = String(object.parent); + return message; + }; + + /** + * Creates a plain object from a ListBackupSchedulesRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ListBackupSchedulesRequest + * @static + * @param {google.firestore.admin.v1.ListBackupSchedulesRequest} message ListBackupSchedulesRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListBackupSchedulesRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.parent = ""; + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + return object; + }; + + /** + * Converts this ListBackupSchedulesRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ListBackupSchedulesRequest + * @instance + * @returns {Object.} JSON object + */ + ListBackupSchedulesRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListBackupSchedulesRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ListBackupSchedulesRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListBackupSchedulesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ListBackupSchedulesRequest"; + }; + + return ListBackupSchedulesRequest; + })(); + + v1.ListBackupSchedulesResponse = (function() { + + /** + * Properties of a ListBackupSchedulesResponse. + * @memberof google.firestore.admin.v1 + * @interface IListBackupSchedulesResponse + * @property {Array.|null} [backupSchedules] ListBackupSchedulesResponse backupSchedules + */ + + /** + * Constructs a new ListBackupSchedulesResponse. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a ListBackupSchedulesResponse. + * @implements IListBackupSchedulesResponse + * @constructor + * @param {google.firestore.admin.v1.IListBackupSchedulesResponse=} [properties] Properties to set + */ + function ListBackupSchedulesResponse(properties) { + this.backupSchedules = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListBackupSchedulesResponse backupSchedules. + * @member {Array.} backupSchedules + * @memberof google.firestore.admin.v1.ListBackupSchedulesResponse + * @instance + */ + ListBackupSchedulesResponse.prototype.backupSchedules = $util.emptyArray; + + /** + * Creates a ListBackupSchedulesResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ListBackupSchedulesResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ListBackupSchedulesResponse} ListBackupSchedulesResponse + */ + ListBackupSchedulesResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ListBackupSchedulesResponse) + return object; + var message = new $root.google.firestore.admin.v1.ListBackupSchedulesResponse(); + if (object.backupSchedules) { + if (!Array.isArray(object.backupSchedules)) + throw TypeError(".google.firestore.admin.v1.ListBackupSchedulesResponse.backupSchedules: array expected"); + message.backupSchedules = []; + for (var i = 0; i < object.backupSchedules.length; ++i) { + if (typeof object.backupSchedules[i] !== "object") + throw TypeError(".google.firestore.admin.v1.ListBackupSchedulesResponse.backupSchedules: object expected"); + message.backupSchedules[i] = $root.google.firestore.admin.v1.BackupSchedule.fromObject(object.backupSchedules[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a ListBackupSchedulesResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ListBackupSchedulesResponse + * @static + * @param {google.firestore.admin.v1.ListBackupSchedulesResponse} message ListBackupSchedulesResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListBackupSchedulesResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.backupSchedules = []; + if (message.backupSchedules && message.backupSchedules.length) { + object.backupSchedules = []; + for (var j = 0; j < message.backupSchedules.length; ++j) + object.backupSchedules[j] = $root.google.firestore.admin.v1.BackupSchedule.toObject(message.backupSchedules[j], options); + } + return object; + }; + + /** + * Converts this ListBackupSchedulesResponse to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ListBackupSchedulesResponse + * @instance + * @returns {Object.} JSON object + */ + ListBackupSchedulesResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListBackupSchedulesResponse + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ListBackupSchedulesResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListBackupSchedulesResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ListBackupSchedulesResponse"; + }; + + return ListBackupSchedulesResponse; + })(); + + v1.DeleteBackupScheduleRequest = (function() { + + /** + * Properties of a DeleteBackupScheduleRequest. + * @memberof google.firestore.admin.v1 + * @interface IDeleteBackupScheduleRequest + * @property {string|null} [name] DeleteBackupScheduleRequest name + */ + + /** + * Constructs a new DeleteBackupScheduleRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a DeleteBackupScheduleRequest. + * @implements IDeleteBackupScheduleRequest + * @constructor + * @param {google.firestore.admin.v1.IDeleteBackupScheduleRequest=} [properties] Properties to set + */ + function DeleteBackupScheduleRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteBackupScheduleRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.DeleteBackupScheduleRequest + * @instance + */ + DeleteBackupScheduleRequest.prototype.name = ""; + + /** + * Creates a DeleteBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.DeleteBackupScheduleRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.DeleteBackupScheduleRequest} DeleteBackupScheduleRequest + */ + DeleteBackupScheduleRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.DeleteBackupScheduleRequest) + return object; + var message = new $root.google.firestore.admin.v1.DeleteBackupScheduleRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a DeleteBackupScheduleRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.DeleteBackupScheduleRequest + * @static + * @param {google.firestore.admin.v1.DeleteBackupScheduleRequest} message DeleteBackupScheduleRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteBackupScheduleRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this DeleteBackupScheduleRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.DeleteBackupScheduleRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteBackupScheduleRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteBackupScheduleRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.DeleteBackupScheduleRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteBackupScheduleRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.DeleteBackupScheduleRequest"; + }; + + return DeleteBackupScheduleRequest; + })(); + + v1.CreateIndexRequest = (function() { + + /** + * Properties of a CreateIndexRequest. + * @memberof google.firestore.admin.v1 + * @interface ICreateIndexRequest + * @property {string|null} [parent] CreateIndexRequest parent + * @property {google.firestore.admin.v1.IIndex|null} [index] CreateIndexRequest index + */ + + /** + * Constructs a new CreateIndexRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a CreateIndexRequest. + * @implements ICreateIndexRequest + * @constructor + * @param {google.firestore.admin.v1.ICreateIndexRequest=} [properties] Properties to set + */ + function CreateIndexRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateIndexRequest parent. + * @member {string} parent + * @memberof google.firestore.admin.v1.CreateIndexRequest + * @instance + */ + CreateIndexRequest.prototype.parent = ""; + + /** + * CreateIndexRequest index. + * @member {google.firestore.admin.v1.IIndex|null|undefined} index + * @memberof google.firestore.admin.v1.CreateIndexRequest + * @instance + */ + CreateIndexRequest.prototype.index = null; + + /** + * Creates a CreateIndexRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.CreateIndexRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.CreateIndexRequest} CreateIndexRequest + */ + CreateIndexRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.CreateIndexRequest) + return object; + var message = new $root.google.firestore.admin.v1.CreateIndexRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.index != null) { + if (typeof object.index !== "object") + throw TypeError(".google.firestore.admin.v1.CreateIndexRequest.index: object expected"); + message.index = $root.google.firestore.admin.v1.Index.fromObject(object.index); + } + return message; + }; + + /** + * Creates a plain object from a CreateIndexRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.CreateIndexRequest + * @static + * @param {google.firestore.admin.v1.CreateIndexRequest} message CreateIndexRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateIndexRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.index = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.index != null && message.hasOwnProperty("index")) + object.index = $root.google.firestore.admin.v1.Index.toObject(message.index, options); + return object; + }; + + /** + * Converts this CreateIndexRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.CreateIndexRequest + * @instance + * @returns {Object.} JSON object + */ + CreateIndexRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateIndexRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.CreateIndexRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateIndexRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.CreateIndexRequest"; + }; + + return CreateIndexRequest; + })(); + + v1.ListIndexesRequest = (function() { + + /** + * Properties of a ListIndexesRequest. + * @memberof google.firestore.admin.v1 + * @interface IListIndexesRequest + * @property {string|null} [parent] ListIndexesRequest parent + * @property {string|null} [filter] ListIndexesRequest filter + * @property {number|null} [pageSize] ListIndexesRequest pageSize + * @property {string|null} [pageToken] ListIndexesRequest pageToken + */ + + /** + * Constructs a new ListIndexesRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a ListIndexesRequest. + * @implements IListIndexesRequest + * @constructor + * @param {google.firestore.admin.v1.IListIndexesRequest=} [properties] Properties to set + */ + function ListIndexesRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListIndexesRequest parent. + * @member {string} parent + * @memberof google.firestore.admin.v1.ListIndexesRequest + * @instance + */ + ListIndexesRequest.prototype.parent = ""; + + /** + * ListIndexesRequest filter. + * @member {string} filter + * @memberof google.firestore.admin.v1.ListIndexesRequest + * @instance + */ + ListIndexesRequest.prototype.filter = ""; + + /** + * ListIndexesRequest pageSize. + * @member {number} pageSize + * @memberof google.firestore.admin.v1.ListIndexesRequest + * @instance + */ + ListIndexesRequest.prototype.pageSize = 0; + + /** + * ListIndexesRequest pageToken. + * @member {string} pageToken + * @memberof google.firestore.admin.v1.ListIndexesRequest + * @instance + */ + ListIndexesRequest.prototype.pageToken = ""; + + /** + * Creates a ListIndexesRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ListIndexesRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ListIndexesRequest} ListIndexesRequest + */ + ListIndexesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ListIndexesRequest) + return object; + var message = new $root.google.firestore.admin.v1.ListIndexesRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListIndexesRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ListIndexesRequest + * @static + * @param {google.firestore.admin.v1.ListIndexesRequest} message ListIndexesRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListIndexesRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListIndexesRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ListIndexesRequest + * @instance + * @returns {Object.} JSON object + */ + ListIndexesRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListIndexesRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ListIndexesRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListIndexesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ListIndexesRequest"; + }; + + return ListIndexesRequest; + })(); + + v1.ListIndexesResponse = (function() { + + /** + * Properties of a ListIndexesResponse. + * @memberof google.firestore.admin.v1 + * @interface IListIndexesResponse + * @property {Array.|null} [indexes] ListIndexesResponse indexes + * @property {string|null} [nextPageToken] ListIndexesResponse nextPageToken + */ + + /** + * Constructs a new ListIndexesResponse. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a ListIndexesResponse. + * @implements IListIndexesResponse + * @constructor + * @param {google.firestore.admin.v1.IListIndexesResponse=} [properties] Properties to set + */ + function ListIndexesResponse(properties) { + this.indexes = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListIndexesResponse indexes. + * @member {Array.} indexes + * @memberof google.firestore.admin.v1.ListIndexesResponse + * @instance + */ + ListIndexesResponse.prototype.indexes = $util.emptyArray; + + /** + * ListIndexesResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.firestore.admin.v1.ListIndexesResponse + * @instance + */ + ListIndexesResponse.prototype.nextPageToken = ""; + + /** + * Creates a ListIndexesResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ListIndexesResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ListIndexesResponse} ListIndexesResponse + */ + ListIndexesResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ListIndexesResponse) + return object; + var message = new $root.google.firestore.admin.v1.ListIndexesResponse(); + if (object.indexes) { + if (!Array.isArray(object.indexes)) + throw TypeError(".google.firestore.admin.v1.ListIndexesResponse.indexes: array expected"); + message.indexes = []; + for (var i = 0; i < object.indexes.length; ++i) { + if (typeof object.indexes[i] !== "object") + throw TypeError(".google.firestore.admin.v1.ListIndexesResponse.indexes: object expected"); + message.indexes[i] = $root.google.firestore.admin.v1.Index.fromObject(object.indexes[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListIndexesResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ListIndexesResponse + * @static + * @param {google.firestore.admin.v1.ListIndexesResponse} message ListIndexesResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListIndexesResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.indexes = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.indexes && message.indexes.length) { + object.indexes = []; + for (var j = 0; j < message.indexes.length; ++j) + object.indexes[j] = $root.google.firestore.admin.v1.Index.toObject(message.indexes[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListIndexesResponse to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ListIndexesResponse + * @instance + * @returns {Object.} JSON object + */ + ListIndexesResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListIndexesResponse + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ListIndexesResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListIndexesResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ListIndexesResponse"; + }; + + return ListIndexesResponse; + })(); + + v1.GetIndexRequest = (function() { + + /** + * Properties of a GetIndexRequest. + * @memberof google.firestore.admin.v1 + * @interface IGetIndexRequest + * @property {string|null} [name] GetIndexRequest name + */ + + /** + * Constructs a new GetIndexRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a GetIndexRequest. + * @implements IGetIndexRequest + * @constructor + * @param {google.firestore.admin.v1.IGetIndexRequest=} [properties] Properties to set + */ + function GetIndexRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetIndexRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.GetIndexRequest + * @instance + */ + GetIndexRequest.prototype.name = ""; + + /** + * Creates a GetIndexRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.GetIndexRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.GetIndexRequest} GetIndexRequest + */ + GetIndexRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.GetIndexRequest) + return object; + var message = new $root.google.firestore.admin.v1.GetIndexRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetIndexRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.GetIndexRequest + * @static + * @param {google.firestore.admin.v1.GetIndexRequest} message GetIndexRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetIndexRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetIndexRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.GetIndexRequest + * @instance + * @returns {Object.} JSON object + */ + GetIndexRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetIndexRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.GetIndexRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetIndexRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.GetIndexRequest"; + }; + + return GetIndexRequest; + })(); + + v1.DeleteIndexRequest = (function() { + + /** + * Properties of a DeleteIndexRequest. + * @memberof google.firestore.admin.v1 + * @interface IDeleteIndexRequest + * @property {string|null} [name] DeleteIndexRequest name + */ + + /** + * Constructs a new DeleteIndexRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a DeleteIndexRequest. + * @implements IDeleteIndexRequest + * @constructor + * @param {google.firestore.admin.v1.IDeleteIndexRequest=} [properties] Properties to set + */ + function DeleteIndexRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteIndexRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.DeleteIndexRequest + * @instance + */ + DeleteIndexRequest.prototype.name = ""; + + /** + * Creates a DeleteIndexRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.DeleteIndexRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.DeleteIndexRequest} DeleteIndexRequest + */ + DeleteIndexRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.DeleteIndexRequest) + return object; + var message = new $root.google.firestore.admin.v1.DeleteIndexRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a DeleteIndexRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.DeleteIndexRequest + * @static + * @param {google.firestore.admin.v1.DeleteIndexRequest} message DeleteIndexRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteIndexRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this DeleteIndexRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.DeleteIndexRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteIndexRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteIndexRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.DeleteIndexRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteIndexRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.DeleteIndexRequest"; + }; + + return DeleteIndexRequest; + })(); + + v1.UpdateFieldRequest = (function() { + + /** + * Properties of an UpdateFieldRequest. + * @memberof google.firestore.admin.v1 + * @interface IUpdateFieldRequest + * @property {google.firestore.admin.v1.IField|null} [field] UpdateFieldRequest field + * @property {google.protobuf.IFieldMask|null} [updateMask] UpdateFieldRequest updateMask + */ + + /** + * Constructs a new UpdateFieldRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents an UpdateFieldRequest. + * @implements IUpdateFieldRequest + * @constructor + * @param {google.firestore.admin.v1.IUpdateFieldRequest=} [properties] Properties to set + */ + function UpdateFieldRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateFieldRequest field. + * @member {google.firestore.admin.v1.IField|null|undefined} field + * @memberof google.firestore.admin.v1.UpdateFieldRequest + * @instance + */ + UpdateFieldRequest.prototype.field = null; + + /** + * UpdateFieldRequest updateMask. + * @member {google.protobuf.IFieldMask|null|undefined} updateMask + * @memberof google.firestore.admin.v1.UpdateFieldRequest + * @instance + */ + UpdateFieldRequest.prototype.updateMask = null; + + /** + * Creates an UpdateFieldRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.UpdateFieldRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.UpdateFieldRequest} UpdateFieldRequest + */ + UpdateFieldRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.UpdateFieldRequest) + return object; + var message = new $root.google.firestore.admin.v1.UpdateFieldRequest(); + if (object.field != null) { + if (typeof object.field !== "object") + throw TypeError(".google.firestore.admin.v1.UpdateFieldRequest.field: object expected"); + message.field = $root.google.firestore.admin.v1.Field.fromObject(object.field); + } + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.firestore.admin.v1.UpdateFieldRequest.updateMask: object expected"); + message.updateMask = $root.google.protobuf.FieldMask.fromObject(object.updateMask); + } + return message; + }; + + /** + * Creates a plain object from an UpdateFieldRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.UpdateFieldRequest + * @static + * @param {google.firestore.admin.v1.UpdateFieldRequest} message UpdateFieldRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateFieldRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.field = null; + object.updateMask = null; + } + if (message.field != null && message.hasOwnProperty("field")) + object.field = $root.google.firestore.admin.v1.Field.toObject(message.field, options); + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.protobuf.FieldMask.toObject(message.updateMask, options); + return object; + }; + + /** + * Converts this UpdateFieldRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.UpdateFieldRequest + * @instance + * @returns {Object.} JSON object + */ + UpdateFieldRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateFieldRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.UpdateFieldRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateFieldRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.UpdateFieldRequest"; + }; + + return UpdateFieldRequest; + })(); + + v1.GetFieldRequest = (function() { + + /** + * Properties of a GetFieldRequest. + * @memberof google.firestore.admin.v1 + * @interface IGetFieldRequest + * @property {string|null} [name] GetFieldRequest name + */ + + /** + * Constructs a new GetFieldRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a GetFieldRequest. + * @implements IGetFieldRequest + * @constructor + * @param {google.firestore.admin.v1.IGetFieldRequest=} [properties] Properties to set + */ + function GetFieldRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetFieldRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.GetFieldRequest + * @instance + */ + GetFieldRequest.prototype.name = ""; + + /** + * Creates a GetFieldRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.GetFieldRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.GetFieldRequest} GetFieldRequest + */ + GetFieldRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.GetFieldRequest) + return object; + var message = new $root.google.firestore.admin.v1.GetFieldRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetFieldRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.GetFieldRequest + * @static + * @param {google.firestore.admin.v1.GetFieldRequest} message GetFieldRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetFieldRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetFieldRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.GetFieldRequest + * @instance + * @returns {Object.} JSON object + */ + GetFieldRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetFieldRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.GetFieldRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetFieldRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.GetFieldRequest"; + }; + + return GetFieldRequest; + })(); + + v1.ListFieldsRequest = (function() { + + /** + * Properties of a ListFieldsRequest. + * @memberof google.firestore.admin.v1 + * @interface IListFieldsRequest + * @property {string|null} [parent] ListFieldsRequest parent + * @property {string|null} [filter] ListFieldsRequest filter + * @property {number|null} [pageSize] ListFieldsRequest pageSize + * @property {string|null} [pageToken] ListFieldsRequest pageToken + */ + + /** + * Constructs a new ListFieldsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a ListFieldsRequest. + * @implements IListFieldsRequest + * @constructor + * @param {google.firestore.admin.v1.IListFieldsRequest=} [properties] Properties to set + */ + function ListFieldsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListFieldsRequest parent. + * @member {string} parent + * @memberof google.firestore.admin.v1.ListFieldsRequest + * @instance + */ + ListFieldsRequest.prototype.parent = ""; + + /** + * ListFieldsRequest filter. + * @member {string} filter + * @memberof google.firestore.admin.v1.ListFieldsRequest + * @instance + */ + ListFieldsRequest.prototype.filter = ""; + + /** + * ListFieldsRequest pageSize. + * @member {number} pageSize + * @memberof google.firestore.admin.v1.ListFieldsRequest + * @instance + */ + ListFieldsRequest.prototype.pageSize = 0; + + /** + * ListFieldsRequest pageToken. + * @member {string} pageToken + * @memberof google.firestore.admin.v1.ListFieldsRequest + * @instance + */ + ListFieldsRequest.prototype.pageToken = ""; + + /** + * Creates a ListFieldsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ListFieldsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ListFieldsRequest} ListFieldsRequest + */ + ListFieldsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ListFieldsRequest) + return object; + var message = new $root.google.firestore.admin.v1.ListFieldsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListFieldsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ListFieldsRequest + * @static + * @param {google.firestore.admin.v1.ListFieldsRequest} message ListFieldsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListFieldsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListFieldsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ListFieldsRequest + * @instance + * @returns {Object.} JSON object + */ + ListFieldsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListFieldsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ListFieldsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListFieldsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ListFieldsRequest"; + }; + + return ListFieldsRequest; + })(); + + v1.ListFieldsResponse = (function() { + + /** + * Properties of a ListFieldsResponse. + * @memberof google.firestore.admin.v1 + * @interface IListFieldsResponse + * @property {Array.|null} [fields] ListFieldsResponse fields + * @property {string|null} [nextPageToken] ListFieldsResponse nextPageToken + */ + + /** + * Constructs a new ListFieldsResponse. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a ListFieldsResponse. + * @implements IListFieldsResponse + * @constructor + * @param {google.firestore.admin.v1.IListFieldsResponse=} [properties] Properties to set + */ + function ListFieldsResponse(properties) { + this.fields = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListFieldsResponse fields. + * @member {Array.} fields + * @memberof google.firestore.admin.v1.ListFieldsResponse + * @instance + */ + ListFieldsResponse.prototype.fields = $util.emptyArray; + + /** + * ListFieldsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.firestore.admin.v1.ListFieldsResponse + * @instance + */ + ListFieldsResponse.prototype.nextPageToken = ""; + + /** + * Creates a ListFieldsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ListFieldsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ListFieldsResponse} ListFieldsResponse + */ + ListFieldsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ListFieldsResponse) + return object; + var message = new $root.google.firestore.admin.v1.ListFieldsResponse(); + if (object.fields) { + if (!Array.isArray(object.fields)) + throw TypeError(".google.firestore.admin.v1.ListFieldsResponse.fields: array expected"); + message.fields = []; + for (var i = 0; i < object.fields.length; ++i) { + if (typeof object.fields[i] !== "object") + throw TypeError(".google.firestore.admin.v1.ListFieldsResponse.fields: object expected"); + message.fields[i] = $root.google.firestore.admin.v1.Field.fromObject(object.fields[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListFieldsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ListFieldsResponse + * @static + * @param {google.firestore.admin.v1.ListFieldsResponse} message ListFieldsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListFieldsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.fields = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.fields && message.fields.length) { + object.fields = []; + for (var j = 0; j < message.fields.length; ++j) + object.fields[j] = $root.google.firestore.admin.v1.Field.toObject(message.fields[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListFieldsResponse to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ListFieldsResponse + * @instance + * @returns {Object.} JSON object + */ + ListFieldsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListFieldsResponse + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ListFieldsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListFieldsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ListFieldsResponse"; + }; + + return ListFieldsResponse; + })(); + + v1.ExportDocumentsRequest = (function() { + + /** + * Properties of an ExportDocumentsRequest. + * @memberof google.firestore.admin.v1 + * @interface IExportDocumentsRequest + * @property {string|null} [name] ExportDocumentsRequest name + * @property {Array.|null} [collectionIds] ExportDocumentsRequest collectionIds + * @property {string|null} [outputUriPrefix] ExportDocumentsRequest outputUriPrefix + * @property {Array.|null} [namespaceIds] ExportDocumentsRequest namespaceIds + * @property {google.protobuf.ITimestamp|null} [snapshotTime] ExportDocumentsRequest snapshotTime + */ + + /** + * Constructs a new ExportDocumentsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents an ExportDocumentsRequest. + * @implements IExportDocumentsRequest + * @constructor + * @param {google.firestore.admin.v1.IExportDocumentsRequest=} [properties] Properties to set + */ + function ExportDocumentsRequest(properties) { + this.collectionIds = []; + this.namespaceIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExportDocumentsRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.ExportDocumentsRequest + * @instance + */ + ExportDocumentsRequest.prototype.name = ""; + + /** + * ExportDocumentsRequest collectionIds. + * @member {Array.} collectionIds + * @memberof google.firestore.admin.v1.ExportDocumentsRequest + * @instance + */ + ExportDocumentsRequest.prototype.collectionIds = $util.emptyArray; + + /** + * ExportDocumentsRequest outputUriPrefix. + * @member {string} outputUriPrefix + * @memberof google.firestore.admin.v1.ExportDocumentsRequest + * @instance + */ + ExportDocumentsRequest.prototype.outputUriPrefix = ""; + + /** + * ExportDocumentsRequest namespaceIds. + * @member {Array.} namespaceIds + * @memberof google.firestore.admin.v1.ExportDocumentsRequest + * @instance + */ + ExportDocumentsRequest.prototype.namespaceIds = $util.emptyArray; + + /** + * ExportDocumentsRequest snapshotTime. + * @member {google.protobuf.ITimestamp|null|undefined} snapshotTime + * @memberof google.firestore.admin.v1.ExportDocumentsRequest + * @instance + */ + ExportDocumentsRequest.prototype.snapshotTime = null; + + /** + * Creates an ExportDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ExportDocumentsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ExportDocumentsRequest} ExportDocumentsRequest + */ + ExportDocumentsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ExportDocumentsRequest) + return object; + var message = new $root.google.firestore.admin.v1.ExportDocumentsRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.collectionIds) { + if (!Array.isArray(object.collectionIds)) + throw TypeError(".google.firestore.admin.v1.ExportDocumentsRequest.collectionIds: array expected"); + message.collectionIds = []; + for (var i = 0; i < object.collectionIds.length; ++i) + message.collectionIds[i] = String(object.collectionIds[i]); + } + if (object.outputUriPrefix != null) + message.outputUriPrefix = String(object.outputUriPrefix); + if (object.namespaceIds) { + if (!Array.isArray(object.namespaceIds)) + throw TypeError(".google.firestore.admin.v1.ExportDocumentsRequest.namespaceIds: array expected"); + message.namespaceIds = []; + for (var i = 0; i < object.namespaceIds.length; ++i) + message.namespaceIds[i] = String(object.namespaceIds[i]); + } + if (object.snapshotTime != null) { + if (typeof object.snapshotTime !== "object") + throw TypeError(".google.firestore.admin.v1.ExportDocumentsRequest.snapshotTime: object expected"); + message.snapshotTime = $root.google.protobuf.Timestamp.fromObject(object.snapshotTime); + } + return message; + }; + + /** + * Creates a plain object from an ExportDocumentsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ExportDocumentsRequest + * @static + * @param {google.firestore.admin.v1.ExportDocumentsRequest} message ExportDocumentsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExportDocumentsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.collectionIds = []; + object.namespaceIds = []; + } + if (options.defaults) { + object.name = ""; + object.outputUriPrefix = ""; + object.snapshotTime = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.collectionIds && message.collectionIds.length) { + object.collectionIds = []; + for (var j = 0; j < message.collectionIds.length; ++j) + object.collectionIds[j] = message.collectionIds[j]; + } + if (message.outputUriPrefix != null && message.hasOwnProperty("outputUriPrefix")) + object.outputUriPrefix = message.outputUriPrefix; + if (message.namespaceIds && message.namespaceIds.length) { + object.namespaceIds = []; + for (var j = 0; j < message.namespaceIds.length; ++j) + object.namespaceIds[j] = message.namespaceIds[j]; + } + if (message.snapshotTime != null && message.hasOwnProperty("snapshotTime")) + object.snapshotTime = $root.google.protobuf.Timestamp.toObject(message.snapshotTime, options); + return object; + }; + + /** + * Converts this ExportDocumentsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ExportDocumentsRequest + * @instance + * @returns {Object.} JSON object + */ + ExportDocumentsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExportDocumentsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ExportDocumentsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExportDocumentsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ExportDocumentsRequest"; + }; + + return ExportDocumentsRequest; + })(); + + v1.ImportDocumentsRequest = (function() { + + /** + * Properties of an ImportDocumentsRequest. + * @memberof google.firestore.admin.v1 + * @interface IImportDocumentsRequest + * @property {string|null} [name] ImportDocumentsRequest name + * @property {Array.|null} [collectionIds] ImportDocumentsRequest collectionIds + * @property {string|null} [inputUriPrefix] ImportDocumentsRequest inputUriPrefix + * @property {Array.|null} [namespaceIds] ImportDocumentsRequest namespaceIds + */ + + /** + * Constructs a new ImportDocumentsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents an ImportDocumentsRequest. + * @implements IImportDocumentsRequest + * @constructor + * @param {google.firestore.admin.v1.IImportDocumentsRequest=} [properties] Properties to set + */ + function ImportDocumentsRequest(properties) { + this.collectionIds = []; + this.namespaceIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ImportDocumentsRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.ImportDocumentsRequest + * @instance + */ + ImportDocumentsRequest.prototype.name = ""; + + /** + * ImportDocumentsRequest collectionIds. + * @member {Array.} collectionIds + * @memberof google.firestore.admin.v1.ImportDocumentsRequest + * @instance + */ + ImportDocumentsRequest.prototype.collectionIds = $util.emptyArray; + + /** + * ImportDocumentsRequest inputUriPrefix. + * @member {string} inputUriPrefix + * @memberof google.firestore.admin.v1.ImportDocumentsRequest + * @instance + */ + ImportDocumentsRequest.prototype.inputUriPrefix = ""; + + /** + * ImportDocumentsRequest namespaceIds. + * @member {Array.} namespaceIds + * @memberof google.firestore.admin.v1.ImportDocumentsRequest + * @instance + */ + ImportDocumentsRequest.prototype.namespaceIds = $util.emptyArray; + + /** + * Creates an ImportDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ImportDocumentsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ImportDocumentsRequest} ImportDocumentsRequest + */ + ImportDocumentsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ImportDocumentsRequest) + return object; + var message = new $root.google.firestore.admin.v1.ImportDocumentsRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.collectionIds) { + if (!Array.isArray(object.collectionIds)) + throw TypeError(".google.firestore.admin.v1.ImportDocumentsRequest.collectionIds: array expected"); + message.collectionIds = []; + for (var i = 0; i < object.collectionIds.length; ++i) + message.collectionIds[i] = String(object.collectionIds[i]); + } + if (object.inputUriPrefix != null) + message.inputUriPrefix = String(object.inputUriPrefix); + if (object.namespaceIds) { + if (!Array.isArray(object.namespaceIds)) + throw TypeError(".google.firestore.admin.v1.ImportDocumentsRequest.namespaceIds: array expected"); + message.namespaceIds = []; + for (var i = 0; i < object.namespaceIds.length; ++i) + message.namespaceIds[i] = String(object.namespaceIds[i]); + } + return message; + }; + + /** + * Creates a plain object from an ImportDocumentsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ImportDocumentsRequest + * @static + * @param {google.firestore.admin.v1.ImportDocumentsRequest} message ImportDocumentsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ImportDocumentsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.collectionIds = []; + object.namespaceIds = []; + } + if (options.defaults) { + object.name = ""; + object.inputUriPrefix = ""; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.collectionIds && message.collectionIds.length) { + object.collectionIds = []; + for (var j = 0; j < message.collectionIds.length; ++j) + object.collectionIds[j] = message.collectionIds[j]; + } + if (message.inputUriPrefix != null && message.hasOwnProperty("inputUriPrefix")) + object.inputUriPrefix = message.inputUriPrefix; + if (message.namespaceIds && message.namespaceIds.length) { + object.namespaceIds = []; + for (var j = 0; j < message.namespaceIds.length; ++j) + object.namespaceIds[j] = message.namespaceIds[j]; + } + return object; + }; + + /** + * Converts this ImportDocumentsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ImportDocumentsRequest + * @instance + * @returns {Object.} JSON object + */ + ImportDocumentsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ImportDocumentsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ImportDocumentsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ImportDocumentsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ImportDocumentsRequest"; + }; + + return ImportDocumentsRequest; + })(); + + v1.BulkDeleteDocumentsRequest = (function() { + + /** + * Properties of a BulkDeleteDocumentsRequest. + * @memberof google.firestore.admin.v1 + * @interface IBulkDeleteDocumentsRequest + * @property {string|null} [name] BulkDeleteDocumentsRequest name + * @property {Array.|null} [collectionIds] BulkDeleteDocumentsRequest collectionIds + * @property {Array.|null} [namespaceIds] BulkDeleteDocumentsRequest namespaceIds + */ + + /** + * Constructs a new BulkDeleteDocumentsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a BulkDeleteDocumentsRequest. + * @implements IBulkDeleteDocumentsRequest + * @constructor + * @param {google.firestore.admin.v1.IBulkDeleteDocumentsRequest=} [properties] Properties to set + */ + function BulkDeleteDocumentsRequest(properties) { + this.collectionIds = []; + this.namespaceIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BulkDeleteDocumentsRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsRequest + * @instance + */ + BulkDeleteDocumentsRequest.prototype.name = ""; + + /** + * BulkDeleteDocumentsRequest collectionIds. + * @member {Array.} collectionIds + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsRequest + * @instance + */ + BulkDeleteDocumentsRequest.prototype.collectionIds = $util.emptyArray; + + /** + * BulkDeleteDocumentsRequest namespaceIds. + * @member {Array.} namespaceIds + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsRequest + * @instance + */ + BulkDeleteDocumentsRequest.prototype.namespaceIds = $util.emptyArray; + + /** + * Creates a BulkDeleteDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.BulkDeleteDocumentsRequest} BulkDeleteDocumentsRequest + */ + BulkDeleteDocumentsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.BulkDeleteDocumentsRequest) + return object; + var message = new $root.google.firestore.admin.v1.BulkDeleteDocumentsRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.collectionIds) { + if (!Array.isArray(object.collectionIds)) + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsRequest.collectionIds: array expected"); + message.collectionIds = []; + for (var i = 0; i < object.collectionIds.length; ++i) + message.collectionIds[i] = String(object.collectionIds[i]); + } + if (object.namespaceIds) { + if (!Array.isArray(object.namespaceIds)) + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsRequest.namespaceIds: array expected"); + message.namespaceIds = []; + for (var i = 0; i < object.namespaceIds.length; ++i) + message.namespaceIds[i] = String(object.namespaceIds[i]); + } + return message; + }; + + /** + * Creates a plain object from a BulkDeleteDocumentsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsRequest + * @static + * @param {google.firestore.admin.v1.BulkDeleteDocumentsRequest} message BulkDeleteDocumentsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BulkDeleteDocumentsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.collectionIds = []; + object.namespaceIds = []; + } + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.collectionIds && message.collectionIds.length) { + object.collectionIds = []; + for (var j = 0; j < message.collectionIds.length; ++j) + object.collectionIds[j] = message.collectionIds[j]; + } + if (message.namespaceIds && message.namespaceIds.length) { + object.namespaceIds = []; + for (var j = 0; j < message.namespaceIds.length; ++j) + object.namespaceIds[j] = message.namespaceIds[j]; + } + return object; + }; + + /** + * Converts this BulkDeleteDocumentsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsRequest + * @instance + * @returns {Object.} JSON object + */ + BulkDeleteDocumentsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BulkDeleteDocumentsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BulkDeleteDocumentsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.BulkDeleteDocumentsRequest"; + }; + + return BulkDeleteDocumentsRequest; + })(); + + v1.BulkDeleteDocumentsResponse = (function() { + + /** + * Properties of a BulkDeleteDocumentsResponse. + * @memberof google.firestore.admin.v1 + * @interface IBulkDeleteDocumentsResponse + */ + + /** + * Constructs a new BulkDeleteDocumentsResponse. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a BulkDeleteDocumentsResponse. + * @implements IBulkDeleteDocumentsResponse + * @constructor + * @param {google.firestore.admin.v1.IBulkDeleteDocumentsResponse=} [properties] Properties to set + */ + function BulkDeleteDocumentsResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a BulkDeleteDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.BulkDeleteDocumentsResponse} BulkDeleteDocumentsResponse + */ + BulkDeleteDocumentsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.BulkDeleteDocumentsResponse) + return object; + return new $root.google.firestore.admin.v1.BulkDeleteDocumentsResponse(); + }; + + /** + * Creates a plain object from a BulkDeleteDocumentsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsResponse + * @static + * @param {google.firestore.admin.v1.BulkDeleteDocumentsResponse} message BulkDeleteDocumentsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BulkDeleteDocumentsResponse.toObject = function toObject() { + return {}; + }; + + /** + * Converts this BulkDeleteDocumentsResponse to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsResponse + * @instance + * @returns {Object.} JSON object + */ + BulkDeleteDocumentsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BulkDeleteDocumentsResponse + * @function getTypeUrl + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BulkDeleteDocumentsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.BulkDeleteDocumentsResponse"; + }; + + return BulkDeleteDocumentsResponse; + })(); + + v1.GetBackupRequest = (function() { + + /** + * Properties of a GetBackupRequest. + * @memberof google.firestore.admin.v1 + * @interface IGetBackupRequest + * @property {string|null} [name] GetBackupRequest name + */ + + /** + * Constructs a new GetBackupRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a GetBackupRequest. + * @implements IGetBackupRequest + * @constructor + * @param {google.firestore.admin.v1.IGetBackupRequest=} [properties] Properties to set + */ + function GetBackupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetBackupRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.GetBackupRequest + * @instance + */ + GetBackupRequest.prototype.name = ""; + + /** + * Creates a GetBackupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.GetBackupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.GetBackupRequest} GetBackupRequest + */ + GetBackupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.GetBackupRequest) + return object; + var message = new $root.google.firestore.admin.v1.GetBackupRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetBackupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.GetBackupRequest + * @static + * @param {google.firestore.admin.v1.GetBackupRequest} message GetBackupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetBackupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetBackupRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.GetBackupRequest + * @instance + * @returns {Object.} JSON object + */ + GetBackupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetBackupRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.GetBackupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetBackupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.GetBackupRequest"; + }; + + return GetBackupRequest; + })(); + + v1.ListBackupsRequest = (function() { + + /** + * Properties of a ListBackupsRequest. + * @memberof google.firestore.admin.v1 + * @interface IListBackupsRequest + * @property {string|null} [parent] ListBackupsRequest parent + * @property {string|null} [filter] ListBackupsRequest filter + */ + + /** + * Constructs a new ListBackupsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a ListBackupsRequest. + * @implements IListBackupsRequest + * @constructor + * @param {google.firestore.admin.v1.IListBackupsRequest=} [properties] Properties to set + */ + function ListBackupsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListBackupsRequest parent. + * @member {string} parent + * @memberof google.firestore.admin.v1.ListBackupsRequest + * @instance + */ + ListBackupsRequest.prototype.parent = ""; + + /** + * ListBackupsRequest filter. + * @member {string} filter + * @memberof google.firestore.admin.v1.ListBackupsRequest + * @instance + */ + ListBackupsRequest.prototype.filter = ""; + + /** + * Creates a ListBackupsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ListBackupsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ListBackupsRequest} ListBackupsRequest + */ + ListBackupsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ListBackupsRequest) + return object; + var message = new $root.google.firestore.admin.v1.ListBackupsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.filter != null) + message.filter = String(object.filter); + return message; + }; + + /** + * Creates a plain object from a ListBackupsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ListBackupsRequest + * @static + * @param {google.firestore.admin.v1.ListBackupsRequest} message ListBackupsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListBackupsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.filter = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + return object; + }; + + /** + * Converts this ListBackupsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ListBackupsRequest + * @instance + * @returns {Object.} JSON object + */ + ListBackupsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListBackupsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ListBackupsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListBackupsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ListBackupsRequest"; + }; + + return ListBackupsRequest; + })(); + + v1.ListBackupsResponse = (function() { + + /** + * Properties of a ListBackupsResponse. + * @memberof google.firestore.admin.v1 + * @interface IListBackupsResponse + * @property {Array.|null} [backups] ListBackupsResponse backups + * @property {Array.|null} [unreachable] ListBackupsResponse unreachable + */ + + /** + * Constructs a new ListBackupsResponse. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a ListBackupsResponse. + * @implements IListBackupsResponse + * @constructor + * @param {google.firestore.admin.v1.IListBackupsResponse=} [properties] Properties to set + */ + function ListBackupsResponse(properties) { + this.backups = []; + this.unreachable = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListBackupsResponse backups. + * @member {Array.} backups + * @memberof google.firestore.admin.v1.ListBackupsResponse + * @instance + */ + ListBackupsResponse.prototype.backups = $util.emptyArray; + + /** + * ListBackupsResponse unreachable. + * @member {Array.} unreachable + * @memberof google.firestore.admin.v1.ListBackupsResponse + * @instance + */ + ListBackupsResponse.prototype.unreachable = $util.emptyArray; + + /** + * Creates a ListBackupsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ListBackupsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ListBackupsResponse} ListBackupsResponse + */ + ListBackupsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ListBackupsResponse) + return object; + var message = new $root.google.firestore.admin.v1.ListBackupsResponse(); + if (object.backups) { + if (!Array.isArray(object.backups)) + throw TypeError(".google.firestore.admin.v1.ListBackupsResponse.backups: array expected"); + message.backups = []; + for (var i = 0; i < object.backups.length; ++i) { + if (typeof object.backups[i] !== "object") + throw TypeError(".google.firestore.admin.v1.ListBackupsResponse.backups: object expected"); + message.backups[i] = $root.google.firestore.admin.v1.Backup.fromObject(object.backups[i]); + } + } + if (object.unreachable) { + if (!Array.isArray(object.unreachable)) + throw TypeError(".google.firestore.admin.v1.ListBackupsResponse.unreachable: array expected"); + message.unreachable = []; + for (var i = 0; i < object.unreachable.length; ++i) + message.unreachable[i] = String(object.unreachable[i]); + } + return message; + }; + + /** + * Creates a plain object from a ListBackupsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ListBackupsResponse + * @static + * @param {google.firestore.admin.v1.ListBackupsResponse} message ListBackupsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListBackupsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.backups = []; + object.unreachable = []; + } + if (message.backups && message.backups.length) { + object.backups = []; + for (var j = 0; j < message.backups.length; ++j) + object.backups[j] = $root.google.firestore.admin.v1.Backup.toObject(message.backups[j], options); + } + if (message.unreachable && message.unreachable.length) { + object.unreachable = []; + for (var j = 0; j < message.unreachable.length; ++j) + object.unreachable[j] = message.unreachable[j]; + } + return object; + }; + + /** + * Converts this ListBackupsResponse to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ListBackupsResponse + * @instance + * @returns {Object.} JSON object + */ + ListBackupsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListBackupsResponse + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ListBackupsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListBackupsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ListBackupsResponse"; + }; + + return ListBackupsResponse; + })(); + + v1.DeleteBackupRequest = (function() { + + /** + * Properties of a DeleteBackupRequest. + * @memberof google.firestore.admin.v1 + * @interface IDeleteBackupRequest + * @property {string|null} [name] DeleteBackupRequest name + */ + + /** + * Constructs a new DeleteBackupRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a DeleteBackupRequest. + * @implements IDeleteBackupRequest + * @constructor + * @param {google.firestore.admin.v1.IDeleteBackupRequest=} [properties] Properties to set + */ + function DeleteBackupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteBackupRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.DeleteBackupRequest + * @instance + */ + DeleteBackupRequest.prototype.name = ""; + + /** + * Creates a DeleteBackupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.DeleteBackupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.DeleteBackupRequest} DeleteBackupRequest + */ + DeleteBackupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.DeleteBackupRequest) + return object; + var message = new $root.google.firestore.admin.v1.DeleteBackupRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a DeleteBackupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.DeleteBackupRequest + * @static + * @param {google.firestore.admin.v1.DeleteBackupRequest} message DeleteBackupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteBackupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this DeleteBackupRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.DeleteBackupRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteBackupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteBackupRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.DeleteBackupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteBackupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.DeleteBackupRequest"; + }; + + return DeleteBackupRequest; + })(); + + v1.RestoreDatabaseRequest = (function() { + + /** + * Properties of a RestoreDatabaseRequest. + * @memberof google.firestore.admin.v1 + * @interface IRestoreDatabaseRequest + * @property {string|null} [parent] RestoreDatabaseRequest parent + * @property {string|null} [databaseId] RestoreDatabaseRequest databaseId + * @property {string|null} [backup] RestoreDatabaseRequest backup + * @property {google.firestore.admin.v1.Database.IEncryptionConfig|null} [encryptionConfig] RestoreDatabaseRequest encryptionConfig + * @property {Object.|null} [tags] RestoreDatabaseRequest tags + */ + + /** + * Constructs a new RestoreDatabaseRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a RestoreDatabaseRequest. + * @implements IRestoreDatabaseRequest + * @constructor + * @param {google.firestore.admin.v1.IRestoreDatabaseRequest=} [properties] Properties to set + */ + function RestoreDatabaseRequest(properties) { + this.tags = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RestoreDatabaseRequest parent. + * @member {string} parent + * @memberof google.firestore.admin.v1.RestoreDatabaseRequest + * @instance + */ + RestoreDatabaseRequest.prototype.parent = ""; + + /** + * RestoreDatabaseRequest databaseId. + * @member {string} databaseId + * @memberof google.firestore.admin.v1.RestoreDatabaseRequest + * @instance + */ + RestoreDatabaseRequest.prototype.databaseId = ""; + + /** + * RestoreDatabaseRequest backup. + * @member {string} backup + * @memberof google.firestore.admin.v1.RestoreDatabaseRequest + * @instance + */ + RestoreDatabaseRequest.prototype.backup = ""; + + /** + * RestoreDatabaseRequest encryptionConfig. + * @member {google.firestore.admin.v1.Database.IEncryptionConfig|null|undefined} encryptionConfig + * @memberof google.firestore.admin.v1.RestoreDatabaseRequest + * @instance + */ + RestoreDatabaseRequest.prototype.encryptionConfig = null; + + /** + * RestoreDatabaseRequest tags. + * @member {Object.} tags + * @memberof google.firestore.admin.v1.RestoreDatabaseRequest + * @instance + */ + RestoreDatabaseRequest.prototype.tags = $util.emptyObject; + + /** + * Creates a RestoreDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.RestoreDatabaseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.RestoreDatabaseRequest} RestoreDatabaseRequest + */ + RestoreDatabaseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.RestoreDatabaseRequest) + return object; + var message = new $root.google.firestore.admin.v1.RestoreDatabaseRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.databaseId != null) + message.databaseId = String(object.databaseId); + if (object.backup != null) + message.backup = String(object.backup); + if (object.encryptionConfig != null) { + if (typeof object.encryptionConfig !== "object") + throw TypeError(".google.firestore.admin.v1.RestoreDatabaseRequest.encryptionConfig: object expected"); + message.encryptionConfig = $root.google.firestore.admin.v1.Database.EncryptionConfig.fromObject(object.encryptionConfig); + } + if (object.tags) { + if (typeof object.tags !== "object") + throw TypeError(".google.firestore.admin.v1.RestoreDatabaseRequest.tags: object expected"); + message.tags = {}; + for (var keys = Object.keys(object.tags), i = 0; i < keys.length; ++i) + message.tags[keys[i]] = String(object.tags[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a RestoreDatabaseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.RestoreDatabaseRequest + * @static + * @param {google.firestore.admin.v1.RestoreDatabaseRequest} message RestoreDatabaseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RestoreDatabaseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.tags = {}; + if (options.defaults) { + object.parent = ""; + object.databaseId = ""; + object.backup = ""; + object.encryptionConfig = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + object.databaseId = message.databaseId; + if (message.backup != null && message.hasOwnProperty("backup")) + object.backup = message.backup; + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) + object.encryptionConfig = $root.google.firestore.admin.v1.Database.EncryptionConfig.toObject(message.encryptionConfig, options); + var keys2; + if (message.tags && (keys2 = Object.keys(message.tags)).length) { + object.tags = {}; + for (var j = 0; j < keys2.length; ++j) + object.tags[keys2[j]] = message.tags[keys2[j]]; + } + return object; + }; + + /** + * Converts this RestoreDatabaseRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.RestoreDatabaseRequest + * @instance + * @returns {Object.} JSON object + */ + RestoreDatabaseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RestoreDatabaseRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.RestoreDatabaseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RestoreDatabaseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.RestoreDatabaseRequest"; + }; + + return RestoreDatabaseRequest; + })(); + + v1.CloneDatabaseRequest = (function() { + + /** + * Properties of a CloneDatabaseRequest. + * @memberof google.firestore.admin.v1 + * @interface ICloneDatabaseRequest + * @property {string|null} [parent] CloneDatabaseRequest parent + * @property {string|null} [databaseId] CloneDatabaseRequest databaseId + * @property {google.firestore.admin.v1.IPitrSnapshot|null} [pitrSnapshot] CloneDatabaseRequest pitrSnapshot + * @property {google.firestore.admin.v1.Database.IEncryptionConfig|null} [encryptionConfig] CloneDatabaseRequest encryptionConfig + * @property {Object.|null} [tags] CloneDatabaseRequest tags + */ + + /** + * Constructs a new CloneDatabaseRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a CloneDatabaseRequest. + * @implements ICloneDatabaseRequest + * @constructor + * @param {google.firestore.admin.v1.ICloneDatabaseRequest=} [properties] Properties to set + */ + function CloneDatabaseRequest(properties) { + this.tags = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CloneDatabaseRequest parent. + * @member {string} parent + * @memberof google.firestore.admin.v1.CloneDatabaseRequest + * @instance + */ + CloneDatabaseRequest.prototype.parent = ""; + + /** + * CloneDatabaseRequest databaseId. + * @member {string} databaseId + * @memberof google.firestore.admin.v1.CloneDatabaseRequest + * @instance + */ + CloneDatabaseRequest.prototype.databaseId = ""; + + /** + * CloneDatabaseRequest pitrSnapshot. + * @member {google.firestore.admin.v1.IPitrSnapshot|null|undefined} pitrSnapshot + * @memberof google.firestore.admin.v1.CloneDatabaseRequest + * @instance + */ + CloneDatabaseRequest.prototype.pitrSnapshot = null; + + /** + * CloneDatabaseRequest encryptionConfig. + * @member {google.firestore.admin.v1.Database.IEncryptionConfig|null|undefined} encryptionConfig + * @memberof google.firestore.admin.v1.CloneDatabaseRequest + * @instance + */ + CloneDatabaseRequest.prototype.encryptionConfig = null; + + /** + * CloneDatabaseRequest tags. + * @member {Object.} tags + * @memberof google.firestore.admin.v1.CloneDatabaseRequest + * @instance + */ + CloneDatabaseRequest.prototype.tags = $util.emptyObject; + + /** + * Creates a CloneDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.CloneDatabaseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.CloneDatabaseRequest} CloneDatabaseRequest + */ + CloneDatabaseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.CloneDatabaseRequest) + return object; + var message = new $root.google.firestore.admin.v1.CloneDatabaseRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.databaseId != null) + message.databaseId = String(object.databaseId); + if (object.pitrSnapshot != null) { + if (typeof object.pitrSnapshot !== "object") + throw TypeError(".google.firestore.admin.v1.CloneDatabaseRequest.pitrSnapshot: object expected"); + message.pitrSnapshot = $root.google.firestore.admin.v1.PitrSnapshot.fromObject(object.pitrSnapshot); + } + if (object.encryptionConfig != null) { + if (typeof object.encryptionConfig !== "object") + throw TypeError(".google.firestore.admin.v1.CloneDatabaseRequest.encryptionConfig: object expected"); + message.encryptionConfig = $root.google.firestore.admin.v1.Database.EncryptionConfig.fromObject(object.encryptionConfig); + } + if (object.tags) { + if (typeof object.tags !== "object") + throw TypeError(".google.firestore.admin.v1.CloneDatabaseRequest.tags: object expected"); + message.tags = {}; + for (var keys = Object.keys(object.tags), i = 0; i < keys.length; ++i) + message.tags[keys[i]] = String(object.tags[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a CloneDatabaseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.CloneDatabaseRequest + * @static + * @param {google.firestore.admin.v1.CloneDatabaseRequest} message CloneDatabaseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CloneDatabaseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.tags = {}; + if (options.defaults) { + object.parent = ""; + object.databaseId = ""; + object.encryptionConfig = null; + object.pitrSnapshot = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + object.databaseId = message.databaseId; + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) + object.encryptionConfig = $root.google.firestore.admin.v1.Database.EncryptionConfig.toObject(message.encryptionConfig, options); + var keys2; + if (message.tags && (keys2 = Object.keys(message.tags)).length) { + object.tags = {}; + for (var j = 0; j < keys2.length; ++j) + object.tags[keys2[j]] = message.tags[keys2[j]]; + } + if (message.pitrSnapshot != null && message.hasOwnProperty("pitrSnapshot")) + object.pitrSnapshot = $root.google.firestore.admin.v1.PitrSnapshot.toObject(message.pitrSnapshot, options); + return object; + }; + + /** + * Converts this CloneDatabaseRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.CloneDatabaseRequest + * @instance + * @returns {Object.} JSON object + */ + CloneDatabaseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CloneDatabaseRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.CloneDatabaseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CloneDatabaseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.CloneDatabaseRequest"; + }; + + return CloneDatabaseRequest; + })(); + + v1.IndexOperationMetadata = (function() { + + /** + * Properties of an IndexOperationMetadata. + * @memberof google.firestore.admin.v1 + * @interface IIndexOperationMetadata + * @property {google.protobuf.ITimestamp|null} [startTime] IndexOperationMetadata startTime + * @property {google.protobuf.ITimestamp|null} [endTime] IndexOperationMetadata endTime + * @property {string|null} [index] IndexOperationMetadata index + * @property {google.firestore.admin.v1.OperationState|null} [state] IndexOperationMetadata state + * @property {google.firestore.admin.v1.IProgress|null} [progressDocuments] IndexOperationMetadata progressDocuments + * @property {google.firestore.admin.v1.IProgress|null} [progressBytes] IndexOperationMetadata progressBytes + */ + + /** + * Constructs a new IndexOperationMetadata. + * @memberof google.firestore.admin.v1 + * @classdesc Represents an IndexOperationMetadata. + * @implements IIndexOperationMetadata + * @constructor + * @param {google.firestore.admin.v1.IIndexOperationMetadata=} [properties] Properties to set + */ + function IndexOperationMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * IndexOperationMetadata startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.firestore.admin.v1.IndexOperationMetadata + * @instance + */ + IndexOperationMetadata.prototype.startTime = null; + + /** + * IndexOperationMetadata endTime. + * @member {google.protobuf.ITimestamp|null|undefined} endTime + * @memberof google.firestore.admin.v1.IndexOperationMetadata + * @instance + */ + IndexOperationMetadata.prototype.endTime = null; + + /** + * IndexOperationMetadata index. + * @member {string} index + * @memberof google.firestore.admin.v1.IndexOperationMetadata + * @instance + */ + IndexOperationMetadata.prototype.index = ""; + + /** + * IndexOperationMetadata state. + * @member {google.firestore.admin.v1.OperationState} state + * @memberof google.firestore.admin.v1.IndexOperationMetadata + * @instance + */ + IndexOperationMetadata.prototype.state = 0; + + /** + * IndexOperationMetadata progressDocuments. + * @member {google.firestore.admin.v1.IProgress|null|undefined} progressDocuments + * @memberof google.firestore.admin.v1.IndexOperationMetadata + * @instance + */ + IndexOperationMetadata.prototype.progressDocuments = null; + + /** + * IndexOperationMetadata progressBytes. + * @member {google.firestore.admin.v1.IProgress|null|undefined} progressBytes + * @memberof google.firestore.admin.v1.IndexOperationMetadata + * @instance + */ + IndexOperationMetadata.prototype.progressBytes = null; + + /** + * Creates an IndexOperationMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.IndexOperationMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.IndexOperationMetadata} IndexOperationMetadata + */ + IndexOperationMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.IndexOperationMetadata) + return object; + var message = new $root.google.firestore.admin.v1.IndexOperationMetadata(); + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.firestore.admin.v1.IndexOperationMetadata.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.endTime != null) { + if (typeof object.endTime !== "object") + throw TypeError(".google.firestore.admin.v1.IndexOperationMetadata.endTime: object expected"); + message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); + } + if (object.index != null) + message.index = String(object.index); + switch (object.state) { + default: + if (typeof object.state === "number") { + message.state = object.state; + break; + } + break; + case "OPERATION_STATE_UNSPECIFIED": + case 0: + message.state = 0; + break; + case "INITIALIZING": + case 1: + message.state = 1; + break; + case "PROCESSING": + case 2: + message.state = 2; + break; + case "CANCELLING": + case 3: + message.state = 3; + break; + case "FINALIZING": + case 4: + message.state = 4; + break; + case "SUCCESSFUL": + case 5: + message.state = 5; + break; + case "FAILED": + case 6: + message.state = 6; + break; + case "CANCELLED": + case 7: + message.state = 7; + break; + } + if (object.progressDocuments != null) { + if (typeof object.progressDocuments !== "object") + throw TypeError(".google.firestore.admin.v1.IndexOperationMetadata.progressDocuments: object expected"); + message.progressDocuments = $root.google.firestore.admin.v1.Progress.fromObject(object.progressDocuments); + } + if (object.progressBytes != null) { + if (typeof object.progressBytes !== "object") + throw TypeError(".google.firestore.admin.v1.IndexOperationMetadata.progressBytes: object expected"); + message.progressBytes = $root.google.firestore.admin.v1.Progress.fromObject(object.progressBytes); + } + return message; + }; + + /** + * Creates a plain object from an IndexOperationMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.IndexOperationMetadata + * @static + * @param {google.firestore.admin.v1.IndexOperationMetadata} message IndexOperationMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + IndexOperationMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.startTime = null; + object.endTime = null; + object.index = ""; + object.state = options.enums === String ? "OPERATION_STATE_UNSPECIFIED" : 0; + object.progressDocuments = null; + object.progressBytes = null; + } + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.endTime != null && message.hasOwnProperty("endTime")) + object.endTime = $root.google.protobuf.Timestamp.toObject(message.endTime, options); + if (message.index != null && message.hasOwnProperty("index")) + object.index = message.index; + if (message.state != null && message.hasOwnProperty("state")) + object.state = options.enums === String ? $root.google.firestore.admin.v1.OperationState[message.state] === undefined ? message.state : $root.google.firestore.admin.v1.OperationState[message.state] : message.state; + if (message.progressDocuments != null && message.hasOwnProperty("progressDocuments")) + object.progressDocuments = $root.google.firestore.admin.v1.Progress.toObject(message.progressDocuments, options); + if (message.progressBytes != null && message.hasOwnProperty("progressBytes")) + object.progressBytes = $root.google.firestore.admin.v1.Progress.toObject(message.progressBytes, options); + return object; + }; + + /** + * Converts this IndexOperationMetadata to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.IndexOperationMetadata + * @instance + * @returns {Object.} JSON object + */ + IndexOperationMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for IndexOperationMetadata + * @function getTypeUrl + * @memberof google.firestore.admin.v1.IndexOperationMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + IndexOperationMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.IndexOperationMetadata"; + }; + + return IndexOperationMetadata; + })(); + + v1.FieldOperationMetadata = (function() { + + /** + * Properties of a FieldOperationMetadata. + * @memberof google.firestore.admin.v1 + * @interface IFieldOperationMetadata + * @property {google.protobuf.ITimestamp|null} [startTime] FieldOperationMetadata startTime + * @property {google.protobuf.ITimestamp|null} [endTime] FieldOperationMetadata endTime + * @property {string|null} [field] FieldOperationMetadata field + * @property {Array.|null} [indexConfigDeltas] FieldOperationMetadata indexConfigDeltas + * @property {google.firestore.admin.v1.OperationState|null} [state] FieldOperationMetadata state + * @property {google.firestore.admin.v1.IProgress|null} [progressDocuments] FieldOperationMetadata progressDocuments + * @property {google.firestore.admin.v1.IProgress|null} [progressBytes] FieldOperationMetadata progressBytes + * @property {google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta|null} [ttlConfigDelta] FieldOperationMetadata ttlConfigDelta + */ + + /** + * Constructs a new FieldOperationMetadata. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a FieldOperationMetadata. + * @implements IFieldOperationMetadata + * @constructor + * @param {google.firestore.admin.v1.IFieldOperationMetadata=} [properties] Properties to set + */ + function FieldOperationMetadata(properties) { + this.indexConfigDeltas = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldOperationMetadata startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.firestore.admin.v1.FieldOperationMetadata + * @instance + */ + FieldOperationMetadata.prototype.startTime = null; + + /** + * FieldOperationMetadata endTime. + * @member {google.protobuf.ITimestamp|null|undefined} endTime + * @memberof google.firestore.admin.v1.FieldOperationMetadata + * @instance + */ + FieldOperationMetadata.prototype.endTime = null; + + /** + * FieldOperationMetadata field. + * @member {string} field + * @memberof google.firestore.admin.v1.FieldOperationMetadata + * @instance + */ + FieldOperationMetadata.prototype.field = ""; + + /** + * FieldOperationMetadata indexConfigDeltas. + * @member {Array.} indexConfigDeltas + * @memberof google.firestore.admin.v1.FieldOperationMetadata + * @instance + */ + FieldOperationMetadata.prototype.indexConfigDeltas = $util.emptyArray; + + /** + * FieldOperationMetadata state. + * @member {google.firestore.admin.v1.OperationState} state + * @memberof google.firestore.admin.v1.FieldOperationMetadata + * @instance + */ + FieldOperationMetadata.prototype.state = 0; + + /** + * FieldOperationMetadata progressDocuments. + * @member {google.firestore.admin.v1.IProgress|null|undefined} progressDocuments + * @memberof google.firestore.admin.v1.FieldOperationMetadata + * @instance + */ + FieldOperationMetadata.prototype.progressDocuments = null; + + /** + * FieldOperationMetadata progressBytes. + * @member {google.firestore.admin.v1.IProgress|null|undefined} progressBytes + * @memberof google.firestore.admin.v1.FieldOperationMetadata + * @instance + */ + FieldOperationMetadata.prototype.progressBytes = null; + + /** + * FieldOperationMetadata ttlConfigDelta. + * @member {google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta|null|undefined} ttlConfigDelta + * @memberof google.firestore.admin.v1.FieldOperationMetadata + * @instance + */ + FieldOperationMetadata.prototype.ttlConfigDelta = null; + + /** + * Creates a FieldOperationMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.FieldOperationMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.FieldOperationMetadata} FieldOperationMetadata + */ + FieldOperationMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.FieldOperationMetadata) + return object; + var message = new $root.google.firestore.admin.v1.FieldOperationMetadata(); + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.firestore.admin.v1.FieldOperationMetadata.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.endTime != null) { + if (typeof object.endTime !== "object") + throw TypeError(".google.firestore.admin.v1.FieldOperationMetadata.endTime: object expected"); + message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); + } + if (object.field != null) + message.field = String(object.field); + if (object.indexConfigDeltas) { + if (!Array.isArray(object.indexConfigDeltas)) + throw TypeError(".google.firestore.admin.v1.FieldOperationMetadata.indexConfigDeltas: array expected"); + message.indexConfigDeltas = []; + for (var i = 0; i < object.indexConfigDeltas.length; ++i) { + if (typeof object.indexConfigDeltas[i] !== "object") + throw TypeError(".google.firestore.admin.v1.FieldOperationMetadata.indexConfigDeltas: object expected"); + message.indexConfigDeltas[i] = $root.google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.fromObject(object.indexConfigDeltas[i]); + } + } + switch (object.state) { + default: + if (typeof object.state === "number") { + message.state = object.state; + break; + } + break; + case "OPERATION_STATE_UNSPECIFIED": + case 0: + message.state = 0; + break; + case "INITIALIZING": + case 1: + message.state = 1; + break; + case "PROCESSING": + case 2: + message.state = 2; + break; + case "CANCELLING": + case 3: + message.state = 3; + break; + case "FINALIZING": + case 4: + message.state = 4; + break; + case "SUCCESSFUL": + case 5: + message.state = 5; + break; + case "FAILED": + case 6: + message.state = 6; + break; + case "CANCELLED": + case 7: + message.state = 7; + break; + } + if (object.progressDocuments != null) { + if (typeof object.progressDocuments !== "object") + throw TypeError(".google.firestore.admin.v1.FieldOperationMetadata.progressDocuments: object expected"); + message.progressDocuments = $root.google.firestore.admin.v1.Progress.fromObject(object.progressDocuments); + } + if (object.progressBytes != null) { + if (typeof object.progressBytes !== "object") + throw TypeError(".google.firestore.admin.v1.FieldOperationMetadata.progressBytes: object expected"); + message.progressBytes = $root.google.firestore.admin.v1.Progress.fromObject(object.progressBytes); + } + if (object.ttlConfigDelta != null) { + if (typeof object.ttlConfigDelta !== "object") + throw TypeError(".google.firestore.admin.v1.FieldOperationMetadata.ttlConfigDelta: object expected"); + message.ttlConfigDelta = $root.google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.fromObject(object.ttlConfigDelta); + } + return message; + }; + + /** + * Creates a plain object from a FieldOperationMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.FieldOperationMetadata + * @static + * @param {google.firestore.admin.v1.FieldOperationMetadata} message FieldOperationMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldOperationMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.indexConfigDeltas = []; + if (options.defaults) { + object.startTime = null; + object.endTime = null; + object.field = ""; + object.state = options.enums === String ? "OPERATION_STATE_UNSPECIFIED" : 0; + object.progressDocuments = null; + object.progressBytes = null; + object.ttlConfigDelta = null; + } + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.endTime != null && message.hasOwnProperty("endTime")) + object.endTime = $root.google.protobuf.Timestamp.toObject(message.endTime, options); + if (message.field != null && message.hasOwnProperty("field")) + object.field = message.field; + if (message.indexConfigDeltas && message.indexConfigDeltas.length) { + object.indexConfigDeltas = []; + for (var j = 0; j < message.indexConfigDeltas.length; ++j) + object.indexConfigDeltas[j] = $root.google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.toObject(message.indexConfigDeltas[j], options); + } + if (message.state != null && message.hasOwnProperty("state")) + object.state = options.enums === String ? $root.google.firestore.admin.v1.OperationState[message.state] === undefined ? message.state : $root.google.firestore.admin.v1.OperationState[message.state] : message.state; + if (message.progressDocuments != null && message.hasOwnProperty("progressDocuments")) + object.progressDocuments = $root.google.firestore.admin.v1.Progress.toObject(message.progressDocuments, options); + if (message.progressBytes != null && message.hasOwnProperty("progressBytes")) + object.progressBytes = $root.google.firestore.admin.v1.Progress.toObject(message.progressBytes, options); + if (message.ttlConfigDelta != null && message.hasOwnProperty("ttlConfigDelta")) + object.ttlConfigDelta = $root.google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.toObject(message.ttlConfigDelta, options); + return object; + }; + + /** + * Converts this FieldOperationMetadata to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.FieldOperationMetadata + * @instance + * @returns {Object.} JSON object + */ + FieldOperationMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldOperationMetadata + * @function getTypeUrl + * @memberof google.firestore.admin.v1.FieldOperationMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldOperationMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.FieldOperationMetadata"; + }; + + FieldOperationMetadata.IndexConfigDelta = (function() { + + /** + * Properties of an IndexConfigDelta. + * @memberof google.firestore.admin.v1.FieldOperationMetadata + * @interface IIndexConfigDelta + * @property {google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType|null} [changeType] IndexConfigDelta changeType + * @property {google.firestore.admin.v1.IIndex|null} [index] IndexConfigDelta index + */ + + /** + * Constructs a new IndexConfigDelta. + * @memberof google.firestore.admin.v1.FieldOperationMetadata + * @classdesc Represents an IndexConfigDelta. + * @implements IIndexConfigDelta + * @constructor + * @param {google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta=} [properties] Properties to set + */ + function IndexConfigDelta(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * IndexConfigDelta changeType. + * @member {google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType} changeType + * @memberof google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta + * @instance + */ + IndexConfigDelta.prototype.changeType = 0; + + /** + * IndexConfigDelta index. + * @member {google.firestore.admin.v1.IIndex|null|undefined} index + * @memberof google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta + * @instance + */ + IndexConfigDelta.prototype.index = null; + + /** + * Creates an IndexConfigDelta message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta} IndexConfigDelta + */ + IndexConfigDelta.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta) + return object; + var message = new $root.google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta(); + switch (object.changeType) { + default: + if (typeof object.changeType === "number") { + message.changeType = object.changeType; + break; + } + break; + case "CHANGE_TYPE_UNSPECIFIED": + case 0: + message.changeType = 0; + break; + case "ADD": + case 1: + message.changeType = 1; + break; + case "REMOVE": + case 2: + message.changeType = 2; + break; + } + if (object.index != null) { + if (typeof object.index !== "object") + throw TypeError(".google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.index: object expected"); + message.index = $root.google.firestore.admin.v1.Index.fromObject(object.index); + } + return message; + }; + + /** + * Creates a plain object from an IndexConfigDelta message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta + * @static + * @param {google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta} message IndexConfigDelta + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + IndexConfigDelta.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.changeType = options.enums === String ? "CHANGE_TYPE_UNSPECIFIED" : 0; + object.index = null; + } + if (message.changeType != null && message.hasOwnProperty("changeType")) + object.changeType = options.enums === String ? $root.google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType[message.changeType] === undefined ? message.changeType : $root.google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType[message.changeType] : message.changeType; + if (message.index != null && message.hasOwnProperty("index")) + object.index = $root.google.firestore.admin.v1.Index.toObject(message.index, options); + return object; + }; + + /** + * Converts this IndexConfigDelta to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta + * @instance + * @returns {Object.} JSON object + */ + IndexConfigDelta.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for IndexConfigDelta + * @function getTypeUrl + * @memberof google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + IndexConfigDelta.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta"; + }; + + /** + * ChangeType enum. + * @name google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType + * @enum {string} + * @property {string} CHANGE_TYPE_UNSPECIFIED=CHANGE_TYPE_UNSPECIFIED CHANGE_TYPE_UNSPECIFIED value + * @property {string} ADD=ADD ADD value + * @property {string} REMOVE=REMOVE REMOVE value + */ + IndexConfigDelta.ChangeType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "CHANGE_TYPE_UNSPECIFIED"] = "CHANGE_TYPE_UNSPECIFIED"; + values[valuesById[1] = "ADD"] = "ADD"; + values[valuesById[2] = "REMOVE"] = "REMOVE"; + return values; + })(); + + return IndexConfigDelta; + })(); + + FieldOperationMetadata.TtlConfigDelta = (function() { + + /** + * Properties of a TtlConfigDelta. + * @memberof google.firestore.admin.v1.FieldOperationMetadata + * @interface ITtlConfigDelta + * @property {google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.ChangeType|null} [changeType] TtlConfigDelta changeType + */ + + /** + * Constructs a new TtlConfigDelta. + * @memberof google.firestore.admin.v1.FieldOperationMetadata + * @classdesc Represents a TtlConfigDelta. + * @implements ITtlConfigDelta + * @constructor + * @param {google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta=} [properties] Properties to set + */ + function TtlConfigDelta(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TtlConfigDelta changeType. + * @member {google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.ChangeType} changeType + * @memberof google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta + * @instance + */ + TtlConfigDelta.prototype.changeType = 0; + + /** + * Creates a TtlConfigDelta message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta} TtlConfigDelta + */ + TtlConfigDelta.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta) + return object; + var message = new $root.google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta(); + switch (object.changeType) { + default: + if (typeof object.changeType === "number") { + message.changeType = object.changeType; + break; + } + break; + case "CHANGE_TYPE_UNSPECIFIED": + case 0: + message.changeType = 0; + break; + case "ADD": + case 1: + message.changeType = 1; + break; + case "REMOVE": + case 2: + message.changeType = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from a TtlConfigDelta message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta + * @static + * @param {google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta} message TtlConfigDelta + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TtlConfigDelta.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.changeType = options.enums === String ? "CHANGE_TYPE_UNSPECIFIED" : 0; + if (message.changeType != null && message.hasOwnProperty("changeType")) + object.changeType = options.enums === String ? $root.google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.ChangeType[message.changeType] === undefined ? message.changeType : $root.google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.ChangeType[message.changeType] : message.changeType; + return object; + }; + + /** + * Converts this TtlConfigDelta to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta + * @instance + * @returns {Object.} JSON object + */ + TtlConfigDelta.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TtlConfigDelta + * @function getTypeUrl + * @memberof google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TtlConfigDelta.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta"; + }; + + /** + * ChangeType enum. + * @name google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.ChangeType + * @enum {string} + * @property {string} CHANGE_TYPE_UNSPECIFIED=CHANGE_TYPE_UNSPECIFIED CHANGE_TYPE_UNSPECIFIED value + * @property {string} ADD=ADD ADD value + * @property {string} REMOVE=REMOVE REMOVE value + */ + TtlConfigDelta.ChangeType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "CHANGE_TYPE_UNSPECIFIED"] = "CHANGE_TYPE_UNSPECIFIED"; + values[valuesById[1] = "ADD"] = "ADD"; + values[valuesById[2] = "REMOVE"] = "REMOVE"; + return values; + })(); + + return TtlConfigDelta; + })(); + + return FieldOperationMetadata; + })(); + + v1.ExportDocumentsMetadata = (function() { + + /** + * Properties of an ExportDocumentsMetadata. + * @memberof google.firestore.admin.v1 + * @interface IExportDocumentsMetadata + * @property {google.protobuf.ITimestamp|null} [startTime] ExportDocumentsMetadata startTime + * @property {google.protobuf.ITimestamp|null} [endTime] ExportDocumentsMetadata endTime + * @property {google.firestore.admin.v1.OperationState|null} [operationState] ExportDocumentsMetadata operationState + * @property {google.firestore.admin.v1.IProgress|null} [progressDocuments] ExportDocumentsMetadata progressDocuments + * @property {google.firestore.admin.v1.IProgress|null} [progressBytes] ExportDocumentsMetadata progressBytes + * @property {Array.|null} [collectionIds] ExportDocumentsMetadata collectionIds + * @property {string|null} [outputUriPrefix] ExportDocumentsMetadata outputUriPrefix + * @property {Array.|null} [namespaceIds] ExportDocumentsMetadata namespaceIds + * @property {google.protobuf.ITimestamp|null} [snapshotTime] ExportDocumentsMetadata snapshotTime + */ + + /** + * Constructs a new ExportDocumentsMetadata. + * @memberof google.firestore.admin.v1 + * @classdesc Represents an ExportDocumentsMetadata. + * @implements IExportDocumentsMetadata + * @constructor + * @param {google.firestore.admin.v1.IExportDocumentsMetadata=} [properties] Properties to set + */ + function ExportDocumentsMetadata(properties) { + this.collectionIds = []; + this.namespaceIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExportDocumentsMetadata startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.firestore.admin.v1.ExportDocumentsMetadata + * @instance + */ + ExportDocumentsMetadata.prototype.startTime = null; + + /** + * ExportDocumentsMetadata endTime. + * @member {google.protobuf.ITimestamp|null|undefined} endTime + * @memberof google.firestore.admin.v1.ExportDocumentsMetadata + * @instance + */ + ExportDocumentsMetadata.prototype.endTime = null; + + /** + * ExportDocumentsMetadata operationState. + * @member {google.firestore.admin.v1.OperationState} operationState + * @memberof google.firestore.admin.v1.ExportDocumentsMetadata + * @instance + */ + ExportDocumentsMetadata.prototype.operationState = 0; + + /** + * ExportDocumentsMetadata progressDocuments. + * @member {google.firestore.admin.v1.IProgress|null|undefined} progressDocuments + * @memberof google.firestore.admin.v1.ExportDocumentsMetadata + * @instance + */ + ExportDocumentsMetadata.prototype.progressDocuments = null; + + /** + * ExportDocumentsMetadata progressBytes. + * @member {google.firestore.admin.v1.IProgress|null|undefined} progressBytes + * @memberof google.firestore.admin.v1.ExportDocumentsMetadata + * @instance + */ + ExportDocumentsMetadata.prototype.progressBytes = null; + + /** + * ExportDocumentsMetadata collectionIds. + * @member {Array.} collectionIds + * @memberof google.firestore.admin.v1.ExportDocumentsMetadata + * @instance + */ + ExportDocumentsMetadata.prototype.collectionIds = $util.emptyArray; + + /** + * ExportDocumentsMetadata outputUriPrefix. + * @member {string} outputUriPrefix + * @memberof google.firestore.admin.v1.ExportDocumentsMetadata + * @instance + */ + ExportDocumentsMetadata.prototype.outputUriPrefix = ""; + + /** + * ExportDocumentsMetadata namespaceIds. + * @member {Array.} namespaceIds + * @memberof google.firestore.admin.v1.ExportDocumentsMetadata + * @instance + */ + ExportDocumentsMetadata.prototype.namespaceIds = $util.emptyArray; + + /** + * ExportDocumentsMetadata snapshotTime. + * @member {google.protobuf.ITimestamp|null|undefined} snapshotTime + * @memberof google.firestore.admin.v1.ExportDocumentsMetadata + * @instance + */ + ExportDocumentsMetadata.prototype.snapshotTime = null; + + /** + * Creates an ExportDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ExportDocumentsMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ExportDocumentsMetadata} ExportDocumentsMetadata + */ + ExportDocumentsMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ExportDocumentsMetadata) + return object; + var message = new $root.google.firestore.admin.v1.ExportDocumentsMetadata(); + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.firestore.admin.v1.ExportDocumentsMetadata.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.endTime != null) { + if (typeof object.endTime !== "object") + throw TypeError(".google.firestore.admin.v1.ExportDocumentsMetadata.endTime: object expected"); + message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); + } + switch (object.operationState) { + default: + if (typeof object.operationState === "number") { + message.operationState = object.operationState; + break; + } + break; + case "OPERATION_STATE_UNSPECIFIED": + case 0: + message.operationState = 0; + break; + case "INITIALIZING": + case 1: + message.operationState = 1; + break; + case "PROCESSING": + case 2: + message.operationState = 2; + break; + case "CANCELLING": + case 3: + message.operationState = 3; + break; + case "FINALIZING": + case 4: + message.operationState = 4; + break; + case "SUCCESSFUL": + case 5: + message.operationState = 5; + break; + case "FAILED": + case 6: + message.operationState = 6; + break; + case "CANCELLED": + case 7: + message.operationState = 7; + break; + } + if (object.progressDocuments != null) { + if (typeof object.progressDocuments !== "object") + throw TypeError(".google.firestore.admin.v1.ExportDocumentsMetadata.progressDocuments: object expected"); + message.progressDocuments = $root.google.firestore.admin.v1.Progress.fromObject(object.progressDocuments); + } + if (object.progressBytes != null) { + if (typeof object.progressBytes !== "object") + throw TypeError(".google.firestore.admin.v1.ExportDocumentsMetadata.progressBytes: object expected"); + message.progressBytes = $root.google.firestore.admin.v1.Progress.fromObject(object.progressBytes); + } + if (object.collectionIds) { + if (!Array.isArray(object.collectionIds)) + throw TypeError(".google.firestore.admin.v1.ExportDocumentsMetadata.collectionIds: array expected"); + message.collectionIds = []; + for (var i = 0; i < object.collectionIds.length; ++i) + message.collectionIds[i] = String(object.collectionIds[i]); + } + if (object.outputUriPrefix != null) + message.outputUriPrefix = String(object.outputUriPrefix); + if (object.namespaceIds) { + if (!Array.isArray(object.namespaceIds)) + throw TypeError(".google.firestore.admin.v1.ExportDocumentsMetadata.namespaceIds: array expected"); + message.namespaceIds = []; + for (var i = 0; i < object.namespaceIds.length; ++i) + message.namespaceIds[i] = String(object.namespaceIds[i]); + } + if (object.snapshotTime != null) { + if (typeof object.snapshotTime !== "object") + throw TypeError(".google.firestore.admin.v1.ExportDocumentsMetadata.snapshotTime: object expected"); + message.snapshotTime = $root.google.protobuf.Timestamp.fromObject(object.snapshotTime); + } + return message; + }; + + /** + * Creates a plain object from an ExportDocumentsMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ExportDocumentsMetadata + * @static + * @param {google.firestore.admin.v1.ExportDocumentsMetadata} message ExportDocumentsMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExportDocumentsMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.collectionIds = []; + object.namespaceIds = []; + } + if (options.defaults) { + object.startTime = null; + object.endTime = null; + object.operationState = options.enums === String ? "OPERATION_STATE_UNSPECIFIED" : 0; + object.progressDocuments = null; + object.progressBytes = null; + object.outputUriPrefix = ""; + object.snapshotTime = null; + } + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.endTime != null && message.hasOwnProperty("endTime")) + object.endTime = $root.google.protobuf.Timestamp.toObject(message.endTime, options); + if (message.operationState != null && message.hasOwnProperty("operationState")) + object.operationState = options.enums === String ? $root.google.firestore.admin.v1.OperationState[message.operationState] === undefined ? message.operationState : $root.google.firestore.admin.v1.OperationState[message.operationState] : message.operationState; + if (message.progressDocuments != null && message.hasOwnProperty("progressDocuments")) + object.progressDocuments = $root.google.firestore.admin.v1.Progress.toObject(message.progressDocuments, options); + if (message.progressBytes != null && message.hasOwnProperty("progressBytes")) + object.progressBytes = $root.google.firestore.admin.v1.Progress.toObject(message.progressBytes, options); + if (message.collectionIds && message.collectionIds.length) { + object.collectionIds = []; + for (var j = 0; j < message.collectionIds.length; ++j) + object.collectionIds[j] = message.collectionIds[j]; + } + if (message.outputUriPrefix != null && message.hasOwnProperty("outputUriPrefix")) + object.outputUriPrefix = message.outputUriPrefix; + if (message.namespaceIds && message.namespaceIds.length) { + object.namespaceIds = []; + for (var j = 0; j < message.namespaceIds.length; ++j) + object.namespaceIds[j] = message.namespaceIds[j]; + } + if (message.snapshotTime != null && message.hasOwnProperty("snapshotTime")) + object.snapshotTime = $root.google.protobuf.Timestamp.toObject(message.snapshotTime, options); + return object; + }; + + /** + * Converts this ExportDocumentsMetadata to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ExportDocumentsMetadata + * @instance + * @returns {Object.} JSON object + */ + ExportDocumentsMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExportDocumentsMetadata + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ExportDocumentsMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExportDocumentsMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ExportDocumentsMetadata"; + }; + + return ExportDocumentsMetadata; + })(); + + v1.ImportDocumentsMetadata = (function() { + + /** + * Properties of an ImportDocumentsMetadata. + * @memberof google.firestore.admin.v1 + * @interface IImportDocumentsMetadata + * @property {google.protobuf.ITimestamp|null} [startTime] ImportDocumentsMetadata startTime + * @property {google.protobuf.ITimestamp|null} [endTime] ImportDocumentsMetadata endTime + * @property {google.firestore.admin.v1.OperationState|null} [operationState] ImportDocumentsMetadata operationState + * @property {google.firestore.admin.v1.IProgress|null} [progressDocuments] ImportDocumentsMetadata progressDocuments + * @property {google.firestore.admin.v1.IProgress|null} [progressBytes] ImportDocumentsMetadata progressBytes + * @property {Array.|null} [collectionIds] ImportDocumentsMetadata collectionIds + * @property {string|null} [inputUriPrefix] ImportDocumentsMetadata inputUriPrefix + * @property {Array.|null} [namespaceIds] ImportDocumentsMetadata namespaceIds + */ + + /** + * Constructs a new ImportDocumentsMetadata. + * @memberof google.firestore.admin.v1 + * @classdesc Represents an ImportDocumentsMetadata. + * @implements IImportDocumentsMetadata + * @constructor + * @param {google.firestore.admin.v1.IImportDocumentsMetadata=} [properties] Properties to set + */ + function ImportDocumentsMetadata(properties) { + this.collectionIds = []; + this.namespaceIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ImportDocumentsMetadata startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @instance + */ + ImportDocumentsMetadata.prototype.startTime = null; + + /** + * ImportDocumentsMetadata endTime. + * @member {google.protobuf.ITimestamp|null|undefined} endTime + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @instance + */ + ImportDocumentsMetadata.prototype.endTime = null; + + /** + * ImportDocumentsMetadata operationState. + * @member {google.firestore.admin.v1.OperationState} operationState + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @instance + */ + ImportDocumentsMetadata.prototype.operationState = 0; + + /** + * ImportDocumentsMetadata progressDocuments. + * @member {google.firestore.admin.v1.IProgress|null|undefined} progressDocuments + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @instance + */ + ImportDocumentsMetadata.prototype.progressDocuments = null; + + /** + * ImportDocumentsMetadata progressBytes. + * @member {google.firestore.admin.v1.IProgress|null|undefined} progressBytes + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @instance + */ + ImportDocumentsMetadata.prototype.progressBytes = null; + + /** + * ImportDocumentsMetadata collectionIds. + * @member {Array.} collectionIds + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @instance + */ + ImportDocumentsMetadata.prototype.collectionIds = $util.emptyArray; + + /** + * ImportDocumentsMetadata inputUriPrefix. + * @member {string} inputUriPrefix + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @instance + */ + ImportDocumentsMetadata.prototype.inputUriPrefix = ""; + + /** + * ImportDocumentsMetadata namespaceIds. + * @member {Array.} namespaceIds + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @instance + */ + ImportDocumentsMetadata.prototype.namespaceIds = $util.emptyArray; + + /** + * Creates an ImportDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ImportDocumentsMetadata} ImportDocumentsMetadata + */ + ImportDocumentsMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ImportDocumentsMetadata) + return object; + var message = new $root.google.firestore.admin.v1.ImportDocumentsMetadata(); + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.endTime != null) { + if (typeof object.endTime !== "object") + throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.endTime: object expected"); + message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); + } + switch (object.operationState) { + default: + if (typeof object.operationState === "number") { + message.operationState = object.operationState; + break; + } + break; + case "OPERATION_STATE_UNSPECIFIED": + case 0: + message.operationState = 0; + break; + case "INITIALIZING": + case 1: + message.operationState = 1; + break; + case "PROCESSING": + case 2: + message.operationState = 2; + break; + case "CANCELLING": + case 3: + message.operationState = 3; + break; + case "FINALIZING": + case 4: + message.operationState = 4; + break; + case "SUCCESSFUL": + case 5: + message.operationState = 5; + break; + case "FAILED": + case 6: + message.operationState = 6; + break; + case "CANCELLED": + case 7: + message.operationState = 7; + break; + } + if (object.progressDocuments != null) { + if (typeof object.progressDocuments !== "object") + throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.progressDocuments: object expected"); + message.progressDocuments = $root.google.firestore.admin.v1.Progress.fromObject(object.progressDocuments); + } + if (object.progressBytes != null) { + if (typeof object.progressBytes !== "object") + throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.progressBytes: object expected"); + message.progressBytes = $root.google.firestore.admin.v1.Progress.fromObject(object.progressBytes); + } + if (object.collectionIds) { + if (!Array.isArray(object.collectionIds)) + throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.collectionIds: array expected"); + message.collectionIds = []; + for (var i = 0; i < object.collectionIds.length; ++i) + message.collectionIds[i] = String(object.collectionIds[i]); + } + if (object.inputUriPrefix != null) + message.inputUriPrefix = String(object.inputUriPrefix); + if (object.namespaceIds) { + if (!Array.isArray(object.namespaceIds)) + throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.namespaceIds: array expected"); + message.namespaceIds = []; + for (var i = 0; i < object.namespaceIds.length; ++i) + message.namespaceIds[i] = String(object.namespaceIds[i]); + } + return message; + }; + + /** + * Creates a plain object from an ImportDocumentsMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @static + * @param {google.firestore.admin.v1.ImportDocumentsMetadata} message ImportDocumentsMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ImportDocumentsMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.collectionIds = []; + object.namespaceIds = []; + } + if (options.defaults) { + object.startTime = null; + object.endTime = null; + object.operationState = options.enums === String ? "OPERATION_STATE_UNSPECIFIED" : 0; + object.progressDocuments = null; + object.progressBytes = null; + object.inputUriPrefix = ""; + } + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.endTime != null && message.hasOwnProperty("endTime")) + object.endTime = $root.google.protobuf.Timestamp.toObject(message.endTime, options); + if (message.operationState != null && message.hasOwnProperty("operationState")) + object.operationState = options.enums === String ? $root.google.firestore.admin.v1.OperationState[message.operationState] === undefined ? message.operationState : $root.google.firestore.admin.v1.OperationState[message.operationState] : message.operationState; + if (message.progressDocuments != null && message.hasOwnProperty("progressDocuments")) + object.progressDocuments = $root.google.firestore.admin.v1.Progress.toObject(message.progressDocuments, options); + if (message.progressBytes != null && message.hasOwnProperty("progressBytes")) + object.progressBytes = $root.google.firestore.admin.v1.Progress.toObject(message.progressBytes, options); + if (message.collectionIds && message.collectionIds.length) { + object.collectionIds = []; + for (var j = 0; j < message.collectionIds.length; ++j) + object.collectionIds[j] = message.collectionIds[j]; + } + if (message.inputUriPrefix != null && message.hasOwnProperty("inputUriPrefix")) + object.inputUriPrefix = message.inputUriPrefix; + if (message.namespaceIds && message.namespaceIds.length) { + object.namespaceIds = []; + for (var j = 0; j < message.namespaceIds.length; ++j) + object.namespaceIds[j] = message.namespaceIds[j]; + } + return object; + }; + + /** + * Converts this ImportDocumentsMetadata to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @instance + * @returns {Object.} JSON object + */ + ImportDocumentsMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ImportDocumentsMetadata + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ImportDocumentsMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ImportDocumentsMetadata"; + }; + + return ImportDocumentsMetadata; + })(); + + v1.BulkDeleteDocumentsMetadata = (function() { + + /** + * Properties of a BulkDeleteDocumentsMetadata. + * @memberof google.firestore.admin.v1 + * @interface IBulkDeleteDocumentsMetadata + * @property {google.protobuf.ITimestamp|null} [startTime] BulkDeleteDocumentsMetadata startTime + * @property {google.protobuf.ITimestamp|null} [endTime] BulkDeleteDocumentsMetadata endTime + * @property {google.firestore.admin.v1.OperationState|null} [operationState] BulkDeleteDocumentsMetadata operationState + * @property {google.firestore.admin.v1.IProgress|null} [progressDocuments] BulkDeleteDocumentsMetadata progressDocuments + * @property {google.firestore.admin.v1.IProgress|null} [progressBytes] BulkDeleteDocumentsMetadata progressBytes + * @property {Array.|null} [collectionIds] BulkDeleteDocumentsMetadata collectionIds + * @property {Array.|null} [namespaceIds] BulkDeleteDocumentsMetadata namespaceIds + * @property {google.protobuf.ITimestamp|null} [snapshotTime] BulkDeleteDocumentsMetadata snapshotTime + */ + + /** + * Constructs a new BulkDeleteDocumentsMetadata. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a BulkDeleteDocumentsMetadata. + * @implements IBulkDeleteDocumentsMetadata + * @constructor + * @param {google.firestore.admin.v1.IBulkDeleteDocumentsMetadata=} [properties] Properties to set + */ + function BulkDeleteDocumentsMetadata(properties) { + this.collectionIds = []; + this.namespaceIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BulkDeleteDocumentsMetadata startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @instance + */ + BulkDeleteDocumentsMetadata.prototype.startTime = null; + + /** + * BulkDeleteDocumentsMetadata endTime. + * @member {google.protobuf.ITimestamp|null|undefined} endTime + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @instance + */ + BulkDeleteDocumentsMetadata.prototype.endTime = null; + + /** + * BulkDeleteDocumentsMetadata operationState. + * @member {google.firestore.admin.v1.OperationState} operationState + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @instance + */ + BulkDeleteDocumentsMetadata.prototype.operationState = 0; + + /** + * BulkDeleteDocumentsMetadata progressDocuments. + * @member {google.firestore.admin.v1.IProgress|null|undefined} progressDocuments + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @instance + */ + BulkDeleteDocumentsMetadata.prototype.progressDocuments = null; + + /** + * BulkDeleteDocumentsMetadata progressBytes. + * @member {google.firestore.admin.v1.IProgress|null|undefined} progressBytes + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @instance + */ + BulkDeleteDocumentsMetadata.prototype.progressBytes = null; + + /** + * BulkDeleteDocumentsMetadata collectionIds. + * @member {Array.} collectionIds + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @instance + */ + BulkDeleteDocumentsMetadata.prototype.collectionIds = $util.emptyArray; + + /** + * BulkDeleteDocumentsMetadata namespaceIds. + * @member {Array.} namespaceIds + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @instance + */ + BulkDeleteDocumentsMetadata.prototype.namespaceIds = $util.emptyArray; + + /** + * BulkDeleteDocumentsMetadata snapshotTime. + * @member {google.protobuf.ITimestamp|null|undefined} snapshotTime + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @instance + */ + BulkDeleteDocumentsMetadata.prototype.snapshotTime = null; + + /** + * Creates a BulkDeleteDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.BulkDeleteDocumentsMetadata} BulkDeleteDocumentsMetadata + */ + BulkDeleteDocumentsMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.BulkDeleteDocumentsMetadata) + return object; + var message = new $root.google.firestore.admin.v1.BulkDeleteDocumentsMetadata(); + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsMetadata.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.endTime != null) { + if (typeof object.endTime !== "object") + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsMetadata.endTime: object expected"); + message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); + } + switch (object.operationState) { + default: + if (typeof object.operationState === "number") { + message.operationState = object.operationState; + break; + } + break; + case "OPERATION_STATE_UNSPECIFIED": + case 0: + message.operationState = 0; + break; + case "INITIALIZING": + case 1: + message.operationState = 1; + break; + case "PROCESSING": + case 2: + message.operationState = 2; + break; + case "CANCELLING": + case 3: + message.operationState = 3; + break; + case "FINALIZING": + case 4: + message.operationState = 4; + break; + case "SUCCESSFUL": + case 5: + message.operationState = 5; + break; + case "FAILED": + case 6: + message.operationState = 6; + break; + case "CANCELLED": + case 7: + message.operationState = 7; + break; + } + if (object.progressDocuments != null) { + if (typeof object.progressDocuments !== "object") + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsMetadata.progressDocuments: object expected"); + message.progressDocuments = $root.google.firestore.admin.v1.Progress.fromObject(object.progressDocuments); + } + if (object.progressBytes != null) { + if (typeof object.progressBytes !== "object") + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsMetadata.progressBytes: object expected"); + message.progressBytes = $root.google.firestore.admin.v1.Progress.fromObject(object.progressBytes); + } + if (object.collectionIds) { + if (!Array.isArray(object.collectionIds)) + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsMetadata.collectionIds: array expected"); + message.collectionIds = []; + for (var i = 0; i < object.collectionIds.length; ++i) + message.collectionIds[i] = String(object.collectionIds[i]); + } + if (object.namespaceIds) { + if (!Array.isArray(object.namespaceIds)) + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsMetadata.namespaceIds: array expected"); + message.namespaceIds = []; + for (var i = 0; i < object.namespaceIds.length; ++i) + message.namespaceIds[i] = String(object.namespaceIds[i]); + } + if (object.snapshotTime != null) { + if (typeof object.snapshotTime !== "object") + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsMetadata.snapshotTime: object expected"); + message.snapshotTime = $root.google.protobuf.Timestamp.fromObject(object.snapshotTime); + } + return message; + }; + + /** + * Creates a plain object from a BulkDeleteDocumentsMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @static + * @param {google.firestore.admin.v1.BulkDeleteDocumentsMetadata} message BulkDeleteDocumentsMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BulkDeleteDocumentsMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.collectionIds = []; + object.namespaceIds = []; + } + if (options.defaults) { + object.startTime = null; + object.endTime = null; + object.operationState = options.enums === String ? "OPERATION_STATE_UNSPECIFIED" : 0; + object.progressDocuments = null; + object.progressBytes = null; + object.snapshotTime = null; + } + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.endTime != null && message.hasOwnProperty("endTime")) + object.endTime = $root.google.protobuf.Timestamp.toObject(message.endTime, options); + if (message.operationState != null && message.hasOwnProperty("operationState")) + object.operationState = options.enums === String ? $root.google.firestore.admin.v1.OperationState[message.operationState] === undefined ? message.operationState : $root.google.firestore.admin.v1.OperationState[message.operationState] : message.operationState; + if (message.progressDocuments != null && message.hasOwnProperty("progressDocuments")) + object.progressDocuments = $root.google.firestore.admin.v1.Progress.toObject(message.progressDocuments, options); + if (message.progressBytes != null && message.hasOwnProperty("progressBytes")) + object.progressBytes = $root.google.firestore.admin.v1.Progress.toObject(message.progressBytes, options); + if (message.collectionIds && message.collectionIds.length) { + object.collectionIds = []; + for (var j = 0; j < message.collectionIds.length; ++j) + object.collectionIds[j] = message.collectionIds[j]; + } + if (message.namespaceIds && message.namespaceIds.length) { + object.namespaceIds = []; + for (var j = 0; j < message.namespaceIds.length; ++j) + object.namespaceIds[j] = message.namespaceIds[j]; + } + if (message.snapshotTime != null && message.hasOwnProperty("snapshotTime")) + object.snapshotTime = $root.google.protobuf.Timestamp.toObject(message.snapshotTime, options); + return object; + }; + + /** + * Converts this BulkDeleteDocumentsMetadata to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @instance + * @returns {Object.} JSON object + */ + BulkDeleteDocumentsMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BulkDeleteDocumentsMetadata + * @function getTypeUrl + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BulkDeleteDocumentsMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.BulkDeleteDocumentsMetadata"; + }; + + return BulkDeleteDocumentsMetadata; + })(); + + v1.ExportDocumentsResponse = (function() { + + /** + * Properties of an ExportDocumentsResponse. + * @memberof google.firestore.admin.v1 + * @interface IExportDocumentsResponse + * @property {string|null} [outputUriPrefix] ExportDocumentsResponse outputUriPrefix + */ + + /** + * Constructs a new ExportDocumentsResponse. + * @memberof google.firestore.admin.v1 + * @classdesc Represents an ExportDocumentsResponse. + * @implements IExportDocumentsResponse + * @constructor + * @param {google.firestore.admin.v1.IExportDocumentsResponse=} [properties] Properties to set + */ + function ExportDocumentsResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExportDocumentsResponse outputUriPrefix. + * @member {string} outputUriPrefix + * @memberof google.firestore.admin.v1.ExportDocumentsResponse + * @instance + */ + ExportDocumentsResponse.prototype.outputUriPrefix = ""; + + /** + * Creates an ExportDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ExportDocumentsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ExportDocumentsResponse} ExportDocumentsResponse + */ + ExportDocumentsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ExportDocumentsResponse) + return object; + var message = new $root.google.firestore.admin.v1.ExportDocumentsResponse(); + if (object.outputUriPrefix != null) + message.outputUriPrefix = String(object.outputUriPrefix); + return message; + }; + + /** + * Creates a plain object from an ExportDocumentsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ExportDocumentsResponse + * @static + * @param {google.firestore.admin.v1.ExportDocumentsResponse} message ExportDocumentsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExportDocumentsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.outputUriPrefix = ""; + if (message.outputUriPrefix != null && message.hasOwnProperty("outputUriPrefix")) + object.outputUriPrefix = message.outputUriPrefix; + return object; + }; + + /** + * Converts this ExportDocumentsResponse to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ExportDocumentsResponse + * @instance + * @returns {Object.} JSON object + */ + ExportDocumentsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExportDocumentsResponse + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ExportDocumentsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExportDocumentsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ExportDocumentsResponse"; + }; + + return ExportDocumentsResponse; + })(); + + v1.RestoreDatabaseMetadata = (function() { + + /** + * Properties of a RestoreDatabaseMetadata. + * @memberof google.firestore.admin.v1 + * @interface IRestoreDatabaseMetadata + * @property {google.protobuf.ITimestamp|null} [startTime] RestoreDatabaseMetadata startTime + * @property {google.protobuf.ITimestamp|null} [endTime] RestoreDatabaseMetadata endTime + * @property {google.firestore.admin.v1.OperationState|null} [operationState] RestoreDatabaseMetadata operationState + * @property {string|null} [database] RestoreDatabaseMetadata database + * @property {string|null} [backup] RestoreDatabaseMetadata backup + * @property {google.firestore.admin.v1.IProgress|null} [progressPercentage] RestoreDatabaseMetadata progressPercentage + */ + + /** + * Constructs a new RestoreDatabaseMetadata. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a RestoreDatabaseMetadata. + * @implements IRestoreDatabaseMetadata + * @constructor + * @param {google.firestore.admin.v1.IRestoreDatabaseMetadata=} [properties] Properties to set + */ + function RestoreDatabaseMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RestoreDatabaseMetadata startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.firestore.admin.v1.RestoreDatabaseMetadata + * @instance + */ + RestoreDatabaseMetadata.prototype.startTime = null; + + /** + * RestoreDatabaseMetadata endTime. + * @member {google.protobuf.ITimestamp|null|undefined} endTime + * @memberof google.firestore.admin.v1.RestoreDatabaseMetadata + * @instance + */ + RestoreDatabaseMetadata.prototype.endTime = null; + + /** + * RestoreDatabaseMetadata operationState. + * @member {google.firestore.admin.v1.OperationState} operationState + * @memberof google.firestore.admin.v1.RestoreDatabaseMetadata + * @instance + */ + RestoreDatabaseMetadata.prototype.operationState = 0; + + /** + * RestoreDatabaseMetadata database. + * @member {string} database + * @memberof google.firestore.admin.v1.RestoreDatabaseMetadata + * @instance + */ + RestoreDatabaseMetadata.prototype.database = ""; + + /** + * RestoreDatabaseMetadata backup. + * @member {string} backup + * @memberof google.firestore.admin.v1.RestoreDatabaseMetadata + * @instance + */ + RestoreDatabaseMetadata.prototype.backup = ""; + + /** + * RestoreDatabaseMetadata progressPercentage. + * @member {google.firestore.admin.v1.IProgress|null|undefined} progressPercentage + * @memberof google.firestore.admin.v1.RestoreDatabaseMetadata + * @instance + */ + RestoreDatabaseMetadata.prototype.progressPercentage = null; + + /** + * Creates a RestoreDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.RestoreDatabaseMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.RestoreDatabaseMetadata} RestoreDatabaseMetadata + */ + RestoreDatabaseMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.RestoreDatabaseMetadata) + return object; + var message = new $root.google.firestore.admin.v1.RestoreDatabaseMetadata(); + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.firestore.admin.v1.RestoreDatabaseMetadata.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.endTime != null) { + if (typeof object.endTime !== "object") + throw TypeError(".google.firestore.admin.v1.RestoreDatabaseMetadata.endTime: object expected"); + message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); + } + switch (object.operationState) { + default: + if (typeof object.operationState === "number") { + message.operationState = object.operationState; + break; + } + break; + case "OPERATION_STATE_UNSPECIFIED": + case 0: + message.operationState = 0; + break; + case "INITIALIZING": + case 1: + message.operationState = 1; + break; + case "PROCESSING": + case 2: + message.operationState = 2; + break; + case "CANCELLING": + case 3: + message.operationState = 3; + break; + case "FINALIZING": + case 4: + message.operationState = 4; + break; + case "SUCCESSFUL": + case 5: + message.operationState = 5; + break; + case "FAILED": + case 6: + message.operationState = 6; + break; + case "CANCELLED": + case 7: + message.operationState = 7; + break; + } + if (object.database != null) + message.database = String(object.database); + if (object.backup != null) + message.backup = String(object.backup); + if (object.progressPercentage != null) { + if (typeof object.progressPercentage !== "object") + throw TypeError(".google.firestore.admin.v1.RestoreDatabaseMetadata.progressPercentage: object expected"); + message.progressPercentage = $root.google.firestore.admin.v1.Progress.fromObject(object.progressPercentage); + } + return message; + }; + + /** + * Creates a plain object from a RestoreDatabaseMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.RestoreDatabaseMetadata + * @static + * @param {google.firestore.admin.v1.RestoreDatabaseMetadata} message RestoreDatabaseMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RestoreDatabaseMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.startTime = null; + object.endTime = null; + object.operationState = options.enums === String ? "OPERATION_STATE_UNSPECIFIED" : 0; + object.database = ""; + object.backup = ""; + object.progressPercentage = null; + } + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.endTime != null && message.hasOwnProperty("endTime")) + object.endTime = $root.google.protobuf.Timestamp.toObject(message.endTime, options); + if (message.operationState != null && message.hasOwnProperty("operationState")) + object.operationState = options.enums === String ? $root.google.firestore.admin.v1.OperationState[message.operationState] === undefined ? message.operationState : $root.google.firestore.admin.v1.OperationState[message.operationState] : message.operationState; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.backup != null && message.hasOwnProperty("backup")) + object.backup = message.backup; + if (message.progressPercentage != null && message.hasOwnProperty("progressPercentage")) + object.progressPercentage = $root.google.firestore.admin.v1.Progress.toObject(message.progressPercentage, options); + return object; + }; + + /** + * Converts this RestoreDatabaseMetadata to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.RestoreDatabaseMetadata + * @instance + * @returns {Object.} JSON object + */ + RestoreDatabaseMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RestoreDatabaseMetadata + * @function getTypeUrl + * @memberof google.firestore.admin.v1.RestoreDatabaseMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RestoreDatabaseMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.RestoreDatabaseMetadata"; + }; + + return RestoreDatabaseMetadata; + })(); + + v1.CloneDatabaseMetadata = (function() { + + /** + * Properties of a CloneDatabaseMetadata. + * @memberof google.firestore.admin.v1 + * @interface ICloneDatabaseMetadata + * @property {google.protobuf.ITimestamp|null} [startTime] CloneDatabaseMetadata startTime + * @property {google.protobuf.ITimestamp|null} [endTime] CloneDatabaseMetadata endTime + * @property {google.firestore.admin.v1.OperationState|null} [operationState] CloneDatabaseMetadata operationState + * @property {string|null} [database] CloneDatabaseMetadata database + * @property {google.firestore.admin.v1.IPitrSnapshot|null} [pitrSnapshot] CloneDatabaseMetadata pitrSnapshot + * @property {google.firestore.admin.v1.IProgress|null} [progressPercentage] CloneDatabaseMetadata progressPercentage + */ + + /** + * Constructs a new CloneDatabaseMetadata. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a CloneDatabaseMetadata. + * @implements ICloneDatabaseMetadata + * @constructor + * @param {google.firestore.admin.v1.ICloneDatabaseMetadata=} [properties] Properties to set + */ + function CloneDatabaseMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CloneDatabaseMetadata startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.firestore.admin.v1.CloneDatabaseMetadata + * @instance + */ + CloneDatabaseMetadata.prototype.startTime = null; + + /** + * CloneDatabaseMetadata endTime. + * @member {google.protobuf.ITimestamp|null|undefined} endTime + * @memberof google.firestore.admin.v1.CloneDatabaseMetadata + * @instance + */ + CloneDatabaseMetadata.prototype.endTime = null; + + /** + * CloneDatabaseMetadata operationState. + * @member {google.firestore.admin.v1.OperationState} operationState + * @memberof google.firestore.admin.v1.CloneDatabaseMetadata + * @instance + */ + CloneDatabaseMetadata.prototype.operationState = 0; + + /** + * CloneDatabaseMetadata database. + * @member {string} database + * @memberof google.firestore.admin.v1.CloneDatabaseMetadata + * @instance + */ + CloneDatabaseMetadata.prototype.database = ""; + + /** + * CloneDatabaseMetadata pitrSnapshot. + * @member {google.firestore.admin.v1.IPitrSnapshot|null|undefined} pitrSnapshot + * @memberof google.firestore.admin.v1.CloneDatabaseMetadata + * @instance + */ + CloneDatabaseMetadata.prototype.pitrSnapshot = null; + + /** + * CloneDatabaseMetadata progressPercentage. + * @member {google.firestore.admin.v1.IProgress|null|undefined} progressPercentage + * @memberof google.firestore.admin.v1.CloneDatabaseMetadata + * @instance + */ + CloneDatabaseMetadata.prototype.progressPercentage = null; + + /** + * Creates a CloneDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.CloneDatabaseMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.CloneDatabaseMetadata} CloneDatabaseMetadata + */ + CloneDatabaseMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.CloneDatabaseMetadata) + return object; + var message = new $root.google.firestore.admin.v1.CloneDatabaseMetadata(); + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.firestore.admin.v1.CloneDatabaseMetadata.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.endTime != null) { + if (typeof object.endTime !== "object") + throw TypeError(".google.firestore.admin.v1.CloneDatabaseMetadata.endTime: object expected"); + message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); + } + switch (object.operationState) { + default: + if (typeof object.operationState === "number") { + message.operationState = object.operationState; + break; + } + break; + case "OPERATION_STATE_UNSPECIFIED": + case 0: + message.operationState = 0; + break; + case "INITIALIZING": + case 1: + message.operationState = 1; + break; + case "PROCESSING": + case 2: + message.operationState = 2; + break; + case "CANCELLING": + case 3: + message.operationState = 3; + break; + case "FINALIZING": + case 4: + message.operationState = 4; + break; + case "SUCCESSFUL": + case 5: + message.operationState = 5; + break; + case "FAILED": + case 6: + message.operationState = 6; + break; + case "CANCELLED": + case 7: + message.operationState = 7; + break; + } + if (object.database != null) + message.database = String(object.database); + if (object.pitrSnapshot != null) { + if (typeof object.pitrSnapshot !== "object") + throw TypeError(".google.firestore.admin.v1.CloneDatabaseMetadata.pitrSnapshot: object expected"); + message.pitrSnapshot = $root.google.firestore.admin.v1.PitrSnapshot.fromObject(object.pitrSnapshot); + } + if (object.progressPercentage != null) { + if (typeof object.progressPercentage !== "object") + throw TypeError(".google.firestore.admin.v1.CloneDatabaseMetadata.progressPercentage: object expected"); + message.progressPercentage = $root.google.firestore.admin.v1.Progress.fromObject(object.progressPercentage); + } + return message; + }; + + /** + * Creates a plain object from a CloneDatabaseMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.CloneDatabaseMetadata + * @static + * @param {google.firestore.admin.v1.CloneDatabaseMetadata} message CloneDatabaseMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CloneDatabaseMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.startTime = null; + object.endTime = null; + object.operationState = options.enums === String ? "OPERATION_STATE_UNSPECIFIED" : 0; + object.database = ""; + object.progressPercentage = null; + object.pitrSnapshot = null; + } + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.endTime != null && message.hasOwnProperty("endTime")) + object.endTime = $root.google.protobuf.Timestamp.toObject(message.endTime, options); + if (message.operationState != null && message.hasOwnProperty("operationState")) + object.operationState = options.enums === String ? $root.google.firestore.admin.v1.OperationState[message.operationState] === undefined ? message.operationState : $root.google.firestore.admin.v1.OperationState[message.operationState] : message.operationState; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.progressPercentage != null && message.hasOwnProperty("progressPercentage")) + object.progressPercentage = $root.google.firestore.admin.v1.Progress.toObject(message.progressPercentage, options); + if (message.pitrSnapshot != null && message.hasOwnProperty("pitrSnapshot")) + object.pitrSnapshot = $root.google.firestore.admin.v1.PitrSnapshot.toObject(message.pitrSnapshot, options); + return object; + }; + + /** + * Converts this CloneDatabaseMetadata to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.CloneDatabaseMetadata + * @instance + * @returns {Object.} JSON object + */ + CloneDatabaseMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CloneDatabaseMetadata + * @function getTypeUrl + * @memberof google.firestore.admin.v1.CloneDatabaseMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CloneDatabaseMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.CloneDatabaseMetadata"; + }; + + return CloneDatabaseMetadata; + })(); + + v1.Progress = (function() { + + /** + * Properties of a Progress. + * @memberof google.firestore.admin.v1 + * @interface IProgress + * @property {number|string|null} [estimatedWork] Progress estimatedWork + * @property {number|string|null} [completedWork] Progress completedWork + */ + + /** + * Constructs a new Progress. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a Progress. + * @implements IProgress + * @constructor + * @param {google.firestore.admin.v1.IProgress=} [properties] Properties to set + */ + function Progress(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Progress estimatedWork. + * @member {number|string} estimatedWork + * @memberof google.firestore.admin.v1.Progress + * @instance + */ + Progress.prototype.estimatedWork = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Progress completedWork. + * @member {number|string} completedWork + * @memberof google.firestore.admin.v1.Progress + * @instance + */ + Progress.prototype.completedWork = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates a Progress message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.Progress + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.Progress} Progress + */ + Progress.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.Progress) + return object; + var message = new $root.google.firestore.admin.v1.Progress(); + if (object.estimatedWork != null) + if ($util.Long) + (message.estimatedWork = $util.Long.fromValue(object.estimatedWork)).unsigned = false; + else if (typeof object.estimatedWork === "string") + message.estimatedWork = parseInt(object.estimatedWork, 10); + else if (typeof object.estimatedWork === "number") + message.estimatedWork = object.estimatedWork; + else if (typeof object.estimatedWork === "object") + message.estimatedWork = new $util.LongBits(object.estimatedWork.low >>> 0, object.estimatedWork.high >>> 0).toNumber(); + if (object.completedWork != null) + if ($util.Long) + (message.completedWork = $util.Long.fromValue(object.completedWork)).unsigned = false; + else if (typeof object.completedWork === "string") + message.completedWork = parseInt(object.completedWork, 10); + else if (typeof object.completedWork === "number") + message.completedWork = object.completedWork; + else if (typeof object.completedWork === "object") + message.completedWork = new $util.LongBits(object.completedWork.low >>> 0, object.completedWork.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a Progress message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.Progress + * @static + * @param {google.firestore.admin.v1.Progress} message Progress + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Progress.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.estimatedWork = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.estimatedWork = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.completedWork = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.completedWork = options.longs === String ? "0" : 0; + } + if (message.estimatedWork != null && message.hasOwnProperty("estimatedWork")) + if (typeof message.estimatedWork === "number") + object.estimatedWork = options.longs === String ? String(message.estimatedWork) : message.estimatedWork; + else + object.estimatedWork = options.longs === String ? $util.Long.prototype.toString.call(message.estimatedWork) : options.longs === Number ? new $util.LongBits(message.estimatedWork.low >>> 0, message.estimatedWork.high >>> 0).toNumber() : message.estimatedWork; + if (message.completedWork != null && message.hasOwnProperty("completedWork")) + if (typeof message.completedWork === "number") + object.completedWork = options.longs === String ? String(message.completedWork) : message.completedWork; + else + object.completedWork = options.longs === String ? $util.Long.prototype.toString.call(message.completedWork) : options.longs === Number ? new $util.LongBits(message.completedWork.low >>> 0, message.completedWork.high >>> 0).toNumber() : message.completedWork; + return object; + }; + + /** + * Converts this Progress to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.Progress + * @instance + * @returns {Object.} JSON object + */ + Progress.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Progress + * @function getTypeUrl + * @memberof google.firestore.admin.v1.Progress + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Progress.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.Progress"; + }; + + return Progress; + })(); + + /** + * OperationState enum. + * @name google.firestore.admin.v1.OperationState + * @enum {string} + * @property {string} OPERATION_STATE_UNSPECIFIED=OPERATION_STATE_UNSPECIFIED OPERATION_STATE_UNSPECIFIED value + * @property {string} INITIALIZING=INITIALIZING INITIALIZING value + * @property {string} PROCESSING=PROCESSING PROCESSING value + * @property {string} CANCELLING=CANCELLING CANCELLING value + * @property {string} FINALIZING=FINALIZING FINALIZING value + * @property {string} SUCCESSFUL=SUCCESSFUL SUCCESSFUL value + * @property {string} FAILED=FAILED FAILED value + * @property {string} CANCELLED=CANCELLED CANCELLED value + */ + v1.OperationState = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "OPERATION_STATE_UNSPECIFIED"] = "OPERATION_STATE_UNSPECIFIED"; + values[valuesById[1] = "INITIALIZING"] = "INITIALIZING"; + values[valuesById[2] = "PROCESSING"] = "PROCESSING"; + values[valuesById[3] = "CANCELLING"] = "CANCELLING"; + values[valuesById[4] = "FINALIZING"] = "FINALIZING"; + values[valuesById[5] = "SUCCESSFUL"] = "SUCCESSFUL"; + values[valuesById[6] = "FAILED"] = "FAILED"; + values[valuesById[7] = "CANCELLED"] = "CANCELLED"; + return values; + })(); + + v1.PitrSnapshot = (function() { + + /** + * Properties of a PitrSnapshot. + * @memberof google.firestore.admin.v1 + * @interface IPitrSnapshot + * @property {string|null} [database] PitrSnapshot database + * @property {Uint8Array|null} [databaseUid] PitrSnapshot databaseUid + * @property {google.protobuf.ITimestamp|null} [snapshotTime] PitrSnapshot snapshotTime + */ + + /** + * Constructs a new PitrSnapshot. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a PitrSnapshot. + * @implements IPitrSnapshot + * @constructor + * @param {google.firestore.admin.v1.IPitrSnapshot=} [properties] Properties to set + */ + function PitrSnapshot(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PitrSnapshot database. + * @member {string} database + * @memberof google.firestore.admin.v1.PitrSnapshot + * @instance + */ + PitrSnapshot.prototype.database = ""; + + /** + * PitrSnapshot databaseUid. + * @member {Uint8Array} databaseUid + * @memberof google.firestore.admin.v1.PitrSnapshot + * @instance + */ + PitrSnapshot.prototype.databaseUid = $util.newBuffer([]); + + /** + * PitrSnapshot snapshotTime. + * @member {google.protobuf.ITimestamp|null|undefined} snapshotTime + * @memberof google.firestore.admin.v1.PitrSnapshot + * @instance + */ + PitrSnapshot.prototype.snapshotTime = null; + + /** + * Creates a PitrSnapshot message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.PitrSnapshot + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.PitrSnapshot} PitrSnapshot + */ + PitrSnapshot.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.PitrSnapshot) + return object; + var message = new $root.google.firestore.admin.v1.PitrSnapshot(); + if (object.database != null) + message.database = String(object.database); + if (object.databaseUid != null) + if (typeof object.databaseUid === "string") + $util.base64.decode(object.databaseUid, message.databaseUid = $util.newBuffer($util.base64.length(object.databaseUid)), 0); + else if (object.databaseUid.length >= 0) + message.databaseUid = object.databaseUid; + if (object.snapshotTime != null) { + if (typeof object.snapshotTime !== "object") + throw TypeError(".google.firestore.admin.v1.PitrSnapshot.snapshotTime: object expected"); + message.snapshotTime = $root.google.protobuf.Timestamp.fromObject(object.snapshotTime); + } + return message; + }; + + /** + * Creates a plain object from a PitrSnapshot message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.PitrSnapshot + * @static + * @param {google.firestore.admin.v1.PitrSnapshot} message PitrSnapshot + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PitrSnapshot.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.database = ""; + if (options.bytes === String) + object.databaseUid = ""; + else { + object.databaseUid = []; + if (options.bytes !== Array) + object.databaseUid = $util.newBuffer(object.databaseUid); + } + object.snapshotTime = null; + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.databaseUid != null && message.hasOwnProperty("databaseUid")) + object.databaseUid = options.bytes === String ? $util.base64.encode(message.databaseUid, 0, message.databaseUid.length) : options.bytes === Array ? Array.prototype.slice.call(message.databaseUid) : message.databaseUid; + if (message.snapshotTime != null && message.hasOwnProperty("snapshotTime")) + object.snapshotTime = $root.google.protobuf.Timestamp.toObject(message.snapshotTime, options); + return object; + }; + + /** + * Converts this PitrSnapshot to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.PitrSnapshot + * @instance + * @returns {Object.} JSON object + */ + PitrSnapshot.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PitrSnapshot + * @function getTypeUrl + * @memberof google.firestore.admin.v1.PitrSnapshot + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PitrSnapshot.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.PitrSnapshot"; + }; + + return PitrSnapshot; + })(); + + v1.BackupSchedule = (function() { + + /** + * Properties of a BackupSchedule. + * @memberof google.firestore.admin.v1 + * @interface IBackupSchedule + * @property {string|null} [name] BackupSchedule name + * @property {google.protobuf.ITimestamp|null} [createTime] BackupSchedule createTime + * @property {google.protobuf.ITimestamp|null} [updateTime] BackupSchedule updateTime + * @property {google.protobuf.IDuration|null} [retention] BackupSchedule retention + * @property {google.firestore.admin.v1.IDailyRecurrence|null} [dailyRecurrence] BackupSchedule dailyRecurrence + * @property {google.firestore.admin.v1.IWeeklyRecurrence|null} [weeklyRecurrence] BackupSchedule weeklyRecurrence + */ + + /** + * Constructs a new BackupSchedule. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a BackupSchedule. + * @implements IBackupSchedule + * @constructor + * @param {google.firestore.admin.v1.IBackupSchedule=} [properties] Properties to set + */ + function BackupSchedule(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BackupSchedule name. + * @member {string} name + * @memberof google.firestore.admin.v1.BackupSchedule + * @instance + */ + BackupSchedule.prototype.name = ""; + + /** + * BackupSchedule createTime. + * @member {google.protobuf.ITimestamp|null|undefined} createTime + * @memberof google.firestore.admin.v1.BackupSchedule + * @instance + */ + BackupSchedule.prototype.createTime = null; + + /** + * BackupSchedule updateTime. + * @member {google.protobuf.ITimestamp|null|undefined} updateTime + * @memberof google.firestore.admin.v1.BackupSchedule + * @instance + */ + BackupSchedule.prototype.updateTime = null; + + /** + * BackupSchedule retention. + * @member {google.protobuf.IDuration|null|undefined} retention + * @memberof google.firestore.admin.v1.BackupSchedule + * @instance + */ + BackupSchedule.prototype.retention = null; + + /** + * BackupSchedule dailyRecurrence. + * @member {google.firestore.admin.v1.IDailyRecurrence|null|undefined} dailyRecurrence + * @memberof google.firestore.admin.v1.BackupSchedule + * @instance + */ + BackupSchedule.prototype.dailyRecurrence = null; + + /** + * BackupSchedule weeklyRecurrence. + * @member {google.firestore.admin.v1.IWeeklyRecurrence|null|undefined} weeklyRecurrence + * @memberof google.firestore.admin.v1.BackupSchedule + * @instance + */ + BackupSchedule.prototype.weeklyRecurrence = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * BackupSchedule recurrence. + * @member {"dailyRecurrence"|"weeklyRecurrence"|undefined} recurrence + * @memberof google.firestore.admin.v1.BackupSchedule + * @instance + */ + Object.defineProperty(BackupSchedule.prototype, "recurrence", { + get: $util.oneOfGetter($oneOfFields = ["dailyRecurrence", "weeklyRecurrence"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a BackupSchedule message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.BackupSchedule + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.BackupSchedule} BackupSchedule + */ + BackupSchedule.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.BackupSchedule) + return object; + var message = new $root.google.firestore.admin.v1.BackupSchedule(); + if (object.name != null) + message.name = String(object.name); + if (object.createTime != null) { + if (typeof object.createTime !== "object") + throw TypeError(".google.firestore.admin.v1.BackupSchedule.createTime: object expected"); + message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime); + } + if (object.updateTime != null) { + if (typeof object.updateTime !== "object") + throw TypeError(".google.firestore.admin.v1.BackupSchedule.updateTime: object expected"); + message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + } + if (object.retention != null) { + if (typeof object.retention !== "object") + throw TypeError(".google.firestore.admin.v1.BackupSchedule.retention: object expected"); + message.retention = $root.google.protobuf.Duration.fromObject(object.retention); + } + if (object.dailyRecurrence != null) { + if (typeof object.dailyRecurrence !== "object") + throw TypeError(".google.firestore.admin.v1.BackupSchedule.dailyRecurrence: object expected"); + message.dailyRecurrence = $root.google.firestore.admin.v1.DailyRecurrence.fromObject(object.dailyRecurrence); + } + if (object.weeklyRecurrence != null) { + if (typeof object.weeklyRecurrence !== "object") + throw TypeError(".google.firestore.admin.v1.BackupSchedule.weeklyRecurrence: object expected"); + message.weeklyRecurrence = $root.google.firestore.admin.v1.WeeklyRecurrence.fromObject(object.weeklyRecurrence); + } + return message; + }; + + /** + * Creates a plain object from a BackupSchedule message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.BackupSchedule + * @static + * @param {google.firestore.admin.v1.BackupSchedule} message BackupSchedule + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BackupSchedule.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.createTime = null; + object.retention = null; + object.updateTime = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.createTime != null && message.hasOwnProperty("createTime")) + object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); + if (message.retention != null && message.hasOwnProperty("retention")) + object.retention = $root.google.protobuf.Duration.toObject(message.retention, options); + if (message.dailyRecurrence != null && message.hasOwnProperty("dailyRecurrence")) { + object.dailyRecurrence = $root.google.firestore.admin.v1.DailyRecurrence.toObject(message.dailyRecurrence, options); + if (options.oneofs) + object.recurrence = "dailyRecurrence"; + } + if (message.weeklyRecurrence != null && message.hasOwnProperty("weeklyRecurrence")) { + object.weeklyRecurrence = $root.google.firestore.admin.v1.WeeklyRecurrence.toObject(message.weeklyRecurrence, options); + if (options.oneofs) + object.recurrence = "weeklyRecurrence"; + } + if (message.updateTime != null && message.hasOwnProperty("updateTime")) + object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + return object; + }; + + /** + * Converts this BackupSchedule to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.BackupSchedule + * @instance + * @returns {Object.} JSON object + */ + BackupSchedule.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BackupSchedule + * @function getTypeUrl + * @memberof google.firestore.admin.v1.BackupSchedule + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BackupSchedule.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.BackupSchedule"; + }; + + return BackupSchedule; + })(); + + v1.DailyRecurrence = (function() { + + /** + * Properties of a DailyRecurrence. + * @memberof google.firestore.admin.v1 + * @interface IDailyRecurrence + */ + + /** + * Constructs a new DailyRecurrence. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a DailyRecurrence. + * @implements IDailyRecurrence + * @constructor + * @param {google.firestore.admin.v1.IDailyRecurrence=} [properties] Properties to set + */ + function DailyRecurrence(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a DailyRecurrence message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.DailyRecurrence + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.DailyRecurrence} DailyRecurrence + */ + DailyRecurrence.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.DailyRecurrence) + return object; + return new $root.google.firestore.admin.v1.DailyRecurrence(); + }; + + /** + * Creates a plain object from a DailyRecurrence message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.DailyRecurrence + * @static + * @param {google.firestore.admin.v1.DailyRecurrence} message DailyRecurrence + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DailyRecurrence.toObject = function toObject() { + return {}; + }; + + /** + * Converts this DailyRecurrence to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.DailyRecurrence + * @instance + * @returns {Object.} JSON object + */ + DailyRecurrence.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DailyRecurrence + * @function getTypeUrl + * @memberof google.firestore.admin.v1.DailyRecurrence + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DailyRecurrence.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.DailyRecurrence"; + }; + + return DailyRecurrence; + })(); + + v1.WeeklyRecurrence = (function() { + + /** + * Properties of a WeeklyRecurrence. + * @memberof google.firestore.admin.v1 + * @interface IWeeklyRecurrence + * @property {google.type.DayOfWeek|null} [day] WeeklyRecurrence day + */ + + /** + * Constructs a new WeeklyRecurrence. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a WeeklyRecurrence. + * @implements IWeeklyRecurrence + * @constructor + * @param {google.firestore.admin.v1.IWeeklyRecurrence=} [properties] Properties to set + */ + function WeeklyRecurrence(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * WeeklyRecurrence day. + * @member {google.type.DayOfWeek} day + * @memberof google.firestore.admin.v1.WeeklyRecurrence + * @instance + */ + WeeklyRecurrence.prototype.day = 0; + + /** + * Creates a WeeklyRecurrence message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.WeeklyRecurrence + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.WeeklyRecurrence} WeeklyRecurrence + */ + WeeklyRecurrence.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.WeeklyRecurrence) + return object; + var message = new $root.google.firestore.admin.v1.WeeklyRecurrence(); + switch (object.day) { + default: + if (typeof object.day === "number") { + message.day = object.day; + break; + } + break; + case "DAY_OF_WEEK_UNSPECIFIED": + case 0: + message.day = 0; + break; + case "MONDAY": + case 1: + message.day = 1; + break; + case "TUESDAY": + case 2: + message.day = 2; + break; + case "WEDNESDAY": + case 3: + message.day = 3; + break; + case "THURSDAY": + case 4: + message.day = 4; + break; + case "FRIDAY": + case 5: + message.day = 5; + break; + case "SATURDAY": + case 6: + message.day = 6; + break; + case "SUNDAY": + case 7: + message.day = 7; + break; + } + return message; + }; + + /** + * Creates a plain object from a WeeklyRecurrence message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.WeeklyRecurrence + * @static + * @param {google.firestore.admin.v1.WeeklyRecurrence} message WeeklyRecurrence + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WeeklyRecurrence.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.day = options.enums === String ? "DAY_OF_WEEK_UNSPECIFIED" : 0; + if (message.day != null && message.hasOwnProperty("day")) + object.day = options.enums === String ? $root.google.type.DayOfWeek[message.day] === undefined ? message.day : $root.google.type.DayOfWeek[message.day] : message.day; + return object; + }; + + /** + * Converts this WeeklyRecurrence to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.WeeklyRecurrence + * @instance + * @returns {Object.} JSON object + */ + WeeklyRecurrence.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for WeeklyRecurrence + * @function getTypeUrl + * @memberof google.firestore.admin.v1.WeeklyRecurrence + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WeeklyRecurrence.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.WeeklyRecurrence"; + }; + + return WeeklyRecurrence; + })(); + + v1.UserCreds = (function() { + + /** + * Properties of a UserCreds. + * @memberof google.firestore.admin.v1 + * @interface IUserCreds + * @property {string|null} [name] UserCreds name + * @property {google.protobuf.ITimestamp|null} [createTime] UserCreds createTime + * @property {google.protobuf.ITimestamp|null} [updateTime] UserCreds updateTime + * @property {google.firestore.admin.v1.UserCreds.State|null} [state] UserCreds state + * @property {string|null} [securePassword] UserCreds securePassword + * @property {google.firestore.admin.v1.UserCreds.IResourceIdentity|null} [resourceIdentity] UserCreds resourceIdentity + */ + + /** + * Constructs a new UserCreds. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a UserCreds. + * @implements IUserCreds + * @constructor + * @param {google.firestore.admin.v1.IUserCreds=} [properties] Properties to set + */ + function UserCreds(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UserCreds name. + * @member {string} name + * @memberof google.firestore.admin.v1.UserCreds + * @instance + */ + UserCreds.prototype.name = ""; + + /** + * UserCreds createTime. + * @member {google.protobuf.ITimestamp|null|undefined} createTime + * @memberof google.firestore.admin.v1.UserCreds + * @instance + */ + UserCreds.prototype.createTime = null; + + /** + * UserCreds updateTime. + * @member {google.protobuf.ITimestamp|null|undefined} updateTime + * @memberof google.firestore.admin.v1.UserCreds + * @instance + */ + UserCreds.prototype.updateTime = null; + + /** + * UserCreds state. + * @member {google.firestore.admin.v1.UserCreds.State} state + * @memberof google.firestore.admin.v1.UserCreds + * @instance + */ + UserCreds.prototype.state = 0; + + /** + * UserCreds securePassword. + * @member {string} securePassword + * @memberof google.firestore.admin.v1.UserCreds + * @instance + */ + UserCreds.prototype.securePassword = ""; + + /** + * UserCreds resourceIdentity. + * @member {google.firestore.admin.v1.UserCreds.IResourceIdentity|null|undefined} resourceIdentity + * @memberof google.firestore.admin.v1.UserCreds + * @instance + */ + UserCreds.prototype.resourceIdentity = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * UserCreds UserCredsIdentity. + * @member {"resourceIdentity"|undefined} UserCredsIdentity + * @memberof google.firestore.admin.v1.UserCreds + * @instance + */ + Object.defineProperty(UserCreds.prototype, "UserCredsIdentity", { + get: $util.oneOfGetter($oneOfFields = ["resourceIdentity"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a UserCreds message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.UserCreds + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.UserCreds} UserCreds + */ + UserCreds.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.UserCreds) + return object; + var message = new $root.google.firestore.admin.v1.UserCreds(); + if (object.name != null) + message.name = String(object.name); + if (object.createTime != null) { + if (typeof object.createTime !== "object") + throw TypeError(".google.firestore.admin.v1.UserCreds.createTime: object expected"); + message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime); + } + if (object.updateTime != null) { + if (typeof object.updateTime !== "object") + throw TypeError(".google.firestore.admin.v1.UserCreds.updateTime: object expected"); + message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + } + switch (object.state) { + default: + if (typeof object.state === "number") { + message.state = object.state; + break; + } + break; + case "STATE_UNSPECIFIED": + case 0: + message.state = 0; + break; + case "ENABLED": + case 1: + message.state = 1; + break; + case "DISABLED": + case 2: + message.state = 2; + break; + } + if (object.securePassword != null) + message.securePassword = String(object.securePassword); + if (object.resourceIdentity != null) { + if (typeof object.resourceIdentity !== "object") + throw TypeError(".google.firestore.admin.v1.UserCreds.resourceIdentity: object expected"); + message.resourceIdentity = $root.google.firestore.admin.v1.UserCreds.ResourceIdentity.fromObject(object.resourceIdentity); + } + return message; + }; + + /** + * Creates a plain object from a UserCreds message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.UserCreds + * @static + * @param {google.firestore.admin.v1.UserCreds} message UserCreds + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UserCreds.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.createTime = null; + object.updateTime = null; + object.state = options.enums === String ? "STATE_UNSPECIFIED" : 0; + object.securePassword = ""; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.createTime != null && message.hasOwnProperty("createTime")) + object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); + if (message.updateTime != null && message.hasOwnProperty("updateTime")) + object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + if (message.state != null && message.hasOwnProperty("state")) + object.state = options.enums === String ? $root.google.firestore.admin.v1.UserCreds.State[message.state] === undefined ? message.state : $root.google.firestore.admin.v1.UserCreds.State[message.state] : message.state; + if (message.securePassword != null && message.hasOwnProperty("securePassword")) + object.securePassword = message.securePassword; + if (message.resourceIdentity != null && message.hasOwnProperty("resourceIdentity")) { + object.resourceIdentity = $root.google.firestore.admin.v1.UserCreds.ResourceIdentity.toObject(message.resourceIdentity, options); + if (options.oneofs) + object.UserCredsIdentity = "resourceIdentity"; + } + return object; + }; + + /** + * Converts this UserCreds to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.UserCreds + * @instance + * @returns {Object.} JSON object + */ + UserCreds.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UserCreds + * @function getTypeUrl + * @memberof google.firestore.admin.v1.UserCreds + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UserCreds.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.UserCreds"; + }; + + /** + * State enum. + * @name google.firestore.admin.v1.UserCreds.State + * @enum {string} + * @property {string} STATE_UNSPECIFIED=STATE_UNSPECIFIED STATE_UNSPECIFIED value + * @property {string} ENABLED=ENABLED ENABLED value + * @property {string} DISABLED=DISABLED DISABLED value + */ + UserCreds.State = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + values[valuesById[1] = "ENABLED"] = "ENABLED"; + values[valuesById[2] = "DISABLED"] = "DISABLED"; + return values; + })(); + + UserCreds.ResourceIdentity = (function() { + + /** + * Properties of a ResourceIdentity. + * @memberof google.firestore.admin.v1.UserCreds + * @interface IResourceIdentity + * @property {string|null} [principal] ResourceIdentity principal + */ + + /** + * Constructs a new ResourceIdentity. + * @memberof google.firestore.admin.v1.UserCreds + * @classdesc Represents a ResourceIdentity. + * @implements IResourceIdentity + * @constructor + * @param {google.firestore.admin.v1.UserCreds.IResourceIdentity=} [properties] Properties to set + */ + function ResourceIdentity(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResourceIdentity principal. + * @member {string} principal + * @memberof google.firestore.admin.v1.UserCreds.ResourceIdentity + * @instance + */ + ResourceIdentity.prototype.principal = ""; + + /** + * Creates a ResourceIdentity message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.UserCreds.ResourceIdentity + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.UserCreds.ResourceIdentity} ResourceIdentity + */ + ResourceIdentity.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.UserCreds.ResourceIdentity) + return object; + var message = new $root.google.firestore.admin.v1.UserCreds.ResourceIdentity(); + if (object.principal != null) + message.principal = String(object.principal); + return message; + }; + + /** + * Creates a plain object from a ResourceIdentity message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.UserCreds.ResourceIdentity + * @static + * @param {google.firestore.admin.v1.UserCreds.ResourceIdentity} message ResourceIdentity + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceIdentity.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.principal = ""; + if (message.principal != null && message.hasOwnProperty("principal")) + object.principal = message.principal; + return object; + }; + + /** + * Converts this ResourceIdentity to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.UserCreds.ResourceIdentity + * @instance + * @returns {Object.} JSON object + */ + ResourceIdentity.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResourceIdentity + * @function getTypeUrl + * @memberof google.firestore.admin.v1.UserCreds.ResourceIdentity + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceIdentity.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.UserCreds.ResourceIdentity"; + }; + + return ResourceIdentity; + })(); + + return UserCreds; + })(); + + v1.LocationMetadata = (function() { + + /** + * Properties of a LocationMetadata. + * @memberof google.firestore.admin.v1 + * @interface ILocationMetadata + */ + + /** + * Constructs a new LocationMetadata. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a LocationMetadata. + * @implements ILocationMetadata + * @constructor + * @param {google.firestore.admin.v1.ILocationMetadata=} [properties] Properties to set + */ + function LocationMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a LocationMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.LocationMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.LocationMetadata} LocationMetadata + */ + LocationMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.LocationMetadata) + return object; + return new $root.google.firestore.admin.v1.LocationMetadata(); + }; + + /** + * Creates a plain object from a LocationMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.LocationMetadata + * @static + * @param {google.firestore.admin.v1.LocationMetadata} message LocationMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + LocationMetadata.toObject = function toObject() { + return {}; + }; + + /** + * Converts this LocationMetadata to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.LocationMetadata + * @instance + * @returns {Object.} JSON object + */ + LocationMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for LocationMetadata + * @function getTypeUrl + * @memberof google.firestore.admin.v1.LocationMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + LocationMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.LocationMetadata"; + }; + + return LocationMetadata; + })(); + + return v1; + })(); + + return admin; + })(); + + return firestore; + })(); + + google.api = (function() { + + /** + * Namespace api. + * @memberof google + * @namespace + */ + var api = {}; + + /** + * FieldBehavior enum. + * @name google.api.FieldBehavior + * @enum {string} + * @property {string} FIELD_BEHAVIOR_UNSPECIFIED=FIELD_BEHAVIOR_UNSPECIFIED FIELD_BEHAVIOR_UNSPECIFIED value + * @property {string} OPTIONAL=OPTIONAL OPTIONAL value + * @property {string} REQUIRED=REQUIRED REQUIRED value + * @property {string} OUTPUT_ONLY=OUTPUT_ONLY OUTPUT_ONLY value + * @property {string} INPUT_ONLY=INPUT_ONLY INPUT_ONLY value + * @property {string} IMMUTABLE=IMMUTABLE IMMUTABLE value + * @property {string} UNORDERED_LIST=UNORDERED_LIST UNORDERED_LIST value + * @property {string} NON_EMPTY_DEFAULT=NON_EMPTY_DEFAULT NON_EMPTY_DEFAULT value + * @property {string} IDENTIFIER=IDENTIFIER IDENTIFIER value + */ + api.FieldBehavior = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "FIELD_BEHAVIOR_UNSPECIFIED"] = "FIELD_BEHAVIOR_UNSPECIFIED"; + values[valuesById[1] = "OPTIONAL"] = "OPTIONAL"; + values[valuesById[2] = "REQUIRED"] = "REQUIRED"; + values[valuesById[3] = "OUTPUT_ONLY"] = "OUTPUT_ONLY"; + values[valuesById[4] = "INPUT_ONLY"] = "INPUT_ONLY"; + values[valuesById[5] = "IMMUTABLE"] = "IMMUTABLE"; + values[valuesById[6] = "UNORDERED_LIST"] = "UNORDERED_LIST"; + values[valuesById[7] = "NON_EMPTY_DEFAULT"] = "NON_EMPTY_DEFAULT"; + values[valuesById[8] = "IDENTIFIER"] = "IDENTIFIER"; + return values; + })(); + + api.ResourceDescriptor = (function() { + + /** + * Properties of a ResourceDescriptor. + * @memberof google.api + * @interface IResourceDescriptor + * @property {string|null} [type] ResourceDescriptor type + * @property {Array.|null} [pattern] ResourceDescriptor pattern + * @property {string|null} [nameField] ResourceDescriptor nameField + * @property {google.api.ResourceDescriptor.History|null} [history] ResourceDescriptor history + * @property {string|null} [plural] ResourceDescriptor plural + * @property {string|null} [singular] ResourceDescriptor singular + * @property {Array.|null} [style] ResourceDescriptor style + */ + + /** + * Constructs a new ResourceDescriptor. + * @memberof google.api + * @classdesc Represents a ResourceDescriptor. + * @implements IResourceDescriptor + * @constructor + * @param {google.api.IResourceDescriptor=} [properties] Properties to set + */ + function ResourceDescriptor(properties) { + this.pattern = []; + this.style = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResourceDescriptor type. + * @member {string} type + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.type = ""; + + /** + * ResourceDescriptor pattern. + * @member {Array.} pattern + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.pattern = $util.emptyArray; + + /** + * ResourceDescriptor nameField. + * @member {string} nameField + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.nameField = ""; + + /** + * ResourceDescriptor history. + * @member {google.api.ResourceDescriptor.History} history + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.history = 0; + + /** + * ResourceDescriptor plural. + * @member {string} plural + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.plural = ""; + + /** + * ResourceDescriptor singular. + * @member {string} singular + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.singular = ""; + + /** + * ResourceDescriptor style. + * @member {Array.} style + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.style = $util.emptyArray; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ResourceDescriptor + * @static + * @param {Object.} object Plain object + * @returns {google.api.ResourceDescriptor} ResourceDescriptor + */ + ResourceDescriptor.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ResourceDescriptor) + return object; + var message = new $root.google.api.ResourceDescriptor(); + if (object.type != null) + message.type = String(object.type); + if (object.pattern) { + if (!Array.isArray(object.pattern)) + throw TypeError(".google.api.ResourceDescriptor.pattern: array expected"); + message.pattern = []; + for (var i = 0; i < object.pattern.length; ++i) + message.pattern[i] = String(object.pattern[i]); + } + if (object.nameField != null) + message.nameField = String(object.nameField); + switch (object.history) { + default: + if (typeof object.history === "number") { + message.history = object.history; + break; + } + break; + case "HISTORY_UNSPECIFIED": + case 0: + message.history = 0; + break; + case "ORIGINALLY_SINGLE_PATTERN": + case 1: + message.history = 1; + break; + case "FUTURE_MULTI_PATTERN": + case 2: + message.history = 2; + break; + } + if (object.plural != null) + message.plural = String(object.plural); + if (object.singular != null) + message.singular = String(object.singular); + if (object.style) { + if (!Array.isArray(object.style)) + throw TypeError(".google.api.ResourceDescriptor.style: array expected"); + message.style = []; + for (var i = 0; i < object.style.length; ++i) + switch (object.style[i]) { + default: + if (typeof object.style[i] === "number") { + message.style[i] = object.style[i]; + break; + } + case "STYLE_UNSPECIFIED": + case 0: + message.style[i] = 0; + break; + case "DECLARATIVE_FRIENDLY": + case 1: + message.style[i] = 1; + break; + } + } + return message; + }; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ResourceDescriptor + * @static + * @param {google.api.ResourceDescriptor} message ResourceDescriptor + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceDescriptor.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.pattern = []; + object.style = []; + } + if (options.defaults) { + object.type = ""; + object.nameField = ""; + object.history = options.enums === String ? "HISTORY_UNSPECIFIED" : 0; + object.plural = ""; + object.singular = ""; + } + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.pattern && message.pattern.length) { + object.pattern = []; + for (var j = 0; j < message.pattern.length; ++j) + object.pattern[j] = message.pattern[j]; + } + if (message.nameField != null && message.hasOwnProperty("nameField")) + object.nameField = message.nameField; + if (message.history != null && message.hasOwnProperty("history")) + object.history = options.enums === String ? $root.google.api.ResourceDescriptor.History[message.history] === undefined ? message.history : $root.google.api.ResourceDescriptor.History[message.history] : message.history; + if (message.plural != null && message.hasOwnProperty("plural")) + object.plural = message.plural; + if (message.singular != null && message.hasOwnProperty("singular")) + object.singular = message.singular; + if (message.style && message.style.length) { + object.style = []; + for (var j = 0; j < message.style.length; ++j) + object.style[j] = options.enums === String ? $root.google.api.ResourceDescriptor.Style[message.style[j]] === undefined ? message.style[j] : $root.google.api.ResourceDescriptor.Style[message.style[j]] : message.style[j]; + } + return object; + }; + + /** + * Converts this ResourceDescriptor to JSON. + * @function toJSON + * @memberof google.api.ResourceDescriptor + * @instance + * @returns {Object.} JSON object + */ + ResourceDescriptor.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResourceDescriptor + * @function getTypeUrl + * @memberof google.api.ResourceDescriptor + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceDescriptor.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ResourceDescriptor"; + }; + + /** + * History enum. + * @name google.api.ResourceDescriptor.History + * @enum {string} + * @property {string} HISTORY_UNSPECIFIED=HISTORY_UNSPECIFIED HISTORY_UNSPECIFIED value + * @property {string} ORIGINALLY_SINGLE_PATTERN=ORIGINALLY_SINGLE_PATTERN ORIGINALLY_SINGLE_PATTERN value + * @property {string} FUTURE_MULTI_PATTERN=FUTURE_MULTI_PATTERN FUTURE_MULTI_PATTERN value + */ + ResourceDescriptor.History = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "HISTORY_UNSPECIFIED"] = "HISTORY_UNSPECIFIED"; + values[valuesById[1] = "ORIGINALLY_SINGLE_PATTERN"] = "ORIGINALLY_SINGLE_PATTERN"; + values[valuesById[2] = "FUTURE_MULTI_PATTERN"] = "FUTURE_MULTI_PATTERN"; + return values; + })(); + + /** + * Style enum. + * @name google.api.ResourceDescriptor.Style + * @enum {string} + * @property {string} STYLE_UNSPECIFIED=STYLE_UNSPECIFIED STYLE_UNSPECIFIED value + * @property {string} DECLARATIVE_FRIENDLY=DECLARATIVE_FRIENDLY DECLARATIVE_FRIENDLY value + */ + ResourceDescriptor.Style = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STYLE_UNSPECIFIED"] = "STYLE_UNSPECIFIED"; + values[valuesById[1] = "DECLARATIVE_FRIENDLY"] = "DECLARATIVE_FRIENDLY"; + return values; + })(); + + return ResourceDescriptor; + })(); + + api.ResourceReference = (function() { + + /** + * Properties of a ResourceReference. + * @memberof google.api + * @interface IResourceReference + * @property {string|null} [type] ResourceReference type + * @property {string|null} [childType] ResourceReference childType + */ + + /** + * Constructs a new ResourceReference. + * @memberof google.api + * @classdesc Represents a ResourceReference. + * @implements IResourceReference + * @constructor + * @param {google.api.IResourceReference=} [properties] Properties to set + */ + function ResourceReference(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResourceReference type. + * @member {string} type + * @memberof google.api.ResourceReference + * @instance + */ + ResourceReference.prototype.type = ""; + + /** + * ResourceReference childType. + * @member {string} childType + * @memberof google.api.ResourceReference + * @instance + */ + ResourceReference.prototype.childType = ""; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ResourceReference + * @static + * @param {Object.} object Plain object + * @returns {google.api.ResourceReference} ResourceReference + */ + ResourceReference.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ResourceReference) + return object; + var message = new $root.google.api.ResourceReference(); + if (object.type != null) + message.type = String(object.type); + if (object.childType != null) + message.childType = String(object.childType); + return message; + }; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ResourceReference + * @static + * @param {google.api.ResourceReference} message ResourceReference + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceReference.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.type = ""; + object.childType = ""; + } + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.childType != null && message.hasOwnProperty("childType")) + object.childType = message.childType; + return object; + }; + + /** + * Converts this ResourceReference to JSON. + * @function toJSON + * @memberof google.api.ResourceReference + * @instance + * @returns {Object.} JSON object + */ + ResourceReference.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResourceReference + * @function getTypeUrl + * @memberof google.api.ResourceReference + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceReference.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ResourceReference"; + }; + + return ResourceReference; + })(); + + api.Http = (function() { + + /** + * Properties of a Http. + * @memberof google.api + * @interface IHttp + * @property {Array.|null} [rules] Http rules + * @property {boolean|null} [fullyDecodeReservedExpansion] Http fullyDecodeReservedExpansion + */ + + /** + * Constructs a new Http. + * @memberof google.api + * @classdesc Represents a Http. + * @implements IHttp + * @constructor + * @param {google.api.IHttp=} [properties] Properties to set + */ + function Http(properties) { + this.rules = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Http rules. + * @member {Array.} rules + * @memberof google.api.Http + * @instance + */ + Http.prototype.rules = $util.emptyArray; + + /** + * Http fullyDecodeReservedExpansion. + * @member {boolean} fullyDecodeReservedExpansion + * @memberof google.api.Http + * @instance + */ + Http.prototype.fullyDecodeReservedExpansion = false; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.Http + * @static + * @param {Object.} object Plain object + * @returns {google.api.Http} Http + */ + Http.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.Http) + return object; + var message = new $root.google.api.Http(); + if (object.rules) { + if (!Array.isArray(object.rules)) + throw TypeError(".google.api.Http.rules: array expected"); + message.rules = []; + for (var i = 0; i < object.rules.length; ++i) { + if (typeof object.rules[i] !== "object") + throw TypeError(".google.api.Http.rules: object expected"); + message.rules[i] = $root.google.api.HttpRule.fromObject(object.rules[i]); + } + } + if (object.fullyDecodeReservedExpansion != null) + message.fullyDecodeReservedExpansion = Boolean(object.fullyDecodeReservedExpansion); + return message; + }; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.Http + * @static + * @param {google.api.Http} message Http + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Http.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.rules = []; + if (options.defaults) + object.fullyDecodeReservedExpansion = false; + if (message.rules && message.rules.length) { + object.rules = []; + for (var j = 0; j < message.rules.length; ++j) + object.rules[j] = $root.google.api.HttpRule.toObject(message.rules[j], options); + } + if (message.fullyDecodeReservedExpansion != null && message.hasOwnProperty("fullyDecodeReservedExpansion")) + object.fullyDecodeReservedExpansion = message.fullyDecodeReservedExpansion; + return object; + }; + + /** + * Converts this Http to JSON. + * @function toJSON + * @memberof google.api.Http + * @instance + * @returns {Object.} JSON object + */ + Http.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Http + * @function getTypeUrl + * @memberof google.api.Http + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Http.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.Http"; + }; + + return Http; + })(); + + api.HttpRule = (function() { + + /** + * Properties of a HttpRule. + * @memberof google.api + * @interface IHttpRule + * @property {string|null} [selector] HttpRule selector + * @property {string|null} [get] HttpRule get + * @property {string|null} [put] HttpRule put + * @property {string|null} [post] HttpRule post + * @property {string|null} ["delete"] HttpRule delete + * @property {string|null} [patch] HttpRule patch + * @property {google.api.ICustomHttpPattern|null} [custom] HttpRule custom + * @property {string|null} [body] HttpRule body + * @property {string|null} [responseBody] HttpRule responseBody + * @property {Array.|null} [additionalBindings] HttpRule additionalBindings + */ + + /** + * Constructs a new HttpRule. + * @memberof google.api + * @classdesc Represents a HttpRule. + * @implements IHttpRule + * @constructor + * @param {google.api.IHttpRule=} [properties] Properties to set + */ + function HttpRule(properties) { + this.additionalBindings = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * HttpRule selector. + * @member {string} selector + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.selector = ""; + + /** + * HttpRule get. + * @member {string|null|undefined} get + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.get = null; + + /** + * HttpRule put. + * @member {string|null|undefined} put + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.put = null; + + /** + * HttpRule post. + * @member {string|null|undefined} post + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.post = null; + + /** + * HttpRule delete. + * @member {string|null|undefined} delete + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype["delete"] = null; + + /** + * HttpRule patch. + * @member {string|null|undefined} patch + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.patch = null; + + /** + * HttpRule custom. + * @member {google.api.ICustomHttpPattern|null|undefined} custom + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.custom = null; + + /** + * HttpRule body. + * @member {string} body + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.body = ""; + + /** + * HttpRule responseBody. + * @member {string} responseBody + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.responseBody = ""; + + /** + * HttpRule additionalBindings. + * @member {Array.} additionalBindings + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.additionalBindings = $util.emptyArray; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * HttpRule pattern. + * @member {"get"|"put"|"post"|"delete"|"patch"|"custom"|undefined} pattern + * @memberof google.api.HttpRule + * @instance + */ + Object.defineProperty(HttpRule.prototype, "pattern", { + get: $util.oneOfGetter($oneOfFields = ["get", "put", "post", "delete", "patch", "custom"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.HttpRule + * @static + * @param {Object.} object Plain object + * @returns {google.api.HttpRule} HttpRule + */ + HttpRule.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.HttpRule) + return object; + var message = new $root.google.api.HttpRule(); + if (object.selector != null) + message.selector = String(object.selector); + if (object.get != null) + message.get = String(object.get); + if (object.put != null) + message.put = String(object.put); + if (object.post != null) + message.post = String(object.post); + if (object["delete"] != null) + message["delete"] = String(object["delete"]); + if (object.patch != null) + message.patch = String(object.patch); + if (object.custom != null) { + if (typeof object.custom !== "object") + throw TypeError(".google.api.HttpRule.custom: object expected"); + message.custom = $root.google.api.CustomHttpPattern.fromObject(object.custom); + } + if (object.body != null) + message.body = String(object.body); + if (object.responseBody != null) + message.responseBody = String(object.responseBody); + if (object.additionalBindings) { + if (!Array.isArray(object.additionalBindings)) + throw TypeError(".google.api.HttpRule.additionalBindings: array expected"); + message.additionalBindings = []; + for (var i = 0; i < object.additionalBindings.length; ++i) { + if (typeof object.additionalBindings[i] !== "object") + throw TypeError(".google.api.HttpRule.additionalBindings: object expected"); + message.additionalBindings[i] = $root.google.api.HttpRule.fromObject(object.additionalBindings[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.HttpRule + * @static + * @param {google.api.HttpRule} message HttpRule + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + HttpRule.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.additionalBindings = []; + if (options.defaults) { + object.selector = ""; + object.body = ""; + object.responseBody = ""; + } + if (message.selector != null && message.hasOwnProperty("selector")) + object.selector = message.selector; + if (message.get != null && message.hasOwnProperty("get")) { + object.get = message.get; + if (options.oneofs) + object.pattern = "get"; + } + if (message.put != null && message.hasOwnProperty("put")) { + object.put = message.put; + if (options.oneofs) + object.pattern = "put"; + } + if (message.post != null && message.hasOwnProperty("post")) { + object.post = message.post; + if (options.oneofs) + object.pattern = "post"; + } + if (message["delete"] != null && message.hasOwnProperty("delete")) { + object["delete"] = message["delete"]; + if (options.oneofs) + object.pattern = "delete"; + } + if (message.patch != null && message.hasOwnProperty("patch")) { + object.patch = message.patch; + if (options.oneofs) + object.pattern = "patch"; + } + if (message.body != null && message.hasOwnProperty("body")) + object.body = message.body; + if (message.custom != null && message.hasOwnProperty("custom")) { + object.custom = $root.google.api.CustomHttpPattern.toObject(message.custom, options); + if (options.oneofs) + object.pattern = "custom"; + } + if (message.additionalBindings && message.additionalBindings.length) { + object.additionalBindings = []; + for (var j = 0; j < message.additionalBindings.length; ++j) + object.additionalBindings[j] = $root.google.api.HttpRule.toObject(message.additionalBindings[j], options); + } + if (message.responseBody != null && message.hasOwnProperty("responseBody")) + object.responseBody = message.responseBody; + return object; + }; + + /** + * Converts this HttpRule to JSON. + * @function toJSON + * @memberof google.api.HttpRule + * @instance + * @returns {Object.} JSON object + */ + HttpRule.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for HttpRule + * @function getTypeUrl + * @memberof google.api.HttpRule + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + HttpRule.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.HttpRule"; + }; + + return HttpRule; + })(); + + api.CustomHttpPattern = (function() { + + /** + * Properties of a CustomHttpPattern. + * @memberof google.api + * @interface ICustomHttpPattern + * @property {string|null} [kind] CustomHttpPattern kind + * @property {string|null} [path] CustomHttpPattern path + */ + + /** + * Constructs a new CustomHttpPattern. + * @memberof google.api + * @classdesc Represents a CustomHttpPattern. + * @implements ICustomHttpPattern + * @constructor + * @param {google.api.ICustomHttpPattern=} [properties] Properties to set + */ + function CustomHttpPattern(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CustomHttpPattern kind. + * @member {string} kind + * @memberof google.api.CustomHttpPattern + * @instance + */ + CustomHttpPattern.prototype.kind = ""; + + /** + * CustomHttpPattern path. + * @member {string} path + * @memberof google.api.CustomHttpPattern + * @instance + */ + CustomHttpPattern.prototype.path = ""; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.CustomHttpPattern + * @static + * @param {Object.} object Plain object + * @returns {google.api.CustomHttpPattern} CustomHttpPattern + */ + CustomHttpPattern.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.CustomHttpPattern) + return object; + var message = new $root.google.api.CustomHttpPattern(); + if (object.kind != null) + message.kind = String(object.kind); + if (object.path != null) + message.path = String(object.path); + return message; + }; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.CustomHttpPattern + * @static + * @param {google.api.CustomHttpPattern} message CustomHttpPattern + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CustomHttpPattern.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.kind = ""; + object.path = ""; + } + if (message.kind != null && message.hasOwnProperty("kind")) + object.kind = message.kind; + if (message.path != null && message.hasOwnProperty("path")) + object.path = message.path; + return object; + }; + + /** + * Converts this CustomHttpPattern to JSON. + * @function toJSON + * @memberof google.api.CustomHttpPattern + * @instance + * @returns {Object.} JSON object + */ + CustomHttpPattern.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CustomHttpPattern + * @function getTypeUrl + * @memberof google.api.CustomHttpPattern + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CustomHttpPattern.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.CustomHttpPattern"; + }; + + return CustomHttpPattern; + })(); + + api.CommonLanguageSettings = (function() { + + /** + * Properties of a CommonLanguageSettings. + * @memberof google.api + * @interface ICommonLanguageSettings + * @property {string|null} [referenceDocsUri] CommonLanguageSettings referenceDocsUri + * @property {Array.|null} [destinations] CommonLanguageSettings destinations + * @property {google.api.ISelectiveGapicGeneration|null} [selectiveGapicGeneration] CommonLanguageSettings selectiveGapicGeneration + */ + + /** + * Constructs a new CommonLanguageSettings. + * @memberof google.api + * @classdesc Represents a CommonLanguageSettings. + * @implements ICommonLanguageSettings + * @constructor + * @param {google.api.ICommonLanguageSettings=} [properties] Properties to set + */ + function CommonLanguageSettings(properties) { + this.destinations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CommonLanguageSettings referenceDocsUri. + * @member {string} referenceDocsUri + * @memberof google.api.CommonLanguageSettings + * @instance + */ + CommonLanguageSettings.prototype.referenceDocsUri = ""; + + /** + * CommonLanguageSettings destinations. + * @member {Array.} destinations + * @memberof google.api.CommonLanguageSettings + * @instance + */ + CommonLanguageSettings.prototype.destinations = $util.emptyArray; + + /** + * CommonLanguageSettings selectiveGapicGeneration. + * @member {google.api.ISelectiveGapicGeneration|null|undefined} selectiveGapicGeneration + * @memberof google.api.CommonLanguageSettings + * @instance + */ + CommonLanguageSettings.prototype.selectiveGapicGeneration = null; + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.CommonLanguageSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.CommonLanguageSettings} CommonLanguageSettings + */ + CommonLanguageSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.CommonLanguageSettings) + return object; + var message = new $root.google.api.CommonLanguageSettings(); + if (object.referenceDocsUri != null) + message.referenceDocsUri = String(object.referenceDocsUri); + if (object.destinations) { + if (!Array.isArray(object.destinations)) + throw TypeError(".google.api.CommonLanguageSettings.destinations: array expected"); + message.destinations = []; + for (var i = 0; i < object.destinations.length; ++i) + switch (object.destinations[i]) { + default: + if (typeof object.destinations[i] === "number") { + message.destinations[i] = object.destinations[i]; + break; + } + case "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED": + case 0: + message.destinations[i] = 0; + break; + case "GITHUB": + case 10: + message.destinations[i] = 10; + break; + case "PACKAGE_MANAGER": + case 20: + message.destinations[i] = 20; + break; + } + } + if (object.selectiveGapicGeneration != null) { + if (typeof object.selectiveGapicGeneration !== "object") + throw TypeError(".google.api.CommonLanguageSettings.selectiveGapicGeneration: object expected"); + message.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.fromObject(object.selectiveGapicGeneration); + } + return message; + }; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.CommonLanguageSettings + * @static + * @param {google.api.CommonLanguageSettings} message CommonLanguageSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CommonLanguageSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.destinations = []; + if (options.defaults) { + object.referenceDocsUri = ""; + object.selectiveGapicGeneration = null; + } + if (message.referenceDocsUri != null && message.hasOwnProperty("referenceDocsUri")) + object.referenceDocsUri = message.referenceDocsUri; + if (message.destinations && message.destinations.length) { + object.destinations = []; + for (var j = 0; j < message.destinations.length; ++j) + object.destinations[j] = options.enums === String ? $root.google.api.ClientLibraryDestination[message.destinations[j]] === undefined ? message.destinations[j] : $root.google.api.ClientLibraryDestination[message.destinations[j]] : message.destinations[j]; + } + if (message.selectiveGapicGeneration != null && message.hasOwnProperty("selectiveGapicGeneration")) + object.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.toObject(message.selectiveGapicGeneration, options); + return object; + }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @function toJSON + * @memberof google.api.CommonLanguageSettings + * @instance + * @returns {Object.} JSON object + */ + CommonLanguageSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CommonLanguageSettings + * @function getTypeUrl + * @memberof google.api.CommonLanguageSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CommonLanguageSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.CommonLanguageSettings"; + }; + + return CommonLanguageSettings; + })(); + + api.ClientLibrarySettings = (function() { + + /** + * Properties of a ClientLibrarySettings. + * @memberof google.api + * @interface IClientLibrarySettings + * @property {string|null} [version] ClientLibrarySettings version + * @property {google.api.LaunchStage|null} [launchStage] ClientLibrarySettings launchStage + * @property {boolean|null} [restNumericEnums] ClientLibrarySettings restNumericEnums + * @property {google.api.IJavaSettings|null} [javaSettings] ClientLibrarySettings javaSettings + * @property {google.api.ICppSettings|null} [cppSettings] ClientLibrarySettings cppSettings + * @property {google.api.IPhpSettings|null} [phpSettings] ClientLibrarySettings phpSettings + * @property {google.api.IPythonSettings|null} [pythonSettings] ClientLibrarySettings pythonSettings + * @property {google.api.INodeSettings|null} [nodeSettings] ClientLibrarySettings nodeSettings + * @property {google.api.IDotnetSettings|null} [dotnetSettings] ClientLibrarySettings dotnetSettings + * @property {google.api.IRubySettings|null} [rubySettings] ClientLibrarySettings rubySettings + * @property {google.api.IGoSettings|null} [goSettings] ClientLibrarySettings goSettings + */ + + /** + * Constructs a new ClientLibrarySettings. + * @memberof google.api + * @classdesc Represents a ClientLibrarySettings. + * @implements IClientLibrarySettings + * @constructor + * @param {google.api.IClientLibrarySettings=} [properties] Properties to set + */ + function ClientLibrarySettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ClientLibrarySettings version. + * @member {string} version + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.version = ""; + + /** + * ClientLibrarySettings launchStage. + * @member {google.api.LaunchStage} launchStage + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.launchStage = 0; + + /** + * ClientLibrarySettings restNumericEnums. + * @member {boolean} restNumericEnums + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.restNumericEnums = false; + + /** + * ClientLibrarySettings javaSettings. + * @member {google.api.IJavaSettings|null|undefined} javaSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.javaSettings = null; + + /** + * ClientLibrarySettings cppSettings. + * @member {google.api.ICppSettings|null|undefined} cppSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.cppSettings = null; + + /** + * ClientLibrarySettings phpSettings. + * @member {google.api.IPhpSettings|null|undefined} phpSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.phpSettings = null; + + /** + * ClientLibrarySettings pythonSettings. + * @member {google.api.IPythonSettings|null|undefined} pythonSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.pythonSettings = null; + + /** + * ClientLibrarySettings nodeSettings. + * @member {google.api.INodeSettings|null|undefined} nodeSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.nodeSettings = null; + + /** + * ClientLibrarySettings dotnetSettings. + * @member {google.api.IDotnetSettings|null|undefined} dotnetSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.dotnetSettings = null; + + /** + * ClientLibrarySettings rubySettings. + * @member {google.api.IRubySettings|null|undefined} rubySettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.rubySettings = null; + + /** + * ClientLibrarySettings goSettings. + * @member {google.api.IGoSettings|null|undefined} goSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.goSettings = null; + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ClientLibrarySettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.ClientLibrarySettings} ClientLibrarySettings + */ + ClientLibrarySettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ClientLibrarySettings) + return object; + var message = new $root.google.api.ClientLibrarySettings(); + if (object.version != null) + message.version = String(object.version); + switch (object.launchStage) { + default: + if (typeof object.launchStage === "number") { + message.launchStage = object.launchStage; + break; + } + break; + case "LAUNCH_STAGE_UNSPECIFIED": + case 0: + message.launchStage = 0; + break; + case "UNIMPLEMENTED": + case 6: + message.launchStage = 6; + break; + case "PRELAUNCH": + case 7: + message.launchStage = 7; + break; + case "EARLY_ACCESS": + case 1: + message.launchStage = 1; + break; + case "ALPHA": + case 2: + message.launchStage = 2; + break; + case "BETA": + case 3: + message.launchStage = 3; + break; + case "GA": + case 4: + message.launchStage = 4; + break; + case "DEPRECATED": + case 5: + message.launchStage = 5; + break; + } + if (object.restNumericEnums != null) + message.restNumericEnums = Boolean(object.restNumericEnums); + if (object.javaSettings != null) { + if (typeof object.javaSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.javaSettings: object expected"); + message.javaSettings = $root.google.api.JavaSettings.fromObject(object.javaSettings); + } + if (object.cppSettings != null) { + if (typeof object.cppSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.cppSettings: object expected"); + message.cppSettings = $root.google.api.CppSettings.fromObject(object.cppSettings); + } + if (object.phpSettings != null) { + if (typeof object.phpSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.phpSettings: object expected"); + message.phpSettings = $root.google.api.PhpSettings.fromObject(object.phpSettings); + } + if (object.pythonSettings != null) { + if (typeof object.pythonSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.pythonSettings: object expected"); + message.pythonSettings = $root.google.api.PythonSettings.fromObject(object.pythonSettings); + } + if (object.nodeSettings != null) { + if (typeof object.nodeSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.nodeSettings: object expected"); + message.nodeSettings = $root.google.api.NodeSettings.fromObject(object.nodeSettings); + } + if (object.dotnetSettings != null) { + if (typeof object.dotnetSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.dotnetSettings: object expected"); + message.dotnetSettings = $root.google.api.DotnetSettings.fromObject(object.dotnetSettings); + } + if (object.rubySettings != null) { + if (typeof object.rubySettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.rubySettings: object expected"); + message.rubySettings = $root.google.api.RubySettings.fromObject(object.rubySettings); + } + if (object.goSettings != null) { + if (typeof object.goSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.goSettings: object expected"); + message.goSettings = $root.google.api.GoSettings.fromObject(object.goSettings); + } + return message; + }; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ClientLibrarySettings + * @static + * @param {google.api.ClientLibrarySettings} message ClientLibrarySettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ClientLibrarySettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.version = ""; + object.launchStage = options.enums === String ? "LAUNCH_STAGE_UNSPECIFIED" : 0; + object.restNumericEnums = false; + object.javaSettings = null; + object.cppSettings = null; + object.phpSettings = null; + object.pythonSettings = null; + object.nodeSettings = null; + object.dotnetSettings = null; + object.rubySettings = null; + object.goSettings = null; + } + if (message.version != null && message.hasOwnProperty("version")) + object.version = message.version; + if (message.launchStage != null && message.hasOwnProperty("launchStage")) + object.launchStage = options.enums === String ? $root.google.api.LaunchStage[message.launchStage] === undefined ? message.launchStage : $root.google.api.LaunchStage[message.launchStage] : message.launchStage; + if (message.restNumericEnums != null && message.hasOwnProperty("restNumericEnums")) + object.restNumericEnums = message.restNumericEnums; + if (message.javaSettings != null && message.hasOwnProperty("javaSettings")) + object.javaSettings = $root.google.api.JavaSettings.toObject(message.javaSettings, options); + if (message.cppSettings != null && message.hasOwnProperty("cppSettings")) + object.cppSettings = $root.google.api.CppSettings.toObject(message.cppSettings, options); + if (message.phpSettings != null && message.hasOwnProperty("phpSettings")) + object.phpSettings = $root.google.api.PhpSettings.toObject(message.phpSettings, options); + if (message.pythonSettings != null && message.hasOwnProperty("pythonSettings")) + object.pythonSettings = $root.google.api.PythonSettings.toObject(message.pythonSettings, options); + if (message.nodeSettings != null && message.hasOwnProperty("nodeSettings")) + object.nodeSettings = $root.google.api.NodeSettings.toObject(message.nodeSettings, options); + if (message.dotnetSettings != null && message.hasOwnProperty("dotnetSettings")) + object.dotnetSettings = $root.google.api.DotnetSettings.toObject(message.dotnetSettings, options); + if (message.rubySettings != null && message.hasOwnProperty("rubySettings")) + object.rubySettings = $root.google.api.RubySettings.toObject(message.rubySettings, options); + if (message.goSettings != null && message.hasOwnProperty("goSettings")) + object.goSettings = $root.google.api.GoSettings.toObject(message.goSettings, options); + return object; + }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @function toJSON + * @memberof google.api.ClientLibrarySettings + * @instance + * @returns {Object.} JSON object + */ + ClientLibrarySettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ClientLibrarySettings + * @function getTypeUrl + * @memberof google.api.ClientLibrarySettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ClientLibrarySettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ClientLibrarySettings"; + }; + + return ClientLibrarySettings; + })(); + + api.Publishing = (function() { + + /** + * Properties of a Publishing. + * @memberof google.api + * @interface IPublishing + * @property {Array.|null} [methodSettings] Publishing methodSettings + * @property {string|null} [newIssueUri] Publishing newIssueUri + * @property {string|null} [documentationUri] Publishing documentationUri + * @property {string|null} [apiShortName] Publishing apiShortName + * @property {string|null} [githubLabel] Publishing githubLabel + * @property {Array.|null} [codeownerGithubTeams] Publishing codeownerGithubTeams + * @property {string|null} [docTagPrefix] Publishing docTagPrefix + * @property {google.api.ClientLibraryOrganization|null} [organization] Publishing organization + * @property {Array.|null} [librarySettings] Publishing librarySettings + * @property {string|null} [protoReferenceDocumentationUri] Publishing protoReferenceDocumentationUri + * @property {string|null} [restReferenceDocumentationUri] Publishing restReferenceDocumentationUri + */ + + /** + * Constructs a new Publishing. + * @memberof google.api + * @classdesc Represents a Publishing. + * @implements IPublishing + * @constructor + * @param {google.api.IPublishing=} [properties] Properties to set + */ + function Publishing(properties) { + this.methodSettings = []; + this.codeownerGithubTeams = []; + this.librarySettings = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Publishing methodSettings. + * @member {Array.} methodSettings + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.methodSettings = $util.emptyArray; + + /** + * Publishing newIssueUri. + * @member {string} newIssueUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.newIssueUri = ""; + + /** + * Publishing documentationUri. + * @member {string} documentationUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.documentationUri = ""; + + /** + * Publishing apiShortName. + * @member {string} apiShortName + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.apiShortName = ""; + + /** + * Publishing githubLabel. + * @member {string} githubLabel + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.githubLabel = ""; + + /** + * Publishing codeownerGithubTeams. + * @member {Array.} codeownerGithubTeams + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.codeownerGithubTeams = $util.emptyArray; + + /** + * Publishing docTagPrefix. + * @member {string} docTagPrefix + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.docTagPrefix = ""; + + /** + * Publishing organization. + * @member {google.api.ClientLibraryOrganization} organization + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.organization = 0; + + /** + * Publishing librarySettings. + * @member {Array.} librarySettings + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.librarySettings = $util.emptyArray; + + /** + * Publishing protoReferenceDocumentationUri. + * @member {string} protoReferenceDocumentationUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.protoReferenceDocumentationUri = ""; + + /** + * Publishing restReferenceDocumentationUri. + * @member {string} restReferenceDocumentationUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.restReferenceDocumentationUri = ""; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.Publishing + * @static + * @param {Object.} object Plain object + * @returns {google.api.Publishing} Publishing + */ + Publishing.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.Publishing) + return object; + var message = new $root.google.api.Publishing(); + if (object.methodSettings) { + if (!Array.isArray(object.methodSettings)) + throw TypeError(".google.api.Publishing.methodSettings: array expected"); + message.methodSettings = []; + for (var i = 0; i < object.methodSettings.length; ++i) { + if (typeof object.methodSettings[i] !== "object") + throw TypeError(".google.api.Publishing.methodSettings: object expected"); + message.methodSettings[i] = $root.google.api.MethodSettings.fromObject(object.methodSettings[i]); + } + } + if (object.newIssueUri != null) + message.newIssueUri = String(object.newIssueUri); + if (object.documentationUri != null) + message.documentationUri = String(object.documentationUri); + if (object.apiShortName != null) + message.apiShortName = String(object.apiShortName); + if (object.githubLabel != null) + message.githubLabel = String(object.githubLabel); + if (object.codeownerGithubTeams) { + if (!Array.isArray(object.codeownerGithubTeams)) + throw TypeError(".google.api.Publishing.codeownerGithubTeams: array expected"); + message.codeownerGithubTeams = []; + for (var i = 0; i < object.codeownerGithubTeams.length; ++i) + message.codeownerGithubTeams[i] = String(object.codeownerGithubTeams[i]); + } + if (object.docTagPrefix != null) + message.docTagPrefix = String(object.docTagPrefix); + switch (object.organization) { + default: + if (typeof object.organization === "number") { + message.organization = object.organization; + break; + } + break; + case "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED": + case 0: + message.organization = 0; + break; + case "CLOUD": + case 1: + message.organization = 1; + break; + case "ADS": + case 2: + message.organization = 2; + break; + case "PHOTOS": + case 3: + message.organization = 3; + break; + case "STREET_VIEW": + case 4: + message.organization = 4; + break; + case "SHOPPING": + case 5: + message.organization = 5; + break; + case "GEO": + case 6: + message.organization = 6; + break; + case "GENERATIVE_AI": + case 7: + message.organization = 7; + break; + } + if (object.librarySettings) { + if (!Array.isArray(object.librarySettings)) + throw TypeError(".google.api.Publishing.librarySettings: array expected"); + message.librarySettings = []; + for (var i = 0; i < object.librarySettings.length; ++i) { + if (typeof object.librarySettings[i] !== "object") + throw TypeError(".google.api.Publishing.librarySettings: object expected"); + message.librarySettings[i] = $root.google.api.ClientLibrarySettings.fromObject(object.librarySettings[i]); + } + } + if (object.protoReferenceDocumentationUri != null) + message.protoReferenceDocumentationUri = String(object.protoReferenceDocumentationUri); + if (object.restReferenceDocumentationUri != null) + message.restReferenceDocumentationUri = String(object.restReferenceDocumentationUri); + return message; + }; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.Publishing + * @static + * @param {google.api.Publishing} message Publishing + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Publishing.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.methodSettings = []; + object.codeownerGithubTeams = []; + object.librarySettings = []; + } + if (options.defaults) { + object.newIssueUri = ""; + object.documentationUri = ""; + object.apiShortName = ""; + object.githubLabel = ""; + object.docTagPrefix = ""; + object.organization = options.enums === String ? "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED" : 0; + object.protoReferenceDocumentationUri = ""; + object.restReferenceDocumentationUri = ""; + } + if (message.methodSettings && message.methodSettings.length) { + object.methodSettings = []; + for (var j = 0; j < message.methodSettings.length; ++j) + object.methodSettings[j] = $root.google.api.MethodSettings.toObject(message.methodSettings[j], options); + } + if (message.newIssueUri != null && message.hasOwnProperty("newIssueUri")) + object.newIssueUri = message.newIssueUri; + if (message.documentationUri != null && message.hasOwnProperty("documentationUri")) + object.documentationUri = message.documentationUri; + if (message.apiShortName != null && message.hasOwnProperty("apiShortName")) + object.apiShortName = message.apiShortName; + if (message.githubLabel != null && message.hasOwnProperty("githubLabel")) + object.githubLabel = message.githubLabel; + if (message.codeownerGithubTeams && message.codeownerGithubTeams.length) { + object.codeownerGithubTeams = []; + for (var j = 0; j < message.codeownerGithubTeams.length; ++j) + object.codeownerGithubTeams[j] = message.codeownerGithubTeams[j]; + } + if (message.docTagPrefix != null && message.hasOwnProperty("docTagPrefix")) + object.docTagPrefix = message.docTagPrefix; + if (message.organization != null && message.hasOwnProperty("organization")) + object.organization = options.enums === String ? $root.google.api.ClientLibraryOrganization[message.organization] === undefined ? message.organization : $root.google.api.ClientLibraryOrganization[message.organization] : message.organization; + if (message.librarySettings && message.librarySettings.length) { + object.librarySettings = []; + for (var j = 0; j < message.librarySettings.length; ++j) + object.librarySettings[j] = $root.google.api.ClientLibrarySettings.toObject(message.librarySettings[j], options); + } + if (message.protoReferenceDocumentationUri != null && message.hasOwnProperty("protoReferenceDocumentationUri")) + object.protoReferenceDocumentationUri = message.protoReferenceDocumentationUri; + if (message.restReferenceDocumentationUri != null && message.hasOwnProperty("restReferenceDocumentationUri")) + object.restReferenceDocumentationUri = message.restReferenceDocumentationUri; + return object; + }; + + /** + * Converts this Publishing to JSON. + * @function toJSON + * @memberof google.api.Publishing + * @instance + * @returns {Object.} JSON object + */ + Publishing.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Publishing + * @function getTypeUrl + * @memberof google.api.Publishing + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Publishing.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.Publishing"; + }; + + return Publishing; + })(); + + api.JavaSettings = (function() { + + /** + * Properties of a JavaSettings. + * @memberof google.api + * @interface IJavaSettings + * @property {string|null} [libraryPackage] JavaSettings libraryPackage + * @property {Object.|null} [serviceClassNames] JavaSettings serviceClassNames + * @property {google.api.ICommonLanguageSettings|null} [common] JavaSettings common + */ + + /** + * Constructs a new JavaSettings. + * @memberof google.api + * @classdesc Represents a JavaSettings. + * @implements IJavaSettings + * @constructor + * @param {google.api.IJavaSettings=} [properties] Properties to set + */ + function JavaSettings(properties) { + this.serviceClassNames = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * JavaSettings libraryPackage. + * @member {string} libraryPackage + * @memberof google.api.JavaSettings + * @instance + */ + JavaSettings.prototype.libraryPackage = ""; + + /** + * JavaSettings serviceClassNames. + * @member {Object.} serviceClassNames + * @memberof google.api.JavaSettings + * @instance + */ + JavaSettings.prototype.serviceClassNames = $util.emptyObject; + + /** + * JavaSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.JavaSettings + * @instance + */ + JavaSettings.prototype.common = null; + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.JavaSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.JavaSettings} JavaSettings + */ + JavaSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.JavaSettings) + return object; + var message = new $root.google.api.JavaSettings(); + if (object.libraryPackage != null) + message.libraryPackage = String(object.libraryPackage); + if (object.serviceClassNames) { + if (typeof object.serviceClassNames !== "object") + throw TypeError(".google.api.JavaSettings.serviceClassNames: object expected"); + message.serviceClassNames = {}; + for (var keys = Object.keys(object.serviceClassNames), i = 0; i < keys.length; ++i) + message.serviceClassNames[keys[i]] = String(object.serviceClassNames[keys[i]]); + } + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.JavaSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.JavaSettings + * @static + * @param {google.api.JavaSettings} message JavaSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + JavaSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.serviceClassNames = {}; + if (options.defaults) { + object.libraryPackage = ""; + object.common = null; + } + if (message.libraryPackage != null && message.hasOwnProperty("libraryPackage")) + object.libraryPackage = message.libraryPackage; + var keys2; + if (message.serviceClassNames && (keys2 = Object.keys(message.serviceClassNames)).length) { + object.serviceClassNames = {}; + for (var j = 0; j < keys2.length; ++j) + object.serviceClassNames[keys2[j]] = message.serviceClassNames[keys2[j]]; + } + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this JavaSettings to JSON. + * @function toJSON + * @memberof google.api.JavaSettings + * @instance + * @returns {Object.} JSON object + */ + JavaSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for JavaSettings + * @function getTypeUrl + * @memberof google.api.JavaSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + JavaSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.JavaSettings"; + }; + + return JavaSettings; + })(); + + api.CppSettings = (function() { + + /** + * Properties of a CppSettings. + * @memberof google.api + * @interface ICppSettings + * @property {google.api.ICommonLanguageSettings|null} [common] CppSettings common + */ + + /** + * Constructs a new CppSettings. + * @memberof google.api + * @classdesc Represents a CppSettings. + * @implements ICppSettings + * @constructor + * @param {google.api.ICppSettings=} [properties] Properties to set + */ + function CppSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CppSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.CppSettings + * @instance + */ + CppSettings.prototype.common = null; + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.CppSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.CppSettings} CppSettings + */ + CppSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.CppSettings) + return object; + var message = new $root.google.api.CppSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.CppSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.CppSettings + * @static + * @param {google.api.CppSettings} message CppSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CppSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this CppSettings to JSON. + * @function toJSON + * @memberof google.api.CppSettings + * @instance + * @returns {Object.} JSON object + */ + CppSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CppSettings + * @function getTypeUrl + * @memberof google.api.CppSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CppSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.CppSettings"; + }; + + return CppSettings; + })(); + + api.PhpSettings = (function() { + + /** + * Properties of a PhpSettings. + * @memberof google.api + * @interface IPhpSettings + * @property {google.api.ICommonLanguageSettings|null} [common] PhpSettings common + */ + + /** + * Constructs a new PhpSettings. + * @memberof google.api + * @classdesc Represents a PhpSettings. + * @implements IPhpSettings + * @constructor + * @param {google.api.IPhpSettings=} [properties] Properties to set + */ + function PhpSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PhpSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.PhpSettings + * @instance + */ + PhpSettings.prototype.common = null; + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.PhpSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.PhpSettings} PhpSettings + */ + PhpSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.PhpSettings) + return object; + var message = new $root.google.api.PhpSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.PhpSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.PhpSettings + * @static + * @param {google.api.PhpSettings} message PhpSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PhpSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this PhpSettings to JSON. + * @function toJSON + * @memberof google.api.PhpSettings + * @instance + * @returns {Object.} JSON object + */ + PhpSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PhpSettings + * @function getTypeUrl + * @memberof google.api.PhpSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PhpSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.PhpSettings"; + }; + + return PhpSettings; + })(); + + api.PythonSettings = (function() { + + /** + * Properties of a PythonSettings. + * @memberof google.api + * @interface IPythonSettings + * @property {google.api.ICommonLanguageSettings|null} [common] PythonSettings common + * @property {google.api.PythonSettings.IExperimentalFeatures|null} [experimentalFeatures] PythonSettings experimentalFeatures + */ + + /** + * Constructs a new PythonSettings. + * @memberof google.api + * @classdesc Represents a PythonSettings. + * @implements IPythonSettings + * @constructor + * @param {google.api.IPythonSettings=} [properties] Properties to set + */ + function PythonSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PythonSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.PythonSettings + * @instance + */ + PythonSettings.prototype.common = null; + + /** + * PythonSettings experimentalFeatures. + * @member {google.api.PythonSettings.IExperimentalFeatures|null|undefined} experimentalFeatures + * @memberof google.api.PythonSettings + * @instance + */ + PythonSettings.prototype.experimentalFeatures = null; + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.PythonSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.PythonSettings} PythonSettings + */ + PythonSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.PythonSettings) + return object; + var message = new $root.google.api.PythonSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.PythonSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + if (object.experimentalFeatures != null) { + if (typeof object.experimentalFeatures !== "object") + throw TypeError(".google.api.PythonSettings.experimentalFeatures: object expected"); + message.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.fromObject(object.experimentalFeatures); + } + return message; + }; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.PythonSettings + * @static + * @param {google.api.PythonSettings} message PythonSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PythonSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.common = null; + object.experimentalFeatures = null; + } + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + if (message.experimentalFeatures != null && message.hasOwnProperty("experimentalFeatures")) + object.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.toObject(message.experimentalFeatures, options); + return object; + }; + + /** + * Converts this PythonSettings to JSON. + * @function toJSON + * @memberof google.api.PythonSettings + * @instance + * @returns {Object.} JSON object + */ + PythonSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PythonSettings + * @function getTypeUrl + * @memberof google.api.PythonSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PythonSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.PythonSettings"; + }; + + PythonSettings.ExperimentalFeatures = (function() { + + /** + * Properties of an ExperimentalFeatures. + * @memberof google.api.PythonSettings + * @interface IExperimentalFeatures + * @property {boolean|null} [restAsyncIoEnabled] ExperimentalFeatures restAsyncIoEnabled + * @property {boolean|null} [protobufPythonicTypesEnabled] ExperimentalFeatures protobufPythonicTypesEnabled + * @property {boolean|null} [unversionedPackageDisabled] ExperimentalFeatures unversionedPackageDisabled + */ + + /** + * Constructs a new ExperimentalFeatures. + * @memberof google.api.PythonSettings + * @classdesc Represents an ExperimentalFeatures. + * @implements IExperimentalFeatures + * @constructor + * @param {google.api.PythonSettings.IExperimentalFeatures=} [properties] Properties to set + */ + function ExperimentalFeatures(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExperimentalFeatures restAsyncIoEnabled. + * @member {boolean} restAsyncIoEnabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.restAsyncIoEnabled = false; + + /** + * ExperimentalFeatures protobufPythonicTypesEnabled. + * @member {boolean} protobufPythonicTypesEnabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.protobufPythonicTypesEnabled = false; + + /** + * ExperimentalFeatures unversionedPackageDisabled. + * @member {boolean} unversionedPackageDisabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.unversionedPackageDisabled = false; + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {Object.} object Plain object + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + */ + ExperimentalFeatures.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.PythonSettings.ExperimentalFeatures) + return object; + var message = new $root.google.api.PythonSettings.ExperimentalFeatures(); + if (object.restAsyncIoEnabled != null) + message.restAsyncIoEnabled = Boolean(object.restAsyncIoEnabled); + if (object.protobufPythonicTypesEnabled != null) + message.protobufPythonicTypesEnabled = Boolean(object.protobufPythonicTypesEnabled); + if (object.unversionedPackageDisabled != null) + message.unversionedPackageDisabled = Boolean(object.unversionedPackageDisabled); + return message; + }; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.ExperimentalFeatures} message ExperimentalFeatures + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExperimentalFeatures.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.restAsyncIoEnabled = false; + object.protobufPythonicTypesEnabled = false; + object.unversionedPackageDisabled = false; + } + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + object.restAsyncIoEnabled = message.restAsyncIoEnabled; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + object.protobufPythonicTypesEnabled = message.protobufPythonicTypesEnabled; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + object.unversionedPackageDisabled = message.unversionedPackageDisabled; + return object; + }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @function toJSON + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + * @returns {Object.} JSON object + */ + ExperimentalFeatures.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExperimentalFeatures + * @function getTypeUrl + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExperimentalFeatures.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.PythonSettings.ExperimentalFeatures"; + }; + + return ExperimentalFeatures; + })(); + + return PythonSettings; + })(); + + api.NodeSettings = (function() { + + /** + * Properties of a NodeSettings. + * @memberof google.api + * @interface INodeSettings + * @property {google.api.ICommonLanguageSettings|null} [common] NodeSettings common + */ + + /** + * Constructs a new NodeSettings. + * @memberof google.api + * @classdesc Represents a NodeSettings. + * @implements INodeSettings + * @constructor + * @param {google.api.INodeSettings=} [properties] Properties to set + */ + function NodeSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * NodeSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.NodeSettings + * @instance + */ + NodeSettings.prototype.common = null; + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.NodeSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.NodeSettings} NodeSettings + */ + NodeSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.NodeSettings) + return object; + var message = new $root.google.api.NodeSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.NodeSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.NodeSettings + * @static + * @param {google.api.NodeSettings} message NodeSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + NodeSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this NodeSettings to JSON. + * @function toJSON + * @memberof google.api.NodeSettings + * @instance + * @returns {Object.} JSON object + */ + NodeSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for NodeSettings + * @function getTypeUrl + * @memberof google.api.NodeSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + NodeSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.NodeSettings"; + }; + + return NodeSettings; + })(); + + api.DotnetSettings = (function() { + + /** + * Properties of a DotnetSettings. + * @memberof google.api + * @interface IDotnetSettings + * @property {google.api.ICommonLanguageSettings|null} [common] DotnetSettings common + * @property {Object.|null} [renamedServices] DotnetSettings renamedServices + * @property {Object.|null} [renamedResources] DotnetSettings renamedResources + * @property {Array.|null} [ignoredResources] DotnetSettings ignoredResources + * @property {Array.|null} [forcedNamespaceAliases] DotnetSettings forcedNamespaceAliases + * @property {Array.|null} [handwrittenSignatures] DotnetSettings handwrittenSignatures + */ + + /** + * Constructs a new DotnetSettings. + * @memberof google.api + * @classdesc Represents a DotnetSettings. + * @implements IDotnetSettings + * @constructor + * @param {google.api.IDotnetSettings=} [properties] Properties to set + */ + function DotnetSettings(properties) { + this.renamedServices = {}; + this.renamedResources = {}; + this.ignoredResources = []; + this.forcedNamespaceAliases = []; + this.handwrittenSignatures = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DotnetSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.common = null; + + /** + * DotnetSettings renamedServices. + * @member {Object.} renamedServices + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.renamedServices = $util.emptyObject; + + /** + * DotnetSettings renamedResources. + * @member {Object.} renamedResources + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.renamedResources = $util.emptyObject; + + /** + * DotnetSettings ignoredResources. + * @member {Array.} ignoredResources + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.ignoredResources = $util.emptyArray; + + /** + * DotnetSettings forcedNamespaceAliases. + * @member {Array.} forcedNamespaceAliases + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.forcedNamespaceAliases = $util.emptyArray; + + /** + * DotnetSettings handwrittenSignatures. + * @member {Array.} handwrittenSignatures + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.handwrittenSignatures = $util.emptyArray; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.DotnetSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.DotnetSettings} DotnetSettings + */ + DotnetSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.DotnetSettings) + return object; + var message = new $root.google.api.DotnetSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.DotnetSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + if (object.renamedServices) { + if (typeof object.renamedServices !== "object") + throw TypeError(".google.api.DotnetSettings.renamedServices: object expected"); + message.renamedServices = {}; + for (var keys = Object.keys(object.renamedServices), i = 0; i < keys.length; ++i) + message.renamedServices[keys[i]] = String(object.renamedServices[keys[i]]); + } + if (object.renamedResources) { + if (typeof object.renamedResources !== "object") + throw TypeError(".google.api.DotnetSettings.renamedResources: object expected"); + message.renamedResources = {}; + for (var keys = Object.keys(object.renamedResources), i = 0; i < keys.length; ++i) + message.renamedResources[keys[i]] = String(object.renamedResources[keys[i]]); + } + if (object.ignoredResources) { + if (!Array.isArray(object.ignoredResources)) + throw TypeError(".google.api.DotnetSettings.ignoredResources: array expected"); + message.ignoredResources = []; + for (var i = 0; i < object.ignoredResources.length; ++i) + message.ignoredResources[i] = String(object.ignoredResources[i]); + } + if (object.forcedNamespaceAliases) { + if (!Array.isArray(object.forcedNamespaceAliases)) + throw TypeError(".google.api.DotnetSettings.forcedNamespaceAliases: array expected"); + message.forcedNamespaceAliases = []; + for (var i = 0; i < object.forcedNamespaceAliases.length; ++i) + message.forcedNamespaceAliases[i] = String(object.forcedNamespaceAliases[i]); + } + if (object.handwrittenSignatures) { + if (!Array.isArray(object.handwrittenSignatures)) + throw TypeError(".google.api.DotnetSettings.handwrittenSignatures: array expected"); + message.handwrittenSignatures = []; + for (var i = 0; i < object.handwrittenSignatures.length; ++i) + message.handwrittenSignatures[i] = String(object.handwrittenSignatures[i]); + } + return message; + }; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.DotnetSettings + * @static + * @param {google.api.DotnetSettings} message DotnetSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DotnetSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.ignoredResources = []; + object.forcedNamespaceAliases = []; + object.handwrittenSignatures = []; + } + if (options.objects || options.defaults) { + object.renamedServices = {}; + object.renamedResources = {}; + } + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + var keys2; + if (message.renamedServices && (keys2 = Object.keys(message.renamedServices)).length) { + object.renamedServices = {}; + for (var j = 0; j < keys2.length; ++j) + object.renamedServices[keys2[j]] = message.renamedServices[keys2[j]]; + } + if (message.renamedResources && (keys2 = Object.keys(message.renamedResources)).length) { + object.renamedResources = {}; + for (var j = 0; j < keys2.length; ++j) + object.renamedResources[keys2[j]] = message.renamedResources[keys2[j]]; + } + if (message.ignoredResources && message.ignoredResources.length) { + object.ignoredResources = []; + for (var j = 0; j < message.ignoredResources.length; ++j) + object.ignoredResources[j] = message.ignoredResources[j]; + } + if (message.forcedNamespaceAliases && message.forcedNamespaceAliases.length) { + object.forcedNamespaceAliases = []; + for (var j = 0; j < message.forcedNamespaceAliases.length; ++j) + object.forcedNamespaceAliases[j] = message.forcedNamespaceAliases[j]; + } + if (message.handwrittenSignatures && message.handwrittenSignatures.length) { + object.handwrittenSignatures = []; + for (var j = 0; j < message.handwrittenSignatures.length; ++j) + object.handwrittenSignatures[j] = message.handwrittenSignatures[j]; + } + return object; + }; + + /** + * Converts this DotnetSettings to JSON. + * @function toJSON + * @memberof google.api.DotnetSettings + * @instance + * @returns {Object.} JSON object + */ + DotnetSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DotnetSettings + * @function getTypeUrl + * @memberof google.api.DotnetSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DotnetSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.DotnetSettings"; + }; + + return DotnetSettings; + })(); + + api.RubySettings = (function() { + + /** + * Properties of a RubySettings. + * @memberof google.api + * @interface IRubySettings + * @property {google.api.ICommonLanguageSettings|null} [common] RubySettings common + */ + + /** + * Constructs a new RubySettings. + * @memberof google.api + * @classdesc Represents a RubySettings. + * @implements IRubySettings + * @constructor + * @param {google.api.IRubySettings=} [properties] Properties to set + */ + function RubySettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RubySettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.RubySettings + * @instance + */ + RubySettings.prototype.common = null; + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.RubySettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.RubySettings} RubySettings + */ + RubySettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RubySettings) + return object; + var message = new $root.google.api.RubySettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.RubySettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.RubySettings + * @static + * @param {google.api.RubySettings} message RubySettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RubySettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this RubySettings to JSON. + * @function toJSON + * @memberof google.api.RubySettings + * @instance + * @returns {Object.} JSON object + */ + RubySettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RubySettings + * @function getTypeUrl + * @memberof google.api.RubySettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RubySettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.RubySettings"; + }; + + return RubySettings; + })(); + + api.GoSettings = (function() { + + /** + * Properties of a GoSettings. + * @memberof google.api + * @interface IGoSettings + * @property {google.api.ICommonLanguageSettings|null} [common] GoSettings common + * @property {Object.|null} [renamedServices] GoSettings renamedServices + */ + + /** + * Constructs a new GoSettings. + * @memberof google.api + * @classdesc Represents a GoSettings. + * @implements IGoSettings + * @constructor + * @param {google.api.IGoSettings=} [properties] Properties to set + */ + function GoSettings(properties) { + this.renamedServices = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GoSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.GoSettings + * @instance + */ + GoSettings.prototype.common = null; + + /** + * GoSettings renamedServices. + * @member {Object.} renamedServices + * @memberof google.api.GoSettings + * @instance + */ + GoSettings.prototype.renamedServices = $util.emptyObject; + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.GoSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.GoSettings} GoSettings + */ + GoSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.GoSettings) + return object; + var message = new $root.google.api.GoSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.GoSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + if (object.renamedServices) { + if (typeof object.renamedServices !== "object") + throw TypeError(".google.api.GoSettings.renamedServices: object expected"); + message.renamedServices = {}; + for (var keys = Object.keys(object.renamedServices), i = 0; i < keys.length; ++i) + message.renamedServices[keys[i]] = String(object.renamedServices[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.GoSettings + * @static + * @param {google.api.GoSettings} message GoSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GoSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.renamedServices = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + var keys2; + if (message.renamedServices && (keys2 = Object.keys(message.renamedServices)).length) { + object.renamedServices = {}; + for (var j = 0; j < keys2.length; ++j) + object.renamedServices[keys2[j]] = message.renamedServices[keys2[j]]; + } + return object; + }; + + /** + * Converts this GoSettings to JSON. + * @function toJSON + * @memberof google.api.GoSettings + * @instance + * @returns {Object.} JSON object + */ + GoSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GoSettings + * @function getTypeUrl + * @memberof google.api.GoSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GoSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.GoSettings"; + }; + + return GoSettings; + })(); + + api.MethodSettings = (function() { + + /** + * Properties of a MethodSettings. + * @memberof google.api + * @interface IMethodSettings + * @property {string|null} [selector] MethodSettings selector + * @property {google.api.MethodSettings.ILongRunning|null} [longRunning] MethodSettings longRunning + * @property {Array.|null} [autoPopulatedFields] MethodSettings autoPopulatedFields + */ + + /** + * Constructs a new MethodSettings. + * @memberof google.api + * @classdesc Represents a MethodSettings. + * @implements IMethodSettings + * @constructor + * @param {google.api.IMethodSettings=} [properties] Properties to set + */ + function MethodSettings(properties) { + this.autoPopulatedFields = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MethodSettings selector. + * @member {string} selector + * @memberof google.api.MethodSettings + * @instance + */ + MethodSettings.prototype.selector = ""; + + /** + * MethodSettings longRunning. + * @member {google.api.MethodSettings.ILongRunning|null|undefined} longRunning + * @memberof google.api.MethodSettings + * @instance + */ + MethodSettings.prototype.longRunning = null; + + /** + * MethodSettings autoPopulatedFields. + * @member {Array.} autoPopulatedFields + * @memberof google.api.MethodSettings + * @instance + */ + MethodSettings.prototype.autoPopulatedFields = $util.emptyArray; + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.MethodSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.MethodSettings} MethodSettings + */ + MethodSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.MethodSettings) + return object; + var message = new $root.google.api.MethodSettings(); + if (object.selector != null) + message.selector = String(object.selector); + if (object.longRunning != null) { + if (typeof object.longRunning !== "object") + throw TypeError(".google.api.MethodSettings.longRunning: object expected"); + message.longRunning = $root.google.api.MethodSettings.LongRunning.fromObject(object.longRunning); + } + if (object.autoPopulatedFields) { + if (!Array.isArray(object.autoPopulatedFields)) + throw TypeError(".google.api.MethodSettings.autoPopulatedFields: array expected"); + message.autoPopulatedFields = []; + for (var i = 0; i < object.autoPopulatedFields.length; ++i) + message.autoPopulatedFields[i] = String(object.autoPopulatedFields[i]); + } + return message; + }; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.MethodSettings + * @static + * @param {google.api.MethodSettings} message MethodSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MethodSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.autoPopulatedFields = []; + if (options.defaults) { + object.selector = ""; + object.longRunning = null; + } + if (message.selector != null && message.hasOwnProperty("selector")) + object.selector = message.selector; + if (message.longRunning != null && message.hasOwnProperty("longRunning")) + object.longRunning = $root.google.api.MethodSettings.LongRunning.toObject(message.longRunning, options); + if (message.autoPopulatedFields && message.autoPopulatedFields.length) { + object.autoPopulatedFields = []; + for (var j = 0; j < message.autoPopulatedFields.length; ++j) + object.autoPopulatedFields[j] = message.autoPopulatedFields[j]; + } + return object; + }; + + /** + * Converts this MethodSettings to JSON. + * @function toJSON + * @memberof google.api.MethodSettings + * @instance + * @returns {Object.} JSON object + */ + MethodSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MethodSettings + * @function getTypeUrl + * @memberof google.api.MethodSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MethodSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.MethodSettings"; + }; + + MethodSettings.LongRunning = (function() { + + /** + * Properties of a LongRunning. + * @memberof google.api.MethodSettings + * @interface ILongRunning + * @property {google.protobuf.IDuration|null} [initialPollDelay] LongRunning initialPollDelay + * @property {number|null} [pollDelayMultiplier] LongRunning pollDelayMultiplier + * @property {google.protobuf.IDuration|null} [maxPollDelay] LongRunning maxPollDelay + * @property {google.protobuf.IDuration|null} [totalPollTimeout] LongRunning totalPollTimeout + */ + + /** + * Constructs a new LongRunning. + * @memberof google.api.MethodSettings + * @classdesc Represents a LongRunning. + * @implements ILongRunning + * @constructor + * @param {google.api.MethodSettings.ILongRunning=} [properties] Properties to set + */ + function LongRunning(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * LongRunning initialPollDelay. + * @member {google.protobuf.IDuration|null|undefined} initialPollDelay + * @memberof google.api.MethodSettings.LongRunning + * @instance + */ + LongRunning.prototype.initialPollDelay = null; + + /** + * LongRunning pollDelayMultiplier. + * @member {number} pollDelayMultiplier + * @memberof google.api.MethodSettings.LongRunning + * @instance + */ + LongRunning.prototype.pollDelayMultiplier = 0; + + /** + * LongRunning maxPollDelay. + * @member {google.protobuf.IDuration|null|undefined} maxPollDelay + * @memberof google.api.MethodSettings.LongRunning + * @instance + */ + LongRunning.prototype.maxPollDelay = null; + + /** + * LongRunning totalPollTimeout. + * @member {google.protobuf.IDuration|null|undefined} totalPollTimeout + * @memberof google.api.MethodSettings.LongRunning + * @instance + */ + LongRunning.prototype.totalPollTimeout = null; + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {Object.} object Plain object + * @returns {google.api.MethodSettings.LongRunning} LongRunning + */ + LongRunning.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.MethodSettings.LongRunning) + return object; + var message = new $root.google.api.MethodSettings.LongRunning(); + if (object.initialPollDelay != null) { + if (typeof object.initialPollDelay !== "object") + throw TypeError(".google.api.MethodSettings.LongRunning.initialPollDelay: object expected"); + message.initialPollDelay = $root.google.protobuf.Duration.fromObject(object.initialPollDelay); + } + if (object.pollDelayMultiplier != null) + message.pollDelayMultiplier = Number(object.pollDelayMultiplier); + if (object.maxPollDelay != null) { + if (typeof object.maxPollDelay !== "object") + throw TypeError(".google.api.MethodSettings.LongRunning.maxPollDelay: object expected"); + message.maxPollDelay = $root.google.protobuf.Duration.fromObject(object.maxPollDelay); + } + if (object.totalPollTimeout != null) { + if (typeof object.totalPollTimeout !== "object") + throw TypeError(".google.api.MethodSettings.LongRunning.totalPollTimeout: object expected"); + message.totalPollTimeout = $root.google.protobuf.Duration.fromObject(object.totalPollTimeout); + } + return message; + }; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {google.api.MethodSettings.LongRunning} message LongRunning + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + LongRunning.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.initialPollDelay = null; + object.pollDelayMultiplier = 0; + object.maxPollDelay = null; + object.totalPollTimeout = null; + } + if (message.initialPollDelay != null && message.hasOwnProperty("initialPollDelay")) + object.initialPollDelay = $root.google.protobuf.Duration.toObject(message.initialPollDelay, options); + if (message.pollDelayMultiplier != null && message.hasOwnProperty("pollDelayMultiplier")) + object.pollDelayMultiplier = options.json && !isFinite(message.pollDelayMultiplier) ? String(message.pollDelayMultiplier) : message.pollDelayMultiplier; + if (message.maxPollDelay != null && message.hasOwnProperty("maxPollDelay")) + object.maxPollDelay = $root.google.protobuf.Duration.toObject(message.maxPollDelay, options); + if (message.totalPollTimeout != null && message.hasOwnProperty("totalPollTimeout")) + object.totalPollTimeout = $root.google.protobuf.Duration.toObject(message.totalPollTimeout, options); + return object; + }; + + /** + * Converts this LongRunning to JSON. + * @function toJSON + * @memberof google.api.MethodSettings.LongRunning + * @instance + * @returns {Object.} JSON object + */ + LongRunning.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for LongRunning + * @function getTypeUrl + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + LongRunning.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.MethodSettings.LongRunning"; + }; + + return LongRunning; + })(); + + return MethodSettings; + })(); + + /** + * ClientLibraryOrganization enum. + * @name google.api.ClientLibraryOrganization + * @enum {string} + * @property {string} CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED=CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED value + * @property {string} CLOUD=CLOUD CLOUD value + * @property {string} ADS=ADS ADS value + * @property {string} PHOTOS=PHOTOS PHOTOS value + * @property {string} STREET_VIEW=STREET_VIEW STREET_VIEW value + * @property {string} SHOPPING=SHOPPING SHOPPING value + * @property {string} GEO=GEO GEO value + * @property {string} GENERATIVE_AI=GENERATIVE_AI GENERATIVE_AI value + */ + api.ClientLibraryOrganization = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"] = "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"; + values[valuesById[1] = "CLOUD"] = "CLOUD"; + values[valuesById[2] = "ADS"] = "ADS"; + values[valuesById[3] = "PHOTOS"] = "PHOTOS"; + values[valuesById[4] = "STREET_VIEW"] = "STREET_VIEW"; + values[valuesById[5] = "SHOPPING"] = "SHOPPING"; + values[valuesById[6] = "GEO"] = "GEO"; + values[valuesById[7] = "GENERATIVE_AI"] = "GENERATIVE_AI"; + return values; + })(); + + /** + * ClientLibraryDestination enum. + * @name google.api.ClientLibraryDestination + * @enum {string} + * @property {string} CLIENT_LIBRARY_DESTINATION_UNSPECIFIED=CLIENT_LIBRARY_DESTINATION_UNSPECIFIED CLIENT_LIBRARY_DESTINATION_UNSPECIFIED value + * @property {string} GITHUB=GITHUB GITHUB value + * @property {string} PACKAGE_MANAGER=PACKAGE_MANAGER PACKAGE_MANAGER value + */ + api.ClientLibraryDestination = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"] = "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"; + values[valuesById[10] = "GITHUB"] = "GITHUB"; + values[valuesById[20] = "PACKAGE_MANAGER"] = "PACKAGE_MANAGER"; + return values; + })(); + + api.SelectiveGapicGeneration = (function() { + + /** + * Properties of a SelectiveGapicGeneration. + * @memberof google.api + * @interface ISelectiveGapicGeneration + * @property {Array.|null} [methods] SelectiveGapicGeneration methods + * @property {boolean|null} [generateOmittedAsInternal] SelectiveGapicGeneration generateOmittedAsInternal + */ + + /** + * Constructs a new SelectiveGapicGeneration. + * @memberof google.api + * @classdesc Represents a SelectiveGapicGeneration. + * @implements ISelectiveGapicGeneration + * @constructor + * @param {google.api.ISelectiveGapicGeneration=} [properties] Properties to set + */ + function SelectiveGapicGeneration(properties) { + this.methods = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SelectiveGapicGeneration methods. + * @member {Array.} methods + * @memberof google.api.SelectiveGapicGeneration + * @instance + */ + SelectiveGapicGeneration.prototype.methods = $util.emptyArray; + + /** + * SelectiveGapicGeneration generateOmittedAsInternal. + * @member {boolean} generateOmittedAsInternal + * @memberof google.api.SelectiveGapicGeneration + * @instance + */ + SelectiveGapicGeneration.prototype.generateOmittedAsInternal = false; + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {Object.} object Plain object + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + */ + SelectiveGapicGeneration.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.SelectiveGapicGeneration) + return object; + var message = new $root.google.api.SelectiveGapicGeneration(); + if (object.methods) { + if (!Array.isArray(object.methods)) + throw TypeError(".google.api.SelectiveGapicGeneration.methods: array expected"); + message.methods = []; + for (var i = 0; i < object.methods.length; ++i) + message.methods[i] = String(object.methods[i]); + } + if (object.generateOmittedAsInternal != null) + message.generateOmittedAsInternal = Boolean(object.generateOmittedAsInternal); + return message; + }; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.SelectiveGapicGeneration} message SelectiveGapicGeneration + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SelectiveGapicGeneration.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.methods = []; + if (options.defaults) + object.generateOmittedAsInternal = false; + if (message.methods && message.methods.length) { + object.methods = []; + for (var j = 0; j < message.methods.length; ++j) + object.methods[j] = message.methods[j]; + } + if (message.generateOmittedAsInternal != null && message.hasOwnProperty("generateOmittedAsInternal")) + object.generateOmittedAsInternal = message.generateOmittedAsInternal; + return object; + }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @function toJSON + * @memberof google.api.SelectiveGapicGeneration + * @instance + * @returns {Object.} JSON object + */ + SelectiveGapicGeneration.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @function getTypeUrl + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SelectiveGapicGeneration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.SelectiveGapicGeneration"; + }; + + return SelectiveGapicGeneration; + })(); + + /** + * LaunchStage enum. + * @name google.api.LaunchStage + * @enum {string} + * @property {string} LAUNCH_STAGE_UNSPECIFIED=LAUNCH_STAGE_UNSPECIFIED LAUNCH_STAGE_UNSPECIFIED value + * @property {string} UNIMPLEMENTED=UNIMPLEMENTED UNIMPLEMENTED value + * @property {string} PRELAUNCH=PRELAUNCH PRELAUNCH value + * @property {string} EARLY_ACCESS=EARLY_ACCESS EARLY_ACCESS value + * @property {string} ALPHA=ALPHA ALPHA value + * @property {string} BETA=BETA BETA value + * @property {string} GA=GA GA value + * @property {string} DEPRECATED=DEPRECATED DEPRECATED value + */ + api.LaunchStage = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = "LAUNCH_STAGE_UNSPECIFIED"; + values[valuesById[6] = "UNIMPLEMENTED"] = "UNIMPLEMENTED"; + values[valuesById[7] = "PRELAUNCH"] = "PRELAUNCH"; + values[valuesById[1] = "EARLY_ACCESS"] = "EARLY_ACCESS"; + values[valuesById[2] = "ALPHA"] = "ALPHA"; + values[valuesById[3] = "BETA"] = "BETA"; + values[valuesById[4] = "GA"] = "GA"; + values[valuesById[5] = "DEPRECATED"] = "DEPRECATED"; + return values; + })(); + + api.RoutingRule = (function() { + + /** + * Properties of a RoutingRule. + * @memberof google.api + * @interface IRoutingRule + * @property {Array.|null} [routingParameters] RoutingRule routingParameters + */ + + /** + * Constructs a new RoutingRule. + * @memberof google.api + * @classdesc Represents a RoutingRule. + * @implements IRoutingRule + * @constructor + * @param {google.api.IRoutingRule=} [properties] Properties to set + */ + function RoutingRule(properties) { + this.routingParameters = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RoutingRule routingParameters. + * @member {Array.} routingParameters + * @memberof google.api.RoutingRule + * @instance + */ + RoutingRule.prototype.routingParameters = $util.emptyArray; + + /** + * Creates a RoutingRule message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.RoutingRule + * @static + * @param {Object.} object Plain object + * @returns {google.api.RoutingRule} RoutingRule + */ + RoutingRule.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RoutingRule) + return object; + var message = new $root.google.api.RoutingRule(); + if (object.routingParameters) { + if (!Array.isArray(object.routingParameters)) + throw TypeError(".google.api.RoutingRule.routingParameters: array expected"); + message.routingParameters = []; + for (var i = 0; i < object.routingParameters.length; ++i) { + if (typeof object.routingParameters[i] !== "object") + throw TypeError(".google.api.RoutingRule.routingParameters: object expected"); + message.routingParameters[i] = $root.google.api.RoutingParameter.fromObject(object.routingParameters[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a RoutingRule message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.RoutingRule + * @static + * @param {google.api.RoutingRule} message RoutingRule + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RoutingRule.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.routingParameters = []; + if (message.routingParameters && message.routingParameters.length) { + object.routingParameters = []; + for (var j = 0; j < message.routingParameters.length; ++j) + object.routingParameters[j] = $root.google.api.RoutingParameter.toObject(message.routingParameters[j], options); + } + return object; + }; + + /** + * Converts this RoutingRule to JSON. + * @function toJSON + * @memberof google.api.RoutingRule + * @instance + * @returns {Object.} JSON object + */ + RoutingRule.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RoutingRule + * @function getTypeUrl + * @memberof google.api.RoutingRule + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RoutingRule.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.RoutingRule"; + }; + + return RoutingRule; + })(); + + api.RoutingParameter = (function() { + + /** + * Properties of a RoutingParameter. + * @memberof google.api + * @interface IRoutingParameter + * @property {string|null} [field] RoutingParameter field + * @property {string|null} [pathTemplate] RoutingParameter pathTemplate + */ + + /** + * Constructs a new RoutingParameter. + * @memberof google.api + * @classdesc Represents a RoutingParameter. + * @implements IRoutingParameter + * @constructor + * @param {google.api.IRoutingParameter=} [properties] Properties to set + */ + function RoutingParameter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RoutingParameter field. + * @member {string} field + * @memberof google.api.RoutingParameter + * @instance + */ + RoutingParameter.prototype.field = ""; + + /** + * RoutingParameter pathTemplate. + * @member {string} pathTemplate + * @memberof google.api.RoutingParameter + * @instance + */ + RoutingParameter.prototype.pathTemplate = ""; + + /** + * Creates a RoutingParameter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.RoutingParameter + * @static + * @param {Object.} object Plain object + * @returns {google.api.RoutingParameter} RoutingParameter + */ + RoutingParameter.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RoutingParameter) + return object; + var message = new $root.google.api.RoutingParameter(); + if (object.field != null) + message.field = String(object.field); + if (object.pathTemplate != null) + message.pathTemplate = String(object.pathTemplate); + return message; + }; + + /** + * Creates a plain object from a RoutingParameter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.RoutingParameter + * @static + * @param {google.api.RoutingParameter} message RoutingParameter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RoutingParameter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.field = ""; + object.pathTemplate = ""; + } + if (message.field != null && message.hasOwnProperty("field")) + object.field = message.field; + if (message.pathTemplate != null && message.hasOwnProperty("pathTemplate")) + object.pathTemplate = message.pathTemplate; + return object; + }; + + /** + * Converts this RoutingParameter to JSON. + * @function toJSON + * @memberof google.api.RoutingParameter + * @instance + * @returns {Object.} JSON object + */ + RoutingParameter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RoutingParameter + * @function getTypeUrl + * @memberof google.api.RoutingParameter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RoutingParameter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.RoutingParameter"; + }; + + return RoutingParameter; + })(); + + return api; + })(); + + google.protobuf = (function() { + + /** + * Namespace protobuf. + * @memberof google + * @namespace + */ + var protobuf = {}; + + protobuf.FileDescriptorSet = (function() { + + /** + * Properties of a FileDescriptorSet. + * @memberof google.protobuf + * @interface IFileDescriptorSet + * @property {Array.|null} [file] FileDescriptorSet file + */ + + /** + * Constructs a new FileDescriptorSet. + * @memberof google.protobuf + * @classdesc Represents a FileDescriptorSet. + * @implements IFileDescriptorSet + * @constructor + * @param {google.protobuf.IFileDescriptorSet=} [properties] Properties to set + */ + function FileDescriptorSet(properties) { + this.file = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FileDescriptorSet file. + * @member {Array.} file + * @memberof google.protobuf.FileDescriptorSet + * @instance + */ + FileDescriptorSet.prototype.file = $util.emptyArray; + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FileDescriptorSet} FileDescriptorSet + */ + FileDescriptorSet.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FileDescriptorSet) + return object; + var message = new $root.google.protobuf.FileDescriptorSet(); + if (object.file) { + if (!Array.isArray(object.file)) + throw TypeError(".google.protobuf.FileDescriptorSet.file: array expected"); + message.file = []; + for (var i = 0; i < object.file.length; ++i) { + if (typeof object.file[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorSet.file: object expected"); + message.file[i] = $root.google.protobuf.FileDescriptorProto.fromObject(object.file[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {google.protobuf.FileDescriptorSet} message FileDescriptorSet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FileDescriptorSet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.file = []; + if (message.file && message.file.length) { + object.file = []; + for (var j = 0; j < message.file.length; ++j) + object.file[j] = $root.google.protobuf.FileDescriptorProto.toObject(message.file[j], options); + } + return object; + }; + + /** + * Converts this FileDescriptorSet to JSON. + * @function toJSON + * @memberof google.protobuf.FileDescriptorSet + * @instance + * @returns {Object.} JSON object + */ + FileDescriptorSet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FileDescriptorSet + * @function getTypeUrl + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FileDescriptorSet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FileDescriptorSet"; + }; + + return FileDescriptorSet; + })(); + + /** + * Edition enum. + * @name google.protobuf.Edition + * @enum {string} + * @property {string} EDITION_UNKNOWN=EDITION_UNKNOWN EDITION_UNKNOWN value + * @property {string} EDITION_PROTO2=EDITION_PROTO2 EDITION_PROTO2 value + * @property {string} EDITION_PROTO3=EDITION_PROTO3 EDITION_PROTO3 value + * @property {string} EDITION_2023=EDITION_2023 EDITION_2023 value + * @property {string} EDITION_2024=EDITION_2024 EDITION_2024 value + * @property {string} EDITION_1_TEST_ONLY=EDITION_1_TEST_ONLY EDITION_1_TEST_ONLY value + * @property {string} EDITION_2_TEST_ONLY=EDITION_2_TEST_ONLY EDITION_2_TEST_ONLY value + * @property {string} EDITION_99997_TEST_ONLY=EDITION_99997_TEST_ONLY EDITION_99997_TEST_ONLY value + * @property {string} EDITION_99998_TEST_ONLY=EDITION_99998_TEST_ONLY EDITION_99998_TEST_ONLY value + * @property {string} EDITION_99999_TEST_ONLY=EDITION_99999_TEST_ONLY EDITION_99999_TEST_ONLY value + * @property {string} EDITION_MAX=EDITION_MAX EDITION_MAX value + */ + protobuf.Edition = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "EDITION_UNKNOWN"] = "EDITION_UNKNOWN"; + values[valuesById[998] = "EDITION_PROTO2"] = "EDITION_PROTO2"; + values[valuesById[999] = "EDITION_PROTO3"] = "EDITION_PROTO3"; + values[valuesById[1000] = "EDITION_2023"] = "EDITION_2023"; + values[valuesById[1001] = "EDITION_2024"] = "EDITION_2024"; + values[valuesById[1] = "EDITION_1_TEST_ONLY"] = "EDITION_1_TEST_ONLY"; + values[valuesById[2] = "EDITION_2_TEST_ONLY"] = "EDITION_2_TEST_ONLY"; + values[valuesById[99997] = "EDITION_99997_TEST_ONLY"] = "EDITION_99997_TEST_ONLY"; + values[valuesById[99998] = "EDITION_99998_TEST_ONLY"] = "EDITION_99998_TEST_ONLY"; + values[valuesById[99999] = "EDITION_99999_TEST_ONLY"] = "EDITION_99999_TEST_ONLY"; + values[valuesById[2147483647] = "EDITION_MAX"] = "EDITION_MAX"; + return values; + })(); + + protobuf.FileDescriptorProto = (function() { + + /** + * Properties of a FileDescriptorProto. + * @memberof google.protobuf + * @interface IFileDescriptorProto + * @property {string|null} [name] FileDescriptorProto name + * @property {string|null} ["package"] FileDescriptorProto package + * @property {Array.|null} [dependency] FileDescriptorProto dependency + * @property {Array.|null} [publicDependency] FileDescriptorProto publicDependency + * @property {Array.|null} [weakDependency] FileDescriptorProto weakDependency + * @property {Array.|null} [messageType] FileDescriptorProto messageType + * @property {Array.|null} [enumType] FileDescriptorProto enumType + * @property {Array.|null} [service] FileDescriptorProto service + * @property {Array.|null} [extension] FileDescriptorProto extension + * @property {google.protobuf.IFileOptions|null} [options] FileDescriptorProto options + * @property {google.protobuf.ISourceCodeInfo|null} [sourceCodeInfo] FileDescriptorProto sourceCodeInfo + * @property {string|null} [syntax] FileDescriptorProto syntax + * @property {google.protobuf.Edition|null} [edition] FileDescriptorProto edition + */ + + /** + * Constructs a new FileDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a FileDescriptorProto. + * @implements IFileDescriptorProto + * @constructor + * @param {google.protobuf.IFileDescriptorProto=} [properties] Properties to set + */ + function FileDescriptorProto(properties) { + this.dependency = []; + this.publicDependency = []; + this.weakDependency = []; + this.messageType = []; + this.enumType = []; + this.service = []; + this.extension = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FileDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.name = ""; + + /** + * FileDescriptorProto package. + * @member {string} package + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype["package"] = ""; + + /** + * FileDescriptorProto dependency. + * @member {Array.} dependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.dependency = $util.emptyArray; + + /** + * FileDescriptorProto publicDependency. + * @member {Array.} publicDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.publicDependency = $util.emptyArray; + + /** + * FileDescriptorProto weakDependency. + * @member {Array.} weakDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.weakDependency = $util.emptyArray; + + /** + * FileDescriptorProto messageType. + * @member {Array.} messageType + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.messageType = $util.emptyArray; + + /** + * FileDescriptorProto enumType. + * @member {Array.} enumType + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.enumType = $util.emptyArray; + + /** + * FileDescriptorProto service. + * @member {Array.} service + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.service = $util.emptyArray; + + /** + * FileDescriptorProto extension. + * @member {Array.} extension + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.extension = $util.emptyArray; + + /** + * FileDescriptorProto options. + * @member {google.protobuf.IFileOptions|null|undefined} options + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.options = null; + + /** + * FileDescriptorProto sourceCodeInfo. + * @member {google.protobuf.ISourceCodeInfo|null|undefined} sourceCodeInfo + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.sourceCodeInfo = null; + + /** + * FileDescriptorProto syntax. + * @member {string} syntax + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.syntax = ""; + + /** + * FileDescriptorProto edition. + * @member {google.protobuf.Edition} edition + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.edition = 0; + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FileDescriptorProto} FileDescriptorProto + */ + FileDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FileDescriptorProto) + return object; + var message = new $root.google.protobuf.FileDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object["package"] != null) + message["package"] = String(object["package"]); + if (object.dependency) { + if (!Array.isArray(object.dependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.dependency: array expected"); + message.dependency = []; + for (var i = 0; i < object.dependency.length; ++i) + message.dependency[i] = String(object.dependency[i]); + } + if (object.publicDependency) { + if (!Array.isArray(object.publicDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.publicDependency: array expected"); + message.publicDependency = []; + for (var i = 0; i < object.publicDependency.length; ++i) + message.publicDependency[i] = object.publicDependency[i] | 0; + } + if (object.weakDependency) { + if (!Array.isArray(object.weakDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.weakDependency: array expected"); + message.weakDependency = []; + for (var i = 0; i < object.weakDependency.length; ++i) + message.weakDependency[i] = object.weakDependency[i] | 0; + } + if (object.messageType) { + if (!Array.isArray(object.messageType)) + throw TypeError(".google.protobuf.FileDescriptorProto.messageType: array expected"); + message.messageType = []; + for (var i = 0; i < object.messageType.length; ++i) { + if (typeof object.messageType[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.messageType: object expected"); + message.messageType[i] = $root.google.protobuf.DescriptorProto.fromObject(object.messageType[i]); + } + } + if (object.enumType) { + if (!Array.isArray(object.enumType)) + throw TypeError(".google.protobuf.FileDescriptorProto.enumType: array expected"); + message.enumType = []; + for (var i = 0; i < object.enumType.length; ++i) { + if (typeof object.enumType[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.enumType: object expected"); + message.enumType[i] = $root.google.protobuf.EnumDescriptorProto.fromObject(object.enumType[i]); + } + } + if (object.service) { + if (!Array.isArray(object.service)) + throw TypeError(".google.protobuf.FileDescriptorProto.service: array expected"); + message.service = []; + for (var i = 0; i < object.service.length; ++i) { + if (typeof object.service[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.service: object expected"); + message.service[i] = $root.google.protobuf.ServiceDescriptorProto.fromObject(object.service[i]); + } + } + if (object.extension) { + if (!Array.isArray(object.extension)) + throw TypeError(".google.protobuf.FileDescriptorProto.extension: array expected"); + message.extension = []; + for (var i = 0; i < object.extension.length; ++i) { + if (typeof object.extension[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.extension: object expected"); + message.extension[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.extension[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.FileOptions.fromObject(object.options); + } + if (object.sourceCodeInfo != null) { + if (typeof object.sourceCodeInfo !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.sourceCodeInfo: object expected"); + message.sourceCodeInfo = $root.google.protobuf.SourceCodeInfo.fromObject(object.sourceCodeInfo); + } + if (object.syntax != null) + message.syntax = String(object.syntax); + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.edition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.edition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.edition = 999; + break; + case "EDITION_2023": + case 1000: + message.edition = 1000; + break; + case "EDITION_2024": + case 1001: + message.edition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.edition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.edition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.edition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.edition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.edition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.edition = 2147483647; + break; + } + return message; + }; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {google.protobuf.FileDescriptorProto} message FileDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FileDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.dependency = []; + object.messageType = []; + object.enumType = []; + object.service = []; + object.extension = []; + object.publicDependency = []; + object.weakDependency = []; + } + if (options.defaults) { + object.name = ""; + object["package"] = ""; + object.options = null; + object.sourceCodeInfo = null; + object.syntax = ""; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message["package"] != null && message.hasOwnProperty("package")) + object["package"] = message["package"]; + if (message.dependency && message.dependency.length) { + object.dependency = []; + for (var j = 0; j < message.dependency.length; ++j) + object.dependency[j] = message.dependency[j]; + } + if (message.messageType && message.messageType.length) { + object.messageType = []; + for (var j = 0; j < message.messageType.length; ++j) + object.messageType[j] = $root.google.protobuf.DescriptorProto.toObject(message.messageType[j], options); + } + if (message.enumType && message.enumType.length) { + object.enumType = []; + for (var j = 0; j < message.enumType.length; ++j) + object.enumType[j] = $root.google.protobuf.EnumDescriptorProto.toObject(message.enumType[j], options); + } + if (message.service && message.service.length) { + object.service = []; + for (var j = 0; j < message.service.length; ++j) + object.service[j] = $root.google.protobuf.ServiceDescriptorProto.toObject(message.service[j], options); + } + if (message.extension && message.extension.length) { + object.extension = []; + for (var j = 0; j < message.extension.length; ++j) + object.extension[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.extension[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.FileOptions.toObject(message.options, options); + if (message.sourceCodeInfo != null && message.hasOwnProperty("sourceCodeInfo")) + object.sourceCodeInfo = $root.google.protobuf.SourceCodeInfo.toObject(message.sourceCodeInfo, options); + if (message.publicDependency && message.publicDependency.length) { + object.publicDependency = []; + for (var j = 0; j < message.publicDependency.length; ++j) + object.publicDependency[j] = message.publicDependency[j]; + } + if (message.weakDependency && message.weakDependency.length) { + object.weakDependency = []; + for (var j = 0; j < message.weakDependency.length; ++j) + object.weakDependency[j] = message.weakDependency[j]; + } + if (message.syntax != null && message.hasOwnProperty("syntax")) + object.syntax = message.syntax; + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; + return object; + }; + + /** + * Converts this FileDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.FileDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + FileDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FileDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FileDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FileDescriptorProto"; + }; + + return FileDescriptorProto; + })(); + + protobuf.DescriptorProto = (function() { + + /** + * Properties of a DescriptorProto. + * @memberof google.protobuf + * @interface IDescriptorProto + * @property {string|null} [name] DescriptorProto name + * @property {Array.|null} [field] DescriptorProto field + * @property {Array.|null} [extension] DescriptorProto extension + * @property {Array.|null} [nestedType] DescriptorProto nestedType + * @property {Array.|null} [enumType] DescriptorProto enumType + * @property {Array.|null} [extensionRange] DescriptorProto extensionRange + * @property {Array.|null} [oneofDecl] DescriptorProto oneofDecl + * @property {google.protobuf.IMessageOptions|null} [options] DescriptorProto options + * @property {Array.|null} [reservedRange] DescriptorProto reservedRange + * @property {Array.|null} [reservedName] DescriptorProto reservedName + */ + + /** + * Constructs a new DescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a DescriptorProto. + * @implements IDescriptorProto + * @constructor + * @param {google.protobuf.IDescriptorProto=} [properties] Properties to set + */ + function DescriptorProto(properties) { + this.field = []; + this.extension = []; + this.nestedType = []; + this.enumType = []; + this.extensionRange = []; + this.oneofDecl = []; + this.reservedRange = []; + this.reservedName = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DescriptorProto name. + * @member {string} name + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.name = ""; + + /** + * DescriptorProto field. + * @member {Array.} field + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.field = $util.emptyArray; + + /** + * DescriptorProto extension. + * @member {Array.} extension + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.extension = $util.emptyArray; + + /** + * DescriptorProto nestedType. + * @member {Array.} nestedType + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.nestedType = $util.emptyArray; + + /** + * DescriptorProto enumType. + * @member {Array.} enumType + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.enumType = $util.emptyArray; + + /** + * DescriptorProto extensionRange. + * @member {Array.} extensionRange + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.extensionRange = $util.emptyArray; + + /** + * DescriptorProto oneofDecl. + * @member {Array.} oneofDecl + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.oneofDecl = $util.emptyArray; + + /** + * DescriptorProto options. + * @member {google.protobuf.IMessageOptions|null|undefined} options + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.options = null; + + /** + * DescriptorProto reservedRange. + * @member {Array.} reservedRange + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.reservedRange = $util.emptyArray; + + /** + * DescriptorProto reservedName. + * @member {Array.} reservedName + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.reservedName = $util.emptyArray; + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DescriptorProto} DescriptorProto + */ + DescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DescriptorProto) + return object; + var message = new $root.google.protobuf.DescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.field) { + if (!Array.isArray(object.field)) + throw TypeError(".google.protobuf.DescriptorProto.field: array expected"); + message.field = []; + for (var i = 0; i < object.field.length; ++i) { + if (typeof object.field[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.field: object expected"); + message.field[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.field[i]); + } + } + if (object.extension) { + if (!Array.isArray(object.extension)) + throw TypeError(".google.protobuf.DescriptorProto.extension: array expected"); + message.extension = []; + for (var i = 0; i < object.extension.length; ++i) { + if (typeof object.extension[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.extension: object expected"); + message.extension[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.extension[i]); + } + } + if (object.nestedType) { + if (!Array.isArray(object.nestedType)) + throw TypeError(".google.protobuf.DescriptorProto.nestedType: array expected"); + message.nestedType = []; + for (var i = 0; i < object.nestedType.length; ++i) { + if (typeof object.nestedType[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.nestedType: object expected"); + message.nestedType[i] = $root.google.protobuf.DescriptorProto.fromObject(object.nestedType[i]); + } + } + if (object.enumType) { + if (!Array.isArray(object.enumType)) + throw TypeError(".google.protobuf.DescriptorProto.enumType: array expected"); + message.enumType = []; + for (var i = 0; i < object.enumType.length; ++i) { + if (typeof object.enumType[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.enumType: object expected"); + message.enumType[i] = $root.google.protobuf.EnumDescriptorProto.fromObject(object.enumType[i]); + } + } + if (object.extensionRange) { + if (!Array.isArray(object.extensionRange)) + throw TypeError(".google.protobuf.DescriptorProto.extensionRange: array expected"); + message.extensionRange = []; + for (var i = 0; i < object.extensionRange.length; ++i) { + if (typeof object.extensionRange[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.extensionRange: object expected"); + message.extensionRange[i] = $root.google.protobuf.DescriptorProto.ExtensionRange.fromObject(object.extensionRange[i]); + } + } + if (object.oneofDecl) { + if (!Array.isArray(object.oneofDecl)) + throw TypeError(".google.protobuf.DescriptorProto.oneofDecl: array expected"); + message.oneofDecl = []; + for (var i = 0; i < object.oneofDecl.length; ++i) { + if (typeof object.oneofDecl[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.oneofDecl: object expected"); + message.oneofDecl[i] = $root.google.protobuf.OneofDescriptorProto.fromObject(object.oneofDecl[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.DescriptorProto.options: object expected"); + message.options = $root.google.protobuf.MessageOptions.fromObject(object.options); + } + if (object.reservedRange) { + if (!Array.isArray(object.reservedRange)) + throw TypeError(".google.protobuf.DescriptorProto.reservedRange: array expected"); + message.reservedRange = []; + for (var i = 0; i < object.reservedRange.length; ++i) { + if (typeof object.reservedRange[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.reservedRange: object expected"); + message.reservedRange[i] = $root.google.protobuf.DescriptorProto.ReservedRange.fromObject(object.reservedRange[i]); + } + } + if (object.reservedName) { + if (!Array.isArray(object.reservedName)) + throw TypeError(".google.protobuf.DescriptorProto.reservedName: array expected"); + message.reservedName = []; + for (var i = 0; i < object.reservedName.length; ++i) + message.reservedName[i] = String(object.reservedName[i]); + } + return message; + }; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.DescriptorProto + * @static + * @param {google.protobuf.DescriptorProto} message DescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.field = []; + object.nestedType = []; + object.enumType = []; + object.extensionRange = []; + object.extension = []; + object.oneofDecl = []; + object.reservedRange = []; + object.reservedName = []; + } + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.field && message.field.length) { + object.field = []; + for (var j = 0; j < message.field.length; ++j) + object.field[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.field[j], options); + } + if (message.nestedType && message.nestedType.length) { + object.nestedType = []; + for (var j = 0; j < message.nestedType.length; ++j) + object.nestedType[j] = $root.google.protobuf.DescriptorProto.toObject(message.nestedType[j], options); + } + if (message.enumType && message.enumType.length) { + object.enumType = []; + for (var j = 0; j < message.enumType.length; ++j) + object.enumType[j] = $root.google.protobuf.EnumDescriptorProto.toObject(message.enumType[j], options); + } + if (message.extensionRange && message.extensionRange.length) { + object.extensionRange = []; + for (var j = 0; j < message.extensionRange.length; ++j) + object.extensionRange[j] = $root.google.protobuf.DescriptorProto.ExtensionRange.toObject(message.extensionRange[j], options); + } + if (message.extension && message.extension.length) { + object.extension = []; + for (var j = 0; j < message.extension.length; ++j) + object.extension[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.extension[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.MessageOptions.toObject(message.options, options); + if (message.oneofDecl && message.oneofDecl.length) { + object.oneofDecl = []; + for (var j = 0; j < message.oneofDecl.length; ++j) + object.oneofDecl[j] = $root.google.protobuf.OneofDescriptorProto.toObject(message.oneofDecl[j], options); + } + if (message.reservedRange && message.reservedRange.length) { + object.reservedRange = []; + for (var j = 0; j < message.reservedRange.length; ++j) + object.reservedRange[j] = $root.google.protobuf.DescriptorProto.ReservedRange.toObject(message.reservedRange[j], options); + } + if (message.reservedName && message.reservedName.length) { + object.reservedName = []; + for (var j = 0; j < message.reservedName.length; ++j) + object.reservedName[j] = message.reservedName[j]; + } + return object; + }; + + /** + * Converts this DescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.DescriptorProto + * @instance + * @returns {Object.} JSON object + */ + DescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.DescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.DescriptorProto"; + }; + + DescriptorProto.ExtensionRange = (function() { + + /** + * Properties of an ExtensionRange. + * @memberof google.protobuf.DescriptorProto + * @interface IExtensionRange + * @property {number|null} [start] ExtensionRange start + * @property {number|null} [end] ExtensionRange end + * @property {google.protobuf.IExtensionRangeOptions|null} [options] ExtensionRange options + */ + + /** + * Constructs a new ExtensionRange. + * @memberof google.protobuf.DescriptorProto + * @classdesc Represents an ExtensionRange. + * @implements IExtensionRange + * @constructor + * @param {google.protobuf.DescriptorProto.IExtensionRange=} [properties] Properties to set + */ + function ExtensionRange(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExtensionRange start. + * @member {number} start + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @instance + */ + ExtensionRange.prototype.start = 0; + + /** + * ExtensionRange end. + * @member {number} end + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @instance + */ + ExtensionRange.prototype.end = 0; + + /** + * ExtensionRange options. + * @member {google.protobuf.IExtensionRangeOptions|null|undefined} options + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @instance + */ + ExtensionRange.prototype.options = null; + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DescriptorProto.ExtensionRange} ExtensionRange + */ + ExtensionRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DescriptorProto.ExtensionRange) + return object; + var message = new $root.google.protobuf.DescriptorProto.ExtensionRange(); + if (object.start != null) + message.start = object.start | 0; + if (object.end != null) + message.end = object.end | 0; + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.DescriptorProto.ExtensionRange.options: object expected"); + message.options = $root.google.protobuf.ExtensionRangeOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {google.protobuf.DescriptorProto.ExtensionRange} message ExtensionRange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExtensionRange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.start = 0; + object.end = 0; + object.options = null; + } + if (message.start != null && message.hasOwnProperty("start")) + object.start = message.start; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.ExtensionRangeOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this ExtensionRange to JSON. + * @function toJSON + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @instance + * @returns {Object.} JSON object + */ + ExtensionRange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExtensionRange + * @function getTypeUrl + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExtensionRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.DescriptorProto.ExtensionRange"; + }; + + return ExtensionRange; + })(); + + DescriptorProto.ReservedRange = (function() { + + /** + * Properties of a ReservedRange. + * @memberof google.protobuf.DescriptorProto + * @interface IReservedRange + * @property {number|null} [start] ReservedRange start + * @property {number|null} [end] ReservedRange end + */ + + /** + * Constructs a new ReservedRange. + * @memberof google.protobuf.DescriptorProto + * @classdesc Represents a ReservedRange. + * @implements IReservedRange + * @constructor + * @param {google.protobuf.DescriptorProto.IReservedRange=} [properties] Properties to set + */ + function ReservedRange(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReservedRange start. + * @member {number} start + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @instance + */ + ReservedRange.prototype.start = 0; + + /** + * ReservedRange end. + * @member {number} end + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @instance + */ + ReservedRange.prototype.end = 0; + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DescriptorProto.ReservedRange} ReservedRange + */ + ReservedRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DescriptorProto.ReservedRange) + return object; + var message = new $root.google.protobuf.DescriptorProto.ReservedRange(); + if (object.start != null) + message.start = object.start | 0; + if (object.end != null) + message.end = object.end | 0; + return message; + }; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {google.protobuf.DescriptorProto.ReservedRange} message ReservedRange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReservedRange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.start = 0; + object.end = 0; + } + if (message.start != null && message.hasOwnProperty("start")) + object.start = message.start; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + return object; + }; + + /** + * Converts this ReservedRange to JSON. + * @function toJSON + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @instance + * @returns {Object.} JSON object + */ + ReservedRange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReservedRange + * @function getTypeUrl + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReservedRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.DescriptorProto.ReservedRange"; + }; + + return ReservedRange; + })(); + + return DescriptorProto; + })(); + + protobuf.ExtensionRangeOptions = (function() { + + /** + * Properties of an ExtensionRangeOptions. + * @memberof google.protobuf + * @interface IExtensionRangeOptions + * @property {Array.|null} [uninterpretedOption] ExtensionRangeOptions uninterpretedOption + * @property {Array.|null} [declaration] ExtensionRangeOptions declaration + * @property {google.protobuf.IFeatureSet|null} [features] ExtensionRangeOptions features + * @property {google.protobuf.ExtensionRangeOptions.VerificationState|null} [verification] ExtensionRangeOptions verification + */ + + /** + * Constructs a new ExtensionRangeOptions. + * @memberof google.protobuf + * @classdesc Represents an ExtensionRangeOptions. + * @implements IExtensionRangeOptions + * @constructor + * @param {google.protobuf.IExtensionRangeOptions=} [properties] Properties to set + */ + function ExtensionRangeOptions(properties) { + this.uninterpretedOption = []; + this.declaration = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExtensionRangeOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * ExtensionRangeOptions declaration. + * @member {Array.} declaration + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.declaration = $util.emptyArray; + + /** + * ExtensionRangeOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.features = null; + + /** + * ExtensionRangeOptions verification. + * @member {google.protobuf.ExtensionRangeOptions.VerificationState} verification + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.verification = 1; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ExtensionRangeOptions} ExtensionRangeOptions + */ + ExtensionRangeOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ExtensionRangeOptions) + return object; + var message = new $root.google.protobuf.ExtensionRangeOptions(); + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.ExtensionRangeOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.ExtensionRangeOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object.declaration) { + if (!Array.isArray(object.declaration)) + throw TypeError(".google.protobuf.ExtensionRangeOptions.declaration: array expected"); + message.declaration = []; + for (var i = 0; i < object.declaration.length; ++i) { + if (typeof object.declaration[i] !== "object") + throw TypeError(".google.protobuf.ExtensionRangeOptions.declaration: object expected"); + message.declaration[i] = $root.google.protobuf.ExtensionRangeOptions.Declaration.fromObject(object.declaration[i]); + } + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.ExtensionRangeOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + switch (object.verification) { + case "DECLARATION": + case 0: + message.verification = 0; + break; + default: + if (typeof object.verification === "number") { + message.verification = object.verification; + break; + } + break; + case "UNVERIFIED": + case 1: + message.verification = 1; + break; + } + return message; + }; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {google.protobuf.ExtensionRangeOptions} message ExtensionRangeOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExtensionRangeOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.declaration = []; + object.uninterpretedOption = []; + } + if (options.defaults) { + object.verification = options.enums === String ? "UNVERIFIED" : 1; + object.features = null; + } + if (message.declaration && message.declaration.length) { + object.declaration = []; + for (var j = 0; j < message.declaration.length; ++j) + object.declaration[j] = $root.google.protobuf.ExtensionRangeOptions.Declaration.toObject(message.declaration[j], options); + } + if (message.verification != null && message.hasOwnProperty("verification")) + object.verification = options.enums === String ? $root.google.protobuf.ExtensionRangeOptions.VerificationState[message.verification] === undefined ? message.verification : $root.google.protobuf.ExtensionRangeOptions.VerificationState[message.verification] : message.verification; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @function toJSON + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + * @returns {Object.} JSON object + */ + ExtensionRangeOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @function getTypeUrl + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExtensionRangeOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ExtensionRangeOptions"; + }; + + ExtensionRangeOptions.Declaration = (function() { + + /** + * Properties of a Declaration. + * @memberof google.protobuf.ExtensionRangeOptions + * @interface IDeclaration + * @property {number|null} [number] Declaration number + * @property {string|null} [fullName] Declaration fullName + * @property {string|null} [type] Declaration type + * @property {boolean|null} [reserved] Declaration reserved + * @property {boolean|null} [repeated] Declaration repeated + */ + + /** + * Constructs a new Declaration. + * @memberof google.protobuf.ExtensionRangeOptions + * @classdesc Represents a Declaration. + * @implements IDeclaration + * @constructor + * @param {google.protobuf.ExtensionRangeOptions.IDeclaration=} [properties] Properties to set + */ + function Declaration(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Declaration number. + * @member {number} number + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.number = 0; + + /** + * Declaration fullName. + * @member {string} fullName + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.fullName = ""; + + /** + * Declaration type. + * @member {string} type + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.type = ""; + + /** + * Declaration reserved. + * @member {boolean} reserved + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.reserved = false; + + /** + * Declaration repeated. + * @member {boolean} repeated + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.repeated = false; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ExtensionRangeOptions.Declaration} Declaration + */ + Declaration.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ExtensionRangeOptions.Declaration) + return object; + var message = new $root.google.protobuf.ExtensionRangeOptions.Declaration(); + if (object.number != null) + message.number = object.number | 0; + if (object.fullName != null) + message.fullName = String(object.fullName); + if (object.type != null) + message.type = String(object.type); + if (object.reserved != null) + message.reserved = Boolean(object.reserved); + if (object.repeated != null) + message.repeated = Boolean(object.repeated); + return message; + }; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {google.protobuf.ExtensionRangeOptions.Declaration} message Declaration + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Declaration.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.number = 0; + object.fullName = ""; + object.type = ""; + object.reserved = false; + object.repeated = false; + } + if (message.number != null && message.hasOwnProperty("number")) + object.number = message.number; + if (message.fullName != null && message.hasOwnProperty("fullName")) + object.fullName = message.fullName; + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.reserved != null && message.hasOwnProperty("reserved")) + object.reserved = message.reserved; + if (message.repeated != null && message.hasOwnProperty("repeated")) + object.repeated = message.repeated; + return object; + }; + + /** + * Converts this Declaration to JSON. + * @function toJSON + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + * @returns {Object.} JSON object + */ + Declaration.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Declaration + * @function getTypeUrl + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Declaration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ExtensionRangeOptions.Declaration"; + }; + + return Declaration; + })(); + + /** + * VerificationState enum. + * @name google.protobuf.ExtensionRangeOptions.VerificationState + * @enum {string} + * @property {string} DECLARATION=DECLARATION DECLARATION value + * @property {string} UNVERIFIED=UNVERIFIED UNVERIFIED value + */ + ExtensionRangeOptions.VerificationState = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DECLARATION"] = "DECLARATION"; + values[valuesById[1] = "UNVERIFIED"] = "UNVERIFIED"; + return values; + })(); + + return ExtensionRangeOptions; + })(); + + protobuf.FieldDescriptorProto = (function() { + + /** + * Properties of a FieldDescriptorProto. + * @memberof google.protobuf + * @interface IFieldDescriptorProto + * @property {string|null} [name] FieldDescriptorProto name + * @property {number|null} [number] FieldDescriptorProto number + * @property {google.protobuf.FieldDescriptorProto.Label|null} [label] FieldDescriptorProto label + * @property {google.protobuf.FieldDescriptorProto.Type|null} [type] FieldDescriptorProto type + * @property {string|null} [typeName] FieldDescriptorProto typeName + * @property {string|null} [extendee] FieldDescriptorProto extendee + * @property {string|null} [defaultValue] FieldDescriptorProto defaultValue + * @property {number|null} [oneofIndex] FieldDescriptorProto oneofIndex + * @property {string|null} [jsonName] FieldDescriptorProto jsonName + * @property {google.protobuf.IFieldOptions|null} [options] FieldDescriptorProto options + * @property {boolean|null} [proto3Optional] FieldDescriptorProto proto3Optional + */ + + /** + * Constructs a new FieldDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a FieldDescriptorProto. + * @implements IFieldDescriptorProto + * @constructor + * @param {google.protobuf.IFieldDescriptorProto=} [properties] Properties to set + */ + function FieldDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.name = ""; + + /** + * FieldDescriptorProto number. + * @member {number} number + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.number = 0; + + /** + * FieldDescriptorProto label. + * @member {google.protobuf.FieldDescriptorProto.Label} label + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.label = 1; + + /** + * FieldDescriptorProto type. + * @member {google.protobuf.FieldDescriptorProto.Type} type + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.type = 1; + + /** + * FieldDescriptorProto typeName. + * @member {string} typeName + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.typeName = ""; + + /** + * FieldDescriptorProto extendee. + * @member {string} extendee + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.extendee = ""; + + /** + * FieldDescriptorProto defaultValue. + * @member {string} defaultValue + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.defaultValue = ""; + + /** + * FieldDescriptorProto oneofIndex. + * @member {number} oneofIndex + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.oneofIndex = 0; + + /** + * FieldDescriptorProto jsonName. + * @member {string} jsonName + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.jsonName = ""; + + /** + * FieldDescriptorProto options. + * @member {google.protobuf.IFieldOptions|null|undefined} options + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.options = null; + + /** + * FieldDescriptorProto proto3Optional. + * @member {boolean} proto3Optional + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.proto3Optional = false; + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldDescriptorProto} FieldDescriptorProto + */ + FieldDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldDescriptorProto) + return object; + var message = new $root.google.protobuf.FieldDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.number != null) + message.number = object.number | 0; + switch (object.label) { + default: + if (typeof object.label === "number") { + message.label = object.label; + break; + } + break; + case "LABEL_OPTIONAL": + case 1: + message.label = 1; + break; + case "LABEL_REPEATED": + case 3: + message.label = 3; + break; + case "LABEL_REQUIRED": + case 2: + message.label = 2; + break; + } + switch (object.type) { + default: + if (typeof object.type === "number") { + message.type = object.type; + break; + } + break; + case "TYPE_DOUBLE": + case 1: + message.type = 1; + break; + case "TYPE_FLOAT": + case 2: + message.type = 2; + break; + case "TYPE_INT64": + case 3: + message.type = 3; + break; + case "TYPE_UINT64": + case 4: + message.type = 4; + break; + case "TYPE_INT32": + case 5: + message.type = 5; + break; + case "TYPE_FIXED64": + case 6: + message.type = 6; + break; + case "TYPE_FIXED32": + case 7: + message.type = 7; + break; + case "TYPE_BOOL": + case 8: + message.type = 8; + break; + case "TYPE_STRING": + case 9: + message.type = 9; + break; + case "TYPE_GROUP": + case 10: + message.type = 10; + break; + case "TYPE_MESSAGE": + case 11: + message.type = 11; + break; + case "TYPE_BYTES": + case 12: + message.type = 12; + break; + case "TYPE_UINT32": + case 13: + message.type = 13; + break; + case "TYPE_ENUM": + case 14: + message.type = 14; + break; + case "TYPE_SFIXED32": + case 15: + message.type = 15; + break; + case "TYPE_SFIXED64": + case 16: + message.type = 16; + break; + case "TYPE_SINT32": + case 17: + message.type = 17; + break; + case "TYPE_SINT64": + case 18: + message.type = 18; + break; + } + if (object.typeName != null) + message.typeName = String(object.typeName); + if (object.extendee != null) + message.extendee = String(object.extendee); + if (object.defaultValue != null) + message.defaultValue = String(object.defaultValue); + if (object.oneofIndex != null) + message.oneofIndex = object.oneofIndex | 0; + if (object.jsonName != null) + message.jsonName = String(object.jsonName); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.FieldDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.FieldOptions.fromObject(object.options); + } + if (object.proto3Optional != null) + message.proto3Optional = Boolean(object.proto3Optional); + return message; + }; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {google.protobuf.FieldDescriptorProto} message FieldDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.extendee = ""; + object.number = 0; + object.label = options.enums === String ? "LABEL_OPTIONAL" : 1; + object.type = options.enums === String ? "TYPE_DOUBLE" : 1; + object.typeName = ""; + object.defaultValue = ""; + object.options = null; + object.oneofIndex = 0; + object.jsonName = ""; + object.proto3Optional = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.extendee != null && message.hasOwnProperty("extendee")) + object.extendee = message.extendee; + if (message.number != null && message.hasOwnProperty("number")) + object.number = message.number; + if (message.label != null && message.hasOwnProperty("label")) + object.label = options.enums === String ? $root.google.protobuf.FieldDescriptorProto.Label[message.label] === undefined ? message.label : $root.google.protobuf.FieldDescriptorProto.Label[message.label] : message.label; + if (message.type != null && message.hasOwnProperty("type")) + object.type = options.enums === String ? $root.google.protobuf.FieldDescriptorProto.Type[message.type] === undefined ? message.type : $root.google.protobuf.FieldDescriptorProto.Type[message.type] : message.type; + if (message.typeName != null && message.hasOwnProperty("typeName")) + object.typeName = message.typeName; + if (message.defaultValue != null && message.hasOwnProperty("defaultValue")) + object.defaultValue = message.defaultValue; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.FieldOptions.toObject(message.options, options); + if (message.oneofIndex != null && message.hasOwnProperty("oneofIndex")) + object.oneofIndex = message.oneofIndex; + if (message.jsonName != null && message.hasOwnProperty("jsonName")) + object.jsonName = message.jsonName; + if (message.proto3Optional != null && message.hasOwnProperty("proto3Optional")) + object.proto3Optional = message.proto3Optional; + return object; + }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.FieldDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + FieldDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldDescriptorProto"; + }; + + /** + * Type enum. + * @name google.protobuf.FieldDescriptorProto.Type + * @enum {string} + * @property {string} TYPE_DOUBLE=TYPE_DOUBLE TYPE_DOUBLE value + * @property {string} TYPE_FLOAT=TYPE_FLOAT TYPE_FLOAT value + * @property {string} TYPE_INT64=TYPE_INT64 TYPE_INT64 value + * @property {string} TYPE_UINT64=TYPE_UINT64 TYPE_UINT64 value + * @property {string} TYPE_INT32=TYPE_INT32 TYPE_INT32 value + * @property {string} TYPE_FIXED64=TYPE_FIXED64 TYPE_FIXED64 value + * @property {string} TYPE_FIXED32=TYPE_FIXED32 TYPE_FIXED32 value + * @property {string} TYPE_BOOL=TYPE_BOOL TYPE_BOOL value + * @property {string} TYPE_STRING=TYPE_STRING TYPE_STRING value + * @property {string} TYPE_GROUP=TYPE_GROUP TYPE_GROUP value + * @property {string} TYPE_MESSAGE=TYPE_MESSAGE TYPE_MESSAGE value + * @property {string} TYPE_BYTES=TYPE_BYTES TYPE_BYTES value + * @property {string} TYPE_UINT32=TYPE_UINT32 TYPE_UINT32 value + * @property {string} TYPE_ENUM=TYPE_ENUM TYPE_ENUM value + * @property {string} TYPE_SFIXED32=TYPE_SFIXED32 TYPE_SFIXED32 value + * @property {string} TYPE_SFIXED64=TYPE_SFIXED64 TYPE_SFIXED64 value + * @property {string} TYPE_SINT32=TYPE_SINT32 TYPE_SINT32 value + * @property {string} TYPE_SINT64=TYPE_SINT64 TYPE_SINT64 value + */ + FieldDescriptorProto.Type = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[1] = "TYPE_DOUBLE"] = "TYPE_DOUBLE"; + values[valuesById[2] = "TYPE_FLOAT"] = "TYPE_FLOAT"; + values[valuesById[3] = "TYPE_INT64"] = "TYPE_INT64"; + values[valuesById[4] = "TYPE_UINT64"] = "TYPE_UINT64"; + values[valuesById[5] = "TYPE_INT32"] = "TYPE_INT32"; + values[valuesById[6] = "TYPE_FIXED64"] = "TYPE_FIXED64"; + values[valuesById[7] = "TYPE_FIXED32"] = "TYPE_FIXED32"; + values[valuesById[8] = "TYPE_BOOL"] = "TYPE_BOOL"; + values[valuesById[9] = "TYPE_STRING"] = "TYPE_STRING"; + values[valuesById[10] = "TYPE_GROUP"] = "TYPE_GROUP"; + values[valuesById[11] = "TYPE_MESSAGE"] = "TYPE_MESSAGE"; + values[valuesById[12] = "TYPE_BYTES"] = "TYPE_BYTES"; + values[valuesById[13] = "TYPE_UINT32"] = "TYPE_UINT32"; + values[valuesById[14] = "TYPE_ENUM"] = "TYPE_ENUM"; + values[valuesById[15] = "TYPE_SFIXED32"] = "TYPE_SFIXED32"; + values[valuesById[16] = "TYPE_SFIXED64"] = "TYPE_SFIXED64"; + values[valuesById[17] = "TYPE_SINT32"] = "TYPE_SINT32"; + values[valuesById[18] = "TYPE_SINT64"] = "TYPE_SINT64"; + return values; + })(); + + /** + * Label enum. + * @name google.protobuf.FieldDescriptorProto.Label + * @enum {string} + * @property {string} LABEL_OPTIONAL=LABEL_OPTIONAL LABEL_OPTIONAL value + * @property {string} LABEL_REPEATED=LABEL_REPEATED LABEL_REPEATED value + * @property {string} LABEL_REQUIRED=LABEL_REQUIRED LABEL_REQUIRED value + */ + FieldDescriptorProto.Label = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[1] = "LABEL_OPTIONAL"] = "LABEL_OPTIONAL"; + values[valuesById[3] = "LABEL_REPEATED"] = "LABEL_REPEATED"; + values[valuesById[2] = "LABEL_REQUIRED"] = "LABEL_REQUIRED"; + return values; + })(); + + return FieldDescriptorProto; + })(); + + protobuf.OneofDescriptorProto = (function() { + + /** + * Properties of an OneofDescriptorProto. + * @memberof google.protobuf + * @interface IOneofDescriptorProto + * @property {string|null} [name] OneofDescriptorProto name + * @property {google.protobuf.IOneofOptions|null} [options] OneofDescriptorProto options + */ + + /** + * Constructs a new OneofDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents an OneofDescriptorProto. + * @implements IOneofDescriptorProto + * @constructor + * @param {google.protobuf.IOneofDescriptorProto=} [properties] Properties to set + */ + function OneofDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OneofDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.OneofDescriptorProto + * @instance + */ + OneofDescriptorProto.prototype.name = ""; + + /** + * OneofDescriptorProto options. + * @member {google.protobuf.IOneofOptions|null|undefined} options + * @memberof google.protobuf.OneofDescriptorProto + * @instance + */ + OneofDescriptorProto.prototype.options = null; + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.OneofDescriptorProto} OneofDescriptorProto + */ + OneofDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.OneofDescriptorProto) + return object; + var message = new $root.google.protobuf.OneofDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.OneofDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.OneofOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {google.protobuf.OneofDescriptorProto} message OneofDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OneofDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.OneofOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.OneofDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + OneofDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OneofDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OneofDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.OneofDescriptorProto"; + }; + + return OneofDescriptorProto; + })(); + + protobuf.EnumDescriptorProto = (function() { + + /** + * Properties of an EnumDescriptorProto. + * @memberof google.protobuf + * @interface IEnumDescriptorProto + * @property {string|null} [name] EnumDescriptorProto name + * @property {Array.|null} [value] EnumDescriptorProto value + * @property {google.protobuf.IEnumOptions|null} [options] EnumDescriptorProto options + * @property {Array.|null} [reservedRange] EnumDescriptorProto reservedRange + * @property {Array.|null} [reservedName] EnumDescriptorProto reservedName + */ + + /** + * Constructs a new EnumDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents an EnumDescriptorProto. + * @implements IEnumDescriptorProto + * @constructor + * @param {google.protobuf.IEnumDescriptorProto=} [properties] Properties to set + */ + function EnumDescriptorProto(properties) { + this.value = []; + this.reservedRange = []; + this.reservedName = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.name = ""; + + /** + * EnumDescriptorProto value. + * @member {Array.} value + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.value = $util.emptyArray; + + /** + * EnumDescriptorProto options. + * @member {google.protobuf.IEnumOptions|null|undefined} options + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.options = null; + + /** + * EnumDescriptorProto reservedRange. + * @member {Array.} reservedRange + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.reservedRange = $util.emptyArray; + + /** + * EnumDescriptorProto reservedName. + * @member {Array.} reservedName + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.reservedName = $util.emptyArray; + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumDescriptorProto} EnumDescriptorProto + */ + EnumDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumDescriptorProto) + return object; + var message = new $root.google.protobuf.EnumDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.value) { + if (!Array.isArray(object.value)) + throw TypeError(".google.protobuf.EnumDescriptorProto.value: array expected"); + message.value = []; + for (var i = 0; i < object.value.length; ++i) { + if (typeof object.value[i] !== "object") + throw TypeError(".google.protobuf.EnumDescriptorProto.value: object expected"); + message.value[i] = $root.google.protobuf.EnumValueDescriptorProto.fromObject(object.value[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.EnumDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.EnumOptions.fromObject(object.options); + } + if (object.reservedRange) { + if (!Array.isArray(object.reservedRange)) + throw TypeError(".google.protobuf.EnumDescriptorProto.reservedRange: array expected"); + message.reservedRange = []; + for (var i = 0; i < object.reservedRange.length; ++i) { + if (typeof object.reservedRange[i] !== "object") + throw TypeError(".google.protobuf.EnumDescriptorProto.reservedRange: object expected"); + message.reservedRange[i] = $root.google.protobuf.EnumDescriptorProto.EnumReservedRange.fromObject(object.reservedRange[i]); + } + } + if (object.reservedName) { + if (!Array.isArray(object.reservedName)) + throw TypeError(".google.protobuf.EnumDescriptorProto.reservedName: array expected"); + message.reservedName = []; + for (var i = 0; i < object.reservedName.length; ++i) + message.reservedName[i] = String(object.reservedName[i]); + } + return message; + }; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {google.protobuf.EnumDescriptorProto} message EnumDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.value = []; + object.reservedRange = []; + object.reservedName = []; + } + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.value && message.value.length) { + object.value = []; + for (var j = 0; j < message.value.length; ++j) + object.value[j] = $root.google.protobuf.EnumValueDescriptorProto.toObject(message.value[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.EnumOptions.toObject(message.options, options); + if (message.reservedRange && message.reservedRange.length) { + object.reservedRange = []; + for (var j = 0; j < message.reservedRange.length; ++j) + object.reservedRange[j] = $root.google.protobuf.EnumDescriptorProto.EnumReservedRange.toObject(message.reservedRange[j], options); + } + if (message.reservedName && message.reservedName.length) { + object.reservedName = []; + for (var j = 0; j < message.reservedName.length; ++j) + object.reservedName[j] = message.reservedName[j]; + } + return object; + }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.EnumDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + EnumDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumDescriptorProto"; + }; + + EnumDescriptorProto.EnumReservedRange = (function() { + + /** + * Properties of an EnumReservedRange. + * @memberof google.protobuf.EnumDescriptorProto + * @interface IEnumReservedRange + * @property {number|null} [start] EnumReservedRange start + * @property {number|null} [end] EnumReservedRange end + */ + + /** + * Constructs a new EnumReservedRange. + * @memberof google.protobuf.EnumDescriptorProto + * @classdesc Represents an EnumReservedRange. + * @implements IEnumReservedRange + * @constructor + * @param {google.protobuf.EnumDescriptorProto.IEnumReservedRange=} [properties] Properties to set + */ + function EnumReservedRange(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumReservedRange start. + * @member {number} start + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @instance + */ + EnumReservedRange.prototype.start = 0; + + /** + * EnumReservedRange end. + * @member {number} end + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @instance + */ + EnumReservedRange.prototype.end = 0; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumDescriptorProto.EnumReservedRange} EnumReservedRange + */ + EnumReservedRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumDescriptorProto.EnumReservedRange) + return object; + var message = new $root.google.protobuf.EnumDescriptorProto.EnumReservedRange(); + if (object.start != null) + message.start = object.start | 0; + if (object.end != null) + message.end = object.end | 0; + return message; + }; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {google.protobuf.EnumDescriptorProto.EnumReservedRange} message EnumReservedRange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumReservedRange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.start = 0; + object.end = 0; + } + if (message.start != null && message.hasOwnProperty("start")) + object.start = message.start; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + return object; + }; + + /** + * Converts this EnumReservedRange to JSON. + * @function toJSON + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @instance + * @returns {Object.} JSON object + */ + EnumReservedRange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumReservedRange + * @function getTypeUrl + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumReservedRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumDescriptorProto.EnumReservedRange"; + }; + + return EnumReservedRange; + })(); + + return EnumDescriptorProto; + })(); + + protobuf.EnumValueDescriptorProto = (function() { + + /** + * Properties of an EnumValueDescriptorProto. + * @memberof google.protobuf + * @interface IEnumValueDescriptorProto + * @property {string|null} [name] EnumValueDescriptorProto name + * @property {number|null} [number] EnumValueDescriptorProto number + * @property {google.protobuf.IEnumValueOptions|null} [options] EnumValueDescriptorProto options + */ + + /** + * Constructs a new EnumValueDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents an EnumValueDescriptorProto. + * @implements IEnumValueDescriptorProto + * @constructor + * @param {google.protobuf.IEnumValueDescriptorProto=} [properties] Properties to set + */ + function EnumValueDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumValueDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + */ + EnumValueDescriptorProto.prototype.name = ""; + + /** + * EnumValueDescriptorProto number. + * @member {number} number + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + */ + EnumValueDescriptorProto.prototype.number = 0; + + /** + * EnumValueDescriptorProto options. + * @member {google.protobuf.IEnumValueOptions|null|undefined} options + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + */ + EnumValueDescriptorProto.prototype.options = null; + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumValueDescriptorProto} EnumValueDescriptorProto + */ + EnumValueDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumValueDescriptorProto) + return object; + var message = new $root.google.protobuf.EnumValueDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.number != null) + message.number = object.number | 0; + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.EnumValueDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.EnumValueOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {google.protobuf.EnumValueDescriptorProto} message EnumValueDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumValueDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.number = 0; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.number != null && message.hasOwnProperty("number")) + object.number = message.number; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.EnumValueOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + EnumValueDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumValueDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumValueDescriptorProto"; + }; + + return EnumValueDescriptorProto; + })(); + + protobuf.ServiceDescriptorProto = (function() { + + /** + * Properties of a ServiceDescriptorProto. + * @memberof google.protobuf + * @interface IServiceDescriptorProto + * @property {string|null} [name] ServiceDescriptorProto name + * @property {Array.|null} [method] ServiceDescriptorProto method + * @property {google.protobuf.IServiceOptions|null} [options] ServiceDescriptorProto options + */ + + /** + * Constructs a new ServiceDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a ServiceDescriptorProto. + * @implements IServiceDescriptorProto + * @constructor + * @param {google.protobuf.IServiceDescriptorProto=} [properties] Properties to set + */ + function ServiceDescriptorProto(properties) { + this.method = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ServiceDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + */ + ServiceDescriptorProto.prototype.name = ""; + + /** + * ServiceDescriptorProto method. + * @member {Array.} method + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + */ + ServiceDescriptorProto.prototype.method = $util.emptyArray; + + /** + * ServiceDescriptorProto options. + * @member {google.protobuf.IServiceOptions|null|undefined} options + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + */ + ServiceDescriptorProto.prototype.options = null; + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ServiceDescriptorProto} ServiceDescriptorProto + */ + ServiceDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ServiceDescriptorProto) + return object; + var message = new $root.google.protobuf.ServiceDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.method) { + if (!Array.isArray(object.method)) + throw TypeError(".google.protobuf.ServiceDescriptorProto.method: array expected"); + message.method = []; + for (var i = 0; i < object.method.length; ++i) { + if (typeof object.method[i] !== "object") + throw TypeError(".google.protobuf.ServiceDescriptorProto.method: object expected"); + message.method[i] = $root.google.protobuf.MethodDescriptorProto.fromObject(object.method[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.ServiceDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.ServiceOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {google.protobuf.ServiceDescriptorProto} message ServiceDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ServiceDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.method = []; + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.method && message.method.length) { + object.method = []; + for (var j = 0; j < message.method.length; ++j) + object.method[j] = $root.google.protobuf.MethodDescriptorProto.toObject(message.method[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.ServiceOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + ServiceDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ServiceDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ServiceDescriptorProto"; + }; + + return ServiceDescriptorProto; + })(); + + protobuf.MethodDescriptorProto = (function() { + + /** + * Properties of a MethodDescriptorProto. + * @memberof google.protobuf + * @interface IMethodDescriptorProto + * @property {string|null} [name] MethodDescriptorProto name + * @property {string|null} [inputType] MethodDescriptorProto inputType + * @property {string|null} [outputType] MethodDescriptorProto outputType + * @property {google.protobuf.IMethodOptions|null} [options] MethodDescriptorProto options + * @property {boolean|null} [clientStreaming] MethodDescriptorProto clientStreaming + * @property {boolean|null} [serverStreaming] MethodDescriptorProto serverStreaming + */ + + /** + * Constructs a new MethodDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a MethodDescriptorProto. + * @implements IMethodDescriptorProto + * @constructor + * @param {google.protobuf.IMethodDescriptorProto=} [properties] Properties to set + */ + function MethodDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MethodDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.name = ""; + + /** + * MethodDescriptorProto inputType. + * @member {string} inputType + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.inputType = ""; + + /** + * MethodDescriptorProto outputType. + * @member {string} outputType + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.outputType = ""; + + /** + * MethodDescriptorProto options. + * @member {google.protobuf.IMethodOptions|null|undefined} options + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.options = null; + + /** + * MethodDescriptorProto clientStreaming. + * @member {boolean} clientStreaming + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.clientStreaming = false; + + /** + * MethodDescriptorProto serverStreaming. + * @member {boolean} serverStreaming + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.serverStreaming = false; + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.MethodDescriptorProto} MethodDescriptorProto + */ + MethodDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.MethodDescriptorProto) + return object; + var message = new $root.google.protobuf.MethodDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.inputType != null) + message.inputType = String(object.inputType); + if (object.outputType != null) + message.outputType = String(object.outputType); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.MethodDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.MethodOptions.fromObject(object.options); + } + if (object.clientStreaming != null) + message.clientStreaming = Boolean(object.clientStreaming); + if (object.serverStreaming != null) + message.serverStreaming = Boolean(object.serverStreaming); + return message; + }; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {google.protobuf.MethodDescriptorProto} message MethodDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MethodDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.inputType = ""; + object.outputType = ""; + object.options = null; + object.clientStreaming = false; + object.serverStreaming = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.inputType != null && message.hasOwnProperty("inputType")) + object.inputType = message.inputType; + if (message.outputType != null && message.hasOwnProperty("outputType")) + object.outputType = message.outputType; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.MethodOptions.toObject(message.options, options); + if (message.clientStreaming != null && message.hasOwnProperty("clientStreaming")) + object.clientStreaming = message.clientStreaming; + if (message.serverStreaming != null && message.hasOwnProperty("serverStreaming")) + object.serverStreaming = message.serverStreaming; + return object; + }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.MethodDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + MethodDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MethodDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MethodDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.MethodDescriptorProto"; + }; + + return MethodDescriptorProto; + })(); + + protobuf.FileOptions = (function() { + + /** + * Properties of a FileOptions. + * @memberof google.protobuf + * @interface IFileOptions + * @property {string|null} [javaPackage] FileOptions javaPackage + * @property {string|null} [javaOuterClassname] FileOptions javaOuterClassname + * @property {boolean|null} [javaMultipleFiles] FileOptions javaMultipleFiles + * @property {boolean|null} [javaGenerateEqualsAndHash] FileOptions javaGenerateEqualsAndHash + * @property {boolean|null} [javaStringCheckUtf8] FileOptions javaStringCheckUtf8 + * @property {google.protobuf.FileOptions.OptimizeMode|null} [optimizeFor] FileOptions optimizeFor + * @property {string|null} [goPackage] FileOptions goPackage + * @property {boolean|null} [ccGenericServices] FileOptions ccGenericServices + * @property {boolean|null} [javaGenericServices] FileOptions javaGenericServices + * @property {boolean|null} [pyGenericServices] FileOptions pyGenericServices + * @property {boolean|null} [deprecated] FileOptions deprecated + * @property {boolean|null} [ccEnableArenas] FileOptions ccEnableArenas + * @property {string|null} [objcClassPrefix] FileOptions objcClassPrefix + * @property {string|null} [csharpNamespace] FileOptions csharpNamespace + * @property {string|null} [swiftPrefix] FileOptions swiftPrefix + * @property {string|null} [phpClassPrefix] FileOptions phpClassPrefix + * @property {string|null} [phpNamespace] FileOptions phpNamespace + * @property {string|null} [phpMetadataNamespace] FileOptions phpMetadataNamespace + * @property {string|null} [rubyPackage] FileOptions rubyPackage + * @property {google.protobuf.IFeatureSet|null} [features] FileOptions features + * @property {Array.|null} [uninterpretedOption] FileOptions uninterpretedOption + * @property {Array.|null} [".google.api.resourceDefinition"] FileOptions .google.api.resourceDefinition + */ + + /** + * Constructs a new FileOptions. + * @memberof google.protobuf + * @classdesc Represents a FileOptions. + * @implements IFileOptions + * @constructor + * @param {google.protobuf.IFileOptions=} [properties] Properties to set + */ + function FileOptions(properties) { + this.uninterpretedOption = []; + this[".google.api.resourceDefinition"] = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FileOptions javaPackage. + * @member {string} javaPackage + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaPackage = ""; + + /** + * FileOptions javaOuterClassname. + * @member {string} javaOuterClassname + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaOuterClassname = ""; + + /** + * FileOptions javaMultipleFiles. + * @member {boolean} javaMultipleFiles + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaMultipleFiles = false; + + /** + * FileOptions javaGenerateEqualsAndHash. + * @member {boolean} javaGenerateEqualsAndHash + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaGenerateEqualsAndHash = false; + + /** + * FileOptions javaStringCheckUtf8. + * @member {boolean} javaStringCheckUtf8 + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaStringCheckUtf8 = false; + + /** + * FileOptions optimizeFor. + * @member {google.protobuf.FileOptions.OptimizeMode} optimizeFor + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.optimizeFor = 1; + + /** + * FileOptions goPackage. + * @member {string} goPackage + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.goPackage = ""; + + /** + * FileOptions ccGenericServices. + * @member {boolean} ccGenericServices + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.ccGenericServices = false; + + /** + * FileOptions javaGenericServices. + * @member {boolean} javaGenericServices + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaGenericServices = false; + + /** + * FileOptions pyGenericServices. + * @member {boolean} pyGenericServices + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.pyGenericServices = false; + + /** + * FileOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.deprecated = false; + + /** + * FileOptions ccEnableArenas. + * @member {boolean} ccEnableArenas + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.ccEnableArenas = true; + + /** + * FileOptions objcClassPrefix. + * @member {string} objcClassPrefix + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.objcClassPrefix = ""; + + /** + * FileOptions csharpNamespace. + * @member {string} csharpNamespace + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.csharpNamespace = ""; + + /** + * FileOptions swiftPrefix. + * @member {string} swiftPrefix + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.swiftPrefix = ""; + + /** + * FileOptions phpClassPrefix. + * @member {string} phpClassPrefix + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.phpClassPrefix = ""; + + /** + * FileOptions phpNamespace. + * @member {string} phpNamespace + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.phpNamespace = ""; + + /** + * FileOptions phpMetadataNamespace. + * @member {string} phpMetadataNamespace + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.phpMetadataNamespace = ""; + + /** + * FileOptions rubyPackage. + * @member {string} rubyPackage + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.rubyPackage = ""; + + /** + * FileOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.features = null; + + /** + * FileOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * FileOptions .google.api.resourceDefinition. + * @member {Array.} .google.api.resourceDefinition + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype[".google.api.resourceDefinition"] = $util.emptyArray; + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FileOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FileOptions} FileOptions + */ + FileOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FileOptions) + return object; + var message = new $root.google.protobuf.FileOptions(); + if (object.javaPackage != null) + message.javaPackage = String(object.javaPackage); + if (object.javaOuterClassname != null) + message.javaOuterClassname = String(object.javaOuterClassname); + if (object.javaMultipleFiles != null) + message.javaMultipleFiles = Boolean(object.javaMultipleFiles); + if (object.javaGenerateEqualsAndHash != null) + message.javaGenerateEqualsAndHash = Boolean(object.javaGenerateEqualsAndHash); + if (object.javaStringCheckUtf8 != null) + message.javaStringCheckUtf8 = Boolean(object.javaStringCheckUtf8); + switch (object.optimizeFor) { + default: + if (typeof object.optimizeFor === "number") { + message.optimizeFor = object.optimizeFor; + break; + } + break; + case "SPEED": + case 1: + message.optimizeFor = 1; + break; + case "CODE_SIZE": + case 2: + message.optimizeFor = 2; + break; + case "LITE_RUNTIME": + case 3: + message.optimizeFor = 3; + break; + } + if (object.goPackage != null) + message.goPackage = String(object.goPackage); + if (object.ccGenericServices != null) + message.ccGenericServices = Boolean(object.ccGenericServices); + if (object.javaGenericServices != null) + message.javaGenericServices = Boolean(object.javaGenericServices); + if (object.pyGenericServices != null) + message.pyGenericServices = Boolean(object.pyGenericServices); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.ccEnableArenas != null) + message.ccEnableArenas = Boolean(object.ccEnableArenas); + if (object.objcClassPrefix != null) + message.objcClassPrefix = String(object.objcClassPrefix); + if (object.csharpNamespace != null) + message.csharpNamespace = String(object.csharpNamespace); + if (object.swiftPrefix != null) + message.swiftPrefix = String(object.swiftPrefix); + if (object.phpClassPrefix != null) + message.phpClassPrefix = String(object.phpClassPrefix); + if (object.phpNamespace != null) + message.phpNamespace = String(object.phpNamespace); + if (object.phpMetadataNamespace != null) + message.phpMetadataNamespace = String(object.phpMetadataNamespace); + if (object.rubyPackage != null) + message.rubyPackage = String(object.rubyPackage); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.FileOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.FileOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.FileOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.resourceDefinition"]) { + if (!Array.isArray(object[".google.api.resourceDefinition"])) + throw TypeError(".google.protobuf.FileOptions..google.api.resourceDefinition: array expected"); + message[".google.api.resourceDefinition"] = []; + for (var i = 0; i < object[".google.api.resourceDefinition"].length; ++i) { + if (typeof object[".google.api.resourceDefinition"][i] !== "object") + throw TypeError(".google.protobuf.FileOptions..google.api.resourceDefinition: object expected"); + message[".google.api.resourceDefinition"][i] = $root.google.api.ResourceDescriptor.fromObject(object[".google.api.resourceDefinition"][i]); + } + } + return message; + }; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FileOptions + * @static + * @param {google.protobuf.FileOptions} message FileOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FileOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.uninterpretedOption = []; + object[".google.api.resourceDefinition"] = []; + } + if (options.defaults) { + object.javaPackage = ""; + object.javaOuterClassname = ""; + object.optimizeFor = options.enums === String ? "SPEED" : 1; + object.javaMultipleFiles = false; + object.goPackage = ""; + object.ccGenericServices = false; + object.javaGenericServices = false; + object.pyGenericServices = false; + object.javaGenerateEqualsAndHash = false; + object.deprecated = false; + object.javaStringCheckUtf8 = false; + object.ccEnableArenas = true; + object.objcClassPrefix = ""; + object.csharpNamespace = ""; + object.swiftPrefix = ""; + object.phpClassPrefix = ""; + object.phpNamespace = ""; + object.phpMetadataNamespace = ""; + object.rubyPackage = ""; + object.features = null; + } + if (message.javaPackage != null && message.hasOwnProperty("javaPackage")) + object.javaPackage = message.javaPackage; + if (message.javaOuterClassname != null && message.hasOwnProperty("javaOuterClassname")) + object.javaOuterClassname = message.javaOuterClassname; + if (message.optimizeFor != null && message.hasOwnProperty("optimizeFor")) + object.optimizeFor = options.enums === String ? $root.google.protobuf.FileOptions.OptimizeMode[message.optimizeFor] === undefined ? message.optimizeFor : $root.google.protobuf.FileOptions.OptimizeMode[message.optimizeFor] : message.optimizeFor; + if (message.javaMultipleFiles != null && message.hasOwnProperty("javaMultipleFiles")) + object.javaMultipleFiles = message.javaMultipleFiles; + if (message.goPackage != null && message.hasOwnProperty("goPackage")) + object.goPackage = message.goPackage; + if (message.ccGenericServices != null && message.hasOwnProperty("ccGenericServices")) + object.ccGenericServices = message.ccGenericServices; + if (message.javaGenericServices != null && message.hasOwnProperty("javaGenericServices")) + object.javaGenericServices = message.javaGenericServices; + if (message.pyGenericServices != null && message.hasOwnProperty("pyGenericServices")) + object.pyGenericServices = message.pyGenericServices; + if (message.javaGenerateEqualsAndHash != null && message.hasOwnProperty("javaGenerateEqualsAndHash")) + object.javaGenerateEqualsAndHash = message.javaGenerateEqualsAndHash; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.javaStringCheckUtf8 != null && message.hasOwnProperty("javaStringCheckUtf8")) + object.javaStringCheckUtf8 = message.javaStringCheckUtf8; + if (message.ccEnableArenas != null && message.hasOwnProperty("ccEnableArenas")) + object.ccEnableArenas = message.ccEnableArenas; + if (message.objcClassPrefix != null && message.hasOwnProperty("objcClassPrefix")) + object.objcClassPrefix = message.objcClassPrefix; + if (message.csharpNamespace != null && message.hasOwnProperty("csharpNamespace")) + object.csharpNamespace = message.csharpNamespace; + if (message.swiftPrefix != null && message.hasOwnProperty("swiftPrefix")) + object.swiftPrefix = message.swiftPrefix; + if (message.phpClassPrefix != null && message.hasOwnProperty("phpClassPrefix")) + object.phpClassPrefix = message.phpClassPrefix; + if (message.phpNamespace != null && message.hasOwnProperty("phpNamespace")) + object.phpNamespace = message.phpNamespace; + if (message.phpMetadataNamespace != null && message.hasOwnProperty("phpMetadataNamespace")) + object.phpMetadataNamespace = message.phpMetadataNamespace; + if (message.rubyPackage != null && message.hasOwnProperty("rubyPackage")) + object.rubyPackage = message.rubyPackage; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.resourceDefinition"] && message[".google.api.resourceDefinition"].length) { + object[".google.api.resourceDefinition"] = []; + for (var j = 0; j < message[".google.api.resourceDefinition"].length; ++j) + object[".google.api.resourceDefinition"][j] = $root.google.api.ResourceDescriptor.toObject(message[".google.api.resourceDefinition"][j], options); + } + return object; + }; + + /** + * Converts this FileOptions to JSON. + * @function toJSON + * @memberof google.protobuf.FileOptions + * @instance + * @returns {Object.} JSON object + */ + FileOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FileOptions + * @function getTypeUrl + * @memberof google.protobuf.FileOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FileOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FileOptions"; + }; + + /** + * OptimizeMode enum. + * @name google.protobuf.FileOptions.OptimizeMode + * @enum {string} + * @property {string} SPEED=SPEED SPEED value + * @property {string} CODE_SIZE=CODE_SIZE CODE_SIZE value + * @property {string} LITE_RUNTIME=LITE_RUNTIME LITE_RUNTIME value + */ + FileOptions.OptimizeMode = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[1] = "SPEED"] = "SPEED"; + values[valuesById[2] = "CODE_SIZE"] = "CODE_SIZE"; + values[valuesById[3] = "LITE_RUNTIME"] = "LITE_RUNTIME"; + return values; + })(); + + return FileOptions; + })(); + + protobuf.MessageOptions = (function() { + + /** + * Properties of a MessageOptions. + * @memberof google.protobuf + * @interface IMessageOptions + * @property {boolean|null} [messageSetWireFormat] MessageOptions messageSetWireFormat + * @property {boolean|null} [noStandardDescriptorAccessor] MessageOptions noStandardDescriptorAccessor + * @property {boolean|null} [deprecated] MessageOptions deprecated + * @property {boolean|null} [mapEntry] MessageOptions mapEntry + * @property {boolean|null} [deprecatedLegacyJsonFieldConflicts] MessageOptions deprecatedLegacyJsonFieldConflicts + * @property {google.protobuf.IFeatureSet|null} [features] MessageOptions features + * @property {Array.|null} [uninterpretedOption] MessageOptions uninterpretedOption + * @property {google.api.IResourceDescriptor|null} [".google.api.resource"] MessageOptions .google.api.resource + */ + + /** + * Constructs a new MessageOptions. + * @memberof google.protobuf + * @classdesc Represents a MessageOptions. + * @implements IMessageOptions + * @constructor + * @param {google.protobuf.IMessageOptions=} [properties] Properties to set + */ + function MessageOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MessageOptions messageSetWireFormat. + * @member {boolean} messageSetWireFormat + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.messageSetWireFormat = false; + + /** + * MessageOptions noStandardDescriptorAccessor. + * @member {boolean} noStandardDescriptorAccessor + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.noStandardDescriptorAccessor = false; + + /** + * MessageOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.deprecated = false; + + /** + * MessageOptions mapEntry. + * @member {boolean} mapEntry + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.mapEntry = false; + + /** + * MessageOptions deprecatedLegacyJsonFieldConflicts. + * @member {boolean} deprecatedLegacyJsonFieldConflicts + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.deprecatedLegacyJsonFieldConflicts = false; + + /** + * MessageOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.features = null; + + /** + * MessageOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * MessageOptions .google.api.resource. + * @member {google.api.IResourceDescriptor|null|undefined} .google.api.resource + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype[".google.api.resource"] = null; + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.MessageOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.MessageOptions} MessageOptions + */ + MessageOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.MessageOptions) + return object; + var message = new $root.google.protobuf.MessageOptions(); + if (object.messageSetWireFormat != null) + message.messageSetWireFormat = Boolean(object.messageSetWireFormat); + if (object.noStandardDescriptorAccessor != null) + message.noStandardDescriptorAccessor = Boolean(object.noStandardDescriptorAccessor); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.mapEntry != null) + message.mapEntry = Boolean(object.mapEntry); + if (object.deprecatedLegacyJsonFieldConflicts != null) + message.deprecatedLegacyJsonFieldConflicts = Boolean(object.deprecatedLegacyJsonFieldConflicts); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.MessageOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.MessageOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.MessageOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.resource"] != null) { + if (typeof object[".google.api.resource"] !== "object") + throw TypeError(".google.protobuf.MessageOptions..google.api.resource: object expected"); + message[".google.api.resource"] = $root.google.api.ResourceDescriptor.fromObject(object[".google.api.resource"]); + } + return message; + }; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.MessageOptions + * @static + * @param {google.protobuf.MessageOptions} message MessageOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MessageOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.messageSetWireFormat = false; + object.noStandardDescriptorAccessor = false; + object.deprecated = false; + object.mapEntry = false; + object.deprecatedLegacyJsonFieldConflicts = false; + object.features = null; + object[".google.api.resource"] = null; + } + if (message.messageSetWireFormat != null && message.hasOwnProperty("messageSetWireFormat")) + object.messageSetWireFormat = message.messageSetWireFormat; + if (message.noStandardDescriptorAccessor != null && message.hasOwnProperty("noStandardDescriptorAccessor")) + object.noStandardDescriptorAccessor = message.noStandardDescriptorAccessor; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.mapEntry != null && message.hasOwnProperty("mapEntry")) + object.mapEntry = message.mapEntry; + if (message.deprecatedLegacyJsonFieldConflicts != null && message.hasOwnProperty("deprecatedLegacyJsonFieldConflicts")) + object.deprecatedLegacyJsonFieldConflicts = message.deprecatedLegacyJsonFieldConflicts; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.resource"] != null && message.hasOwnProperty(".google.api.resource")) + object[".google.api.resource"] = $root.google.api.ResourceDescriptor.toObject(message[".google.api.resource"], options); + return object; + }; + + /** + * Converts this MessageOptions to JSON. + * @function toJSON + * @memberof google.protobuf.MessageOptions + * @instance + * @returns {Object.} JSON object + */ + MessageOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MessageOptions + * @function getTypeUrl + * @memberof google.protobuf.MessageOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MessageOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.MessageOptions"; + }; + + return MessageOptions; + })(); + + protobuf.FieldOptions = (function() { + + /** + * Properties of a FieldOptions. + * @memberof google.protobuf + * @interface IFieldOptions + * @property {google.protobuf.FieldOptions.CType|null} [ctype] FieldOptions ctype + * @property {boolean|null} [packed] FieldOptions packed + * @property {google.protobuf.FieldOptions.JSType|null} [jstype] FieldOptions jstype + * @property {boolean|null} [lazy] FieldOptions lazy + * @property {boolean|null} [unverifiedLazy] FieldOptions unverifiedLazy + * @property {boolean|null} [deprecated] FieldOptions deprecated + * @property {boolean|null} [weak] FieldOptions weak + * @property {boolean|null} [debugRedact] FieldOptions debugRedact + * @property {google.protobuf.FieldOptions.OptionRetention|null} [retention] FieldOptions retention + * @property {Array.|null} [targets] FieldOptions targets + * @property {Array.|null} [editionDefaults] FieldOptions editionDefaults + * @property {google.protobuf.IFeatureSet|null} [features] FieldOptions features + * @property {Array.|null} [uninterpretedOption] FieldOptions uninterpretedOption + * @property {Array.|null} [".google.api.fieldBehavior"] FieldOptions .google.api.fieldBehavior + * @property {google.api.IResourceReference|null} [".google.api.resourceReference"] FieldOptions .google.api.resourceReference + */ + + /** + * Constructs a new FieldOptions. + * @memberof google.protobuf + * @classdesc Represents a FieldOptions. + * @implements IFieldOptions + * @constructor + * @param {google.protobuf.IFieldOptions=} [properties] Properties to set + */ + function FieldOptions(properties) { + this.targets = []; + this.editionDefaults = []; + this.uninterpretedOption = []; + this[".google.api.fieldBehavior"] = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldOptions ctype. + * @member {google.protobuf.FieldOptions.CType} ctype + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.ctype = 0; + + /** + * FieldOptions packed. + * @member {boolean} packed + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.packed = false; + + /** + * FieldOptions jstype. + * @member {google.protobuf.FieldOptions.JSType} jstype + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.jstype = 0; + + /** + * FieldOptions lazy. + * @member {boolean} lazy + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.lazy = false; + + /** + * FieldOptions unverifiedLazy. + * @member {boolean} unverifiedLazy + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.unverifiedLazy = false; + + /** + * FieldOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.deprecated = false; + + /** + * FieldOptions weak. + * @member {boolean} weak + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.weak = false; + + /** + * FieldOptions debugRedact. + * @member {boolean} debugRedact + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.debugRedact = false; + + /** + * FieldOptions retention. + * @member {google.protobuf.FieldOptions.OptionRetention} retention + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.retention = 0; + + /** + * FieldOptions targets. + * @member {Array.} targets + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.targets = $util.emptyArray; + + /** + * FieldOptions editionDefaults. + * @member {Array.} editionDefaults + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.editionDefaults = $util.emptyArray; + + /** + * FieldOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.features = null; + + /** + * FieldOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * FieldOptions .google.api.fieldBehavior. + * @member {Array.} .google.api.fieldBehavior + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype[".google.api.fieldBehavior"] = $util.emptyArray; + + /** + * FieldOptions .google.api.resourceReference. + * @member {google.api.IResourceReference|null|undefined} .google.api.resourceReference + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype[".google.api.resourceReference"] = null; + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldOptions} FieldOptions + */ + FieldOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldOptions) + return object; + var message = new $root.google.protobuf.FieldOptions(); + switch (object.ctype) { + default: + if (typeof object.ctype === "number") { + message.ctype = object.ctype; + break; + } + break; + case "STRING": + case 0: + message.ctype = 0; + break; + case "CORD": + case 1: + message.ctype = 1; + break; + case "STRING_PIECE": + case 2: + message.ctype = 2; + break; + } + if (object.packed != null) + message.packed = Boolean(object.packed); + switch (object.jstype) { + default: + if (typeof object.jstype === "number") { + message.jstype = object.jstype; + break; + } + break; + case "JS_NORMAL": + case 0: + message.jstype = 0; + break; + case "JS_STRING": + case 1: + message.jstype = 1; + break; + case "JS_NUMBER": + case 2: + message.jstype = 2; + break; + } + if (object.lazy != null) + message.lazy = Boolean(object.lazy); + if (object.unverifiedLazy != null) + message.unverifiedLazy = Boolean(object.unverifiedLazy); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.weak != null) + message.weak = Boolean(object.weak); + if (object.debugRedact != null) + message.debugRedact = Boolean(object.debugRedact); + switch (object.retention) { + default: + if (typeof object.retention === "number") { + message.retention = object.retention; + break; + } + break; + case "RETENTION_UNKNOWN": + case 0: + message.retention = 0; + break; + case "RETENTION_RUNTIME": + case 1: + message.retention = 1; + break; + case "RETENTION_SOURCE": + case 2: + message.retention = 2; + break; + } + if (object.targets) { + if (!Array.isArray(object.targets)) + throw TypeError(".google.protobuf.FieldOptions.targets: array expected"); + message.targets = []; + for (var i = 0; i < object.targets.length; ++i) + switch (object.targets[i]) { + default: + if (typeof object.targets[i] === "number") { + message.targets[i] = object.targets[i]; + break; + } + case "TARGET_TYPE_UNKNOWN": + case 0: + message.targets[i] = 0; + break; + case "TARGET_TYPE_FILE": + case 1: + message.targets[i] = 1; + break; + case "TARGET_TYPE_EXTENSION_RANGE": + case 2: + message.targets[i] = 2; + break; + case "TARGET_TYPE_MESSAGE": + case 3: + message.targets[i] = 3; + break; + case "TARGET_TYPE_FIELD": + case 4: + message.targets[i] = 4; + break; + case "TARGET_TYPE_ONEOF": + case 5: + message.targets[i] = 5; + break; + case "TARGET_TYPE_ENUM": + case 6: + message.targets[i] = 6; + break; + case "TARGET_TYPE_ENUM_ENTRY": + case 7: + message.targets[i] = 7; + break; + case "TARGET_TYPE_SERVICE": + case 8: + message.targets[i] = 8; + break; + case "TARGET_TYPE_METHOD": + case 9: + message.targets[i] = 9; + break; + } + } + if (object.editionDefaults) { + if (!Array.isArray(object.editionDefaults)) + throw TypeError(".google.protobuf.FieldOptions.editionDefaults: array expected"); + message.editionDefaults = []; + for (var i = 0; i < object.editionDefaults.length; ++i) { + if (typeof object.editionDefaults[i] !== "object") + throw TypeError(".google.protobuf.FieldOptions.editionDefaults: object expected"); + message.editionDefaults[i] = $root.google.protobuf.FieldOptions.EditionDefault.fromObject(object.editionDefaults[i]); + } + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.FieldOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.FieldOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.FieldOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.fieldBehavior"]) { + if (!Array.isArray(object[".google.api.fieldBehavior"])) + throw TypeError(".google.protobuf.FieldOptions..google.api.fieldBehavior: array expected"); + message[".google.api.fieldBehavior"] = []; + for (var i = 0; i < object[".google.api.fieldBehavior"].length; ++i) + switch (object[".google.api.fieldBehavior"][i]) { + default: + if (typeof object[".google.api.fieldBehavior"][i] === "number") { + message[".google.api.fieldBehavior"][i] = object[".google.api.fieldBehavior"][i]; + break; + } + case "FIELD_BEHAVIOR_UNSPECIFIED": + case 0: + message[".google.api.fieldBehavior"][i] = 0; + break; + case "OPTIONAL": + case 1: + message[".google.api.fieldBehavior"][i] = 1; + break; + case "REQUIRED": + case 2: + message[".google.api.fieldBehavior"][i] = 2; + break; + case "OUTPUT_ONLY": + case 3: + message[".google.api.fieldBehavior"][i] = 3; + break; + case "INPUT_ONLY": + case 4: + message[".google.api.fieldBehavior"][i] = 4; + break; + case "IMMUTABLE": + case 5: + message[".google.api.fieldBehavior"][i] = 5; + break; + case "UNORDERED_LIST": + case 6: + message[".google.api.fieldBehavior"][i] = 6; + break; + case "NON_EMPTY_DEFAULT": + case 7: + message[".google.api.fieldBehavior"][i] = 7; + break; + case "IDENTIFIER": + case 8: + message[".google.api.fieldBehavior"][i] = 8; + break; + } + } + if (object[".google.api.resourceReference"] != null) { + if (typeof object[".google.api.resourceReference"] !== "object") + throw TypeError(".google.protobuf.FieldOptions..google.api.resourceReference: object expected"); + message[".google.api.resourceReference"] = $root.google.api.ResourceReference.fromObject(object[".google.api.resourceReference"]); + } + return message; + }; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldOptions + * @static + * @param {google.protobuf.FieldOptions} message FieldOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.targets = []; + object.editionDefaults = []; + object.uninterpretedOption = []; + object[".google.api.fieldBehavior"] = []; + } + if (options.defaults) { + object.ctype = options.enums === String ? "STRING" : 0; + object.packed = false; + object.deprecated = false; + object.lazy = false; + object.jstype = options.enums === String ? "JS_NORMAL" : 0; + object.weak = false; + object.unverifiedLazy = false; + object.debugRedact = false; + object.retention = options.enums === String ? "RETENTION_UNKNOWN" : 0; + object.features = null; + object[".google.api.resourceReference"] = null; + } + if (message.ctype != null && message.hasOwnProperty("ctype")) + object.ctype = options.enums === String ? $root.google.protobuf.FieldOptions.CType[message.ctype] === undefined ? message.ctype : $root.google.protobuf.FieldOptions.CType[message.ctype] : message.ctype; + if (message.packed != null && message.hasOwnProperty("packed")) + object.packed = message.packed; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.lazy != null && message.hasOwnProperty("lazy")) + object.lazy = message.lazy; + if (message.jstype != null && message.hasOwnProperty("jstype")) + object.jstype = options.enums === String ? $root.google.protobuf.FieldOptions.JSType[message.jstype] === undefined ? message.jstype : $root.google.protobuf.FieldOptions.JSType[message.jstype] : message.jstype; + if (message.weak != null && message.hasOwnProperty("weak")) + object.weak = message.weak; + if (message.unverifiedLazy != null && message.hasOwnProperty("unverifiedLazy")) + object.unverifiedLazy = message.unverifiedLazy; + if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) + object.debugRedact = message.debugRedact; + if (message.retention != null && message.hasOwnProperty("retention")) + object.retention = options.enums === String ? $root.google.protobuf.FieldOptions.OptionRetention[message.retention] === undefined ? message.retention : $root.google.protobuf.FieldOptions.OptionRetention[message.retention] : message.retention; + if (message.targets && message.targets.length) { + object.targets = []; + for (var j = 0; j < message.targets.length; ++j) + object.targets[j] = options.enums === String ? $root.google.protobuf.FieldOptions.OptionTargetType[message.targets[j]] === undefined ? message.targets[j] : $root.google.protobuf.FieldOptions.OptionTargetType[message.targets[j]] : message.targets[j]; + } + if (message.editionDefaults && message.editionDefaults.length) { + object.editionDefaults = []; + for (var j = 0; j < message.editionDefaults.length; ++j) + object.editionDefaults[j] = $root.google.protobuf.FieldOptions.EditionDefault.toObject(message.editionDefaults[j], options); + } + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.fieldBehavior"] && message[".google.api.fieldBehavior"].length) { + object[".google.api.fieldBehavior"] = []; + for (var j = 0; j < message[".google.api.fieldBehavior"].length; ++j) + object[".google.api.fieldBehavior"][j] = options.enums === String ? $root.google.api.FieldBehavior[message[".google.api.fieldBehavior"][j]] === undefined ? message[".google.api.fieldBehavior"][j] : $root.google.api.FieldBehavior[message[".google.api.fieldBehavior"][j]] : message[".google.api.fieldBehavior"][j]; + } + if (message[".google.api.resourceReference"] != null && message.hasOwnProperty(".google.api.resourceReference")) + object[".google.api.resourceReference"] = $root.google.api.ResourceReference.toObject(message[".google.api.resourceReference"], options); + return object; + }; + + /** + * Converts this FieldOptions to JSON. + * @function toJSON + * @memberof google.protobuf.FieldOptions + * @instance + * @returns {Object.} JSON object + */ + FieldOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldOptions + * @function getTypeUrl + * @memberof google.protobuf.FieldOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldOptions"; + }; + + /** + * CType enum. + * @name google.protobuf.FieldOptions.CType + * @enum {string} + * @property {string} STRING=STRING STRING value + * @property {string} CORD=CORD CORD value + * @property {string} STRING_PIECE=STRING_PIECE STRING_PIECE value + */ + FieldOptions.CType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STRING"] = "STRING"; + values[valuesById[1] = "CORD"] = "CORD"; + values[valuesById[2] = "STRING_PIECE"] = "STRING_PIECE"; + return values; + })(); + + /** + * JSType enum. + * @name google.protobuf.FieldOptions.JSType + * @enum {string} + * @property {string} JS_NORMAL=JS_NORMAL JS_NORMAL value + * @property {string} JS_STRING=JS_STRING JS_STRING value + * @property {string} JS_NUMBER=JS_NUMBER JS_NUMBER value + */ + FieldOptions.JSType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "JS_NORMAL"] = "JS_NORMAL"; + values[valuesById[1] = "JS_STRING"] = "JS_STRING"; + values[valuesById[2] = "JS_NUMBER"] = "JS_NUMBER"; + return values; + })(); + + /** + * OptionRetention enum. + * @name google.protobuf.FieldOptions.OptionRetention + * @enum {string} + * @property {string} RETENTION_UNKNOWN=RETENTION_UNKNOWN RETENTION_UNKNOWN value + * @property {string} RETENTION_RUNTIME=RETENTION_RUNTIME RETENTION_RUNTIME value + * @property {string} RETENTION_SOURCE=RETENTION_SOURCE RETENTION_SOURCE value + */ + FieldOptions.OptionRetention = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "RETENTION_UNKNOWN"] = "RETENTION_UNKNOWN"; + values[valuesById[1] = "RETENTION_RUNTIME"] = "RETENTION_RUNTIME"; + values[valuesById[2] = "RETENTION_SOURCE"] = "RETENTION_SOURCE"; + return values; + })(); + + /** + * OptionTargetType enum. + * @name google.protobuf.FieldOptions.OptionTargetType + * @enum {string} + * @property {string} TARGET_TYPE_UNKNOWN=TARGET_TYPE_UNKNOWN TARGET_TYPE_UNKNOWN value + * @property {string} TARGET_TYPE_FILE=TARGET_TYPE_FILE TARGET_TYPE_FILE value + * @property {string} TARGET_TYPE_EXTENSION_RANGE=TARGET_TYPE_EXTENSION_RANGE TARGET_TYPE_EXTENSION_RANGE value + * @property {string} TARGET_TYPE_MESSAGE=TARGET_TYPE_MESSAGE TARGET_TYPE_MESSAGE value + * @property {string} TARGET_TYPE_FIELD=TARGET_TYPE_FIELD TARGET_TYPE_FIELD value + * @property {string} TARGET_TYPE_ONEOF=TARGET_TYPE_ONEOF TARGET_TYPE_ONEOF value + * @property {string} TARGET_TYPE_ENUM=TARGET_TYPE_ENUM TARGET_TYPE_ENUM value + * @property {string} TARGET_TYPE_ENUM_ENTRY=TARGET_TYPE_ENUM_ENTRY TARGET_TYPE_ENUM_ENTRY value + * @property {string} TARGET_TYPE_SERVICE=TARGET_TYPE_SERVICE TARGET_TYPE_SERVICE value + * @property {string} TARGET_TYPE_METHOD=TARGET_TYPE_METHOD TARGET_TYPE_METHOD value + */ + FieldOptions.OptionTargetType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "TARGET_TYPE_UNKNOWN"] = "TARGET_TYPE_UNKNOWN"; + values[valuesById[1] = "TARGET_TYPE_FILE"] = "TARGET_TYPE_FILE"; + values[valuesById[2] = "TARGET_TYPE_EXTENSION_RANGE"] = "TARGET_TYPE_EXTENSION_RANGE"; + values[valuesById[3] = "TARGET_TYPE_MESSAGE"] = "TARGET_TYPE_MESSAGE"; + values[valuesById[4] = "TARGET_TYPE_FIELD"] = "TARGET_TYPE_FIELD"; + values[valuesById[5] = "TARGET_TYPE_ONEOF"] = "TARGET_TYPE_ONEOF"; + values[valuesById[6] = "TARGET_TYPE_ENUM"] = "TARGET_TYPE_ENUM"; + values[valuesById[7] = "TARGET_TYPE_ENUM_ENTRY"] = "TARGET_TYPE_ENUM_ENTRY"; + values[valuesById[8] = "TARGET_TYPE_SERVICE"] = "TARGET_TYPE_SERVICE"; + values[valuesById[9] = "TARGET_TYPE_METHOD"] = "TARGET_TYPE_METHOD"; + return values; + })(); + + FieldOptions.EditionDefault = (function() { + + /** + * Properties of an EditionDefault. + * @memberof google.protobuf.FieldOptions + * @interface IEditionDefault + * @property {google.protobuf.Edition|null} [edition] EditionDefault edition + * @property {string|null} [value] EditionDefault value + */ + + /** + * Constructs a new EditionDefault. + * @memberof google.protobuf.FieldOptions + * @classdesc Represents an EditionDefault. + * @implements IEditionDefault + * @constructor + * @param {google.protobuf.FieldOptions.IEditionDefault=} [properties] Properties to set + */ + function EditionDefault(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EditionDefault edition. + * @member {google.protobuf.Edition} edition + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + */ + EditionDefault.prototype.edition = 0; + + /** + * EditionDefault value. + * @member {string} value + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + */ + EditionDefault.prototype.value = ""; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldOptions.EditionDefault} EditionDefault + */ + EditionDefault.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldOptions.EditionDefault) + return object; + var message = new $root.google.protobuf.FieldOptions.EditionDefault(); + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.edition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.edition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.edition = 999; + break; + case "EDITION_2023": + case 1000: + message.edition = 1000; + break; + case "EDITION_2024": + case 1001: + message.edition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.edition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.edition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.edition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.edition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.edition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.edition = 2147483647; + break; + } + if (object.value != null) + message.value = String(object.value); + return message; + }; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {google.protobuf.FieldOptions.EditionDefault} message EditionDefault + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EditionDefault.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.value = ""; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; + return object; + }; + + /** + * Converts this EditionDefault to JSON. + * @function toJSON + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + * @returns {Object.} JSON object + */ + EditionDefault.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EditionDefault + * @function getTypeUrl + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldOptions.EditionDefault"; + }; + + return EditionDefault; + })(); + + return FieldOptions; + })(); + + protobuf.OneofOptions = (function() { + + /** + * Properties of an OneofOptions. + * @memberof google.protobuf + * @interface IOneofOptions + * @property {google.protobuf.IFeatureSet|null} [features] OneofOptions features + * @property {Array.|null} [uninterpretedOption] OneofOptions uninterpretedOption + */ + + /** + * Constructs a new OneofOptions. + * @memberof google.protobuf + * @classdesc Represents an OneofOptions. + * @implements IOneofOptions + * @constructor + * @param {google.protobuf.IOneofOptions=} [properties] Properties to set + */ + function OneofOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OneofOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.OneofOptions + * @instance + */ + OneofOptions.prototype.features = null; + + /** + * OneofOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.OneofOptions + * @instance + */ + OneofOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.OneofOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.OneofOptions} OneofOptions + */ + OneofOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.OneofOptions) + return object; + var message = new $root.google.protobuf.OneofOptions(); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.OneofOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.OneofOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.OneofOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.OneofOptions + * @static + * @param {google.protobuf.OneofOptions} message OneofOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OneofOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) + object.features = null; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this OneofOptions to JSON. + * @function toJSON + * @memberof google.protobuf.OneofOptions + * @instance + * @returns {Object.} JSON object + */ + OneofOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OneofOptions + * @function getTypeUrl + * @memberof google.protobuf.OneofOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OneofOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.OneofOptions"; + }; + + return OneofOptions; + })(); + + protobuf.EnumOptions = (function() { + + /** + * Properties of an EnumOptions. + * @memberof google.protobuf + * @interface IEnumOptions + * @property {boolean|null} [allowAlias] EnumOptions allowAlias + * @property {boolean|null} [deprecated] EnumOptions deprecated + * @property {boolean|null} [deprecatedLegacyJsonFieldConflicts] EnumOptions deprecatedLegacyJsonFieldConflicts + * @property {google.protobuf.IFeatureSet|null} [features] EnumOptions features + * @property {Array.|null} [uninterpretedOption] EnumOptions uninterpretedOption + */ + + /** + * Constructs a new EnumOptions. + * @memberof google.protobuf + * @classdesc Represents an EnumOptions. + * @implements IEnumOptions + * @constructor + * @param {google.protobuf.IEnumOptions=} [properties] Properties to set + */ + function EnumOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumOptions allowAlias. + * @member {boolean} allowAlias + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.allowAlias = false; + + /** + * EnumOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.deprecated = false; + + /** + * EnumOptions deprecatedLegacyJsonFieldConflicts. + * @member {boolean} deprecatedLegacyJsonFieldConflicts + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.deprecatedLegacyJsonFieldConflicts = false; + + /** + * EnumOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.features = null; + + /** + * EnumOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumOptions} EnumOptions + */ + EnumOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumOptions) + return object; + var message = new $root.google.protobuf.EnumOptions(); + if (object.allowAlias != null) + message.allowAlias = Boolean(object.allowAlias); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.deprecatedLegacyJsonFieldConflicts != null) + message.deprecatedLegacyJsonFieldConflicts = Boolean(object.deprecatedLegacyJsonFieldConflicts); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.EnumOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.EnumOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.EnumOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumOptions + * @static + * @param {google.protobuf.EnumOptions} message EnumOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.allowAlias = false; + object.deprecated = false; + object.deprecatedLegacyJsonFieldConflicts = false; + object.features = null; + } + if (message.allowAlias != null && message.hasOwnProperty("allowAlias")) + object.allowAlias = message.allowAlias; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.deprecatedLegacyJsonFieldConflicts != null && message.hasOwnProperty("deprecatedLegacyJsonFieldConflicts")) + object.deprecatedLegacyJsonFieldConflicts = message.deprecatedLegacyJsonFieldConflicts; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this EnumOptions to JSON. + * @function toJSON + * @memberof google.protobuf.EnumOptions + * @instance + * @returns {Object.} JSON object + */ + EnumOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumOptions + * @function getTypeUrl + * @memberof google.protobuf.EnumOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumOptions"; + }; + + return EnumOptions; + })(); + + protobuf.EnumValueOptions = (function() { + + /** + * Properties of an EnumValueOptions. + * @memberof google.protobuf + * @interface IEnumValueOptions + * @property {boolean|null} [deprecated] EnumValueOptions deprecated + * @property {google.protobuf.IFeatureSet|null} [features] EnumValueOptions features + * @property {boolean|null} [debugRedact] EnumValueOptions debugRedact + * @property {Array.|null} [uninterpretedOption] EnumValueOptions uninterpretedOption + */ + + /** + * Constructs a new EnumValueOptions. + * @memberof google.protobuf + * @classdesc Represents an EnumValueOptions. + * @implements IEnumValueOptions + * @constructor + * @param {google.protobuf.IEnumValueOptions=} [properties] Properties to set + */ + function EnumValueOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumValueOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.deprecated = false; + + /** + * EnumValueOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.features = null; + + /** + * EnumValueOptions debugRedact. + * @member {boolean} debugRedact + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.debugRedact = false; + + /** + * EnumValueOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumValueOptions} EnumValueOptions + */ + EnumValueOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumValueOptions) + return object; + var message = new $root.google.protobuf.EnumValueOptions(); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.debugRedact != null) + message.debugRedact = Boolean(object.debugRedact); + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.EnumValueOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {google.protobuf.EnumValueOptions} message EnumValueOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumValueOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.deprecated = false; + object.features = null; + object.debugRedact = false; + } + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) + object.debugRedact = message.debugRedact; + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this EnumValueOptions to JSON. + * @function toJSON + * @memberof google.protobuf.EnumValueOptions + * @instance + * @returns {Object.} JSON object + */ + EnumValueOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumValueOptions + * @function getTypeUrl + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumValueOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumValueOptions"; + }; + + return EnumValueOptions; + })(); + + protobuf.ServiceOptions = (function() { + + /** + * Properties of a ServiceOptions. + * @memberof google.protobuf + * @interface IServiceOptions + * @property {google.protobuf.IFeatureSet|null} [features] ServiceOptions features + * @property {boolean|null} [deprecated] ServiceOptions deprecated + * @property {Array.|null} [uninterpretedOption] ServiceOptions uninterpretedOption + * @property {string|null} [".google.api.defaultHost"] ServiceOptions .google.api.defaultHost + * @property {string|null} [".google.api.oauthScopes"] ServiceOptions .google.api.oauthScopes + * @property {string|null} [".google.api.apiVersion"] ServiceOptions .google.api.apiVersion + */ + + /** + * Constructs a new ServiceOptions. + * @memberof google.protobuf + * @classdesc Represents a ServiceOptions. + * @implements IServiceOptions + * @constructor + * @param {google.protobuf.IServiceOptions=} [properties] Properties to set + */ + function ServiceOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ServiceOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype.features = null; + + /** + * ServiceOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype.deprecated = false; + + /** + * ServiceOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * ServiceOptions .google.api.defaultHost. + * @member {string} .google.api.defaultHost + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype[".google.api.defaultHost"] = ""; + + /** + * ServiceOptions .google.api.oauthScopes. + * @member {string} .google.api.oauthScopes + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype[".google.api.oauthScopes"] = ""; + + /** + * ServiceOptions .google.api.apiVersion. + * @member {string} .google.api.apiVersion + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype[".google.api.apiVersion"] = ""; + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ServiceOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ServiceOptions} ServiceOptions + */ + ServiceOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ServiceOptions) + return object; + var message = new $root.google.protobuf.ServiceOptions(); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.ServiceOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.ServiceOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.ServiceOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.defaultHost"] != null) + message[".google.api.defaultHost"] = String(object[".google.api.defaultHost"]); + if (object[".google.api.oauthScopes"] != null) + message[".google.api.oauthScopes"] = String(object[".google.api.oauthScopes"]); + if (object[".google.api.apiVersion"] != null) + message[".google.api.apiVersion"] = String(object[".google.api.apiVersion"]); + return message; + }; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ServiceOptions + * @static + * @param {google.protobuf.ServiceOptions} message ServiceOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ServiceOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.deprecated = false; + object.features = null; + object[".google.api.defaultHost"] = ""; + object[".google.api.oauthScopes"] = ""; + object[".google.api.apiVersion"] = ""; + } + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.defaultHost"] != null && message.hasOwnProperty(".google.api.defaultHost")) + object[".google.api.defaultHost"] = message[".google.api.defaultHost"]; + if (message[".google.api.oauthScopes"] != null && message.hasOwnProperty(".google.api.oauthScopes")) + object[".google.api.oauthScopes"] = message[".google.api.oauthScopes"]; + if (message[".google.api.apiVersion"] != null && message.hasOwnProperty(".google.api.apiVersion")) + object[".google.api.apiVersion"] = message[".google.api.apiVersion"]; + return object; + }; + + /** + * Converts this ServiceOptions to JSON. + * @function toJSON + * @memberof google.protobuf.ServiceOptions + * @instance + * @returns {Object.} JSON object + */ + ServiceOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ServiceOptions + * @function getTypeUrl + * @memberof google.protobuf.ServiceOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ServiceOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ServiceOptions"; + }; + + return ServiceOptions; + })(); + + protobuf.MethodOptions = (function() { + + /** + * Properties of a MethodOptions. + * @memberof google.protobuf + * @interface IMethodOptions + * @property {boolean|null} [deprecated] MethodOptions deprecated + * @property {google.protobuf.MethodOptions.IdempotencyLevel|null} [idempotencyLevel] MethodOptions idempotencyLevel + * @property {google.protobuf.IFeatureSet|null} [features] MethodOptions features + * @property {Array.|null} [uninterpretedOption] MethodOptions uninterpretedOption + * @property {google.api.IHttpRule|null} [".google.api.http"] MethodOptions .google.api.http + * @property {Array.|null} [".google.api.methodSignature"] MethodOptions .google.api.methodSignature + * @property {google.api.IRoutingRule|null} [".google.api.routing"] MethodOptions .google.api.routing + * @property {google.longrunning.IOperationInfo|null} [".google.longrunning.operationInfo"] MethodOptions .google.longrunning.operationInfo + */ + + /** + * Constructs a new MethodOptions. + * @memberof google.protobuf + * @classdesc Represents a MethodOptions. + * @implements IMethodOptions + * @constructor + * @param {google.protobuf.IMethodOptions=} [properties] Properties to set + */ + function MethodOptions(properties) { + this.uninterpretedOption = []; + this[".google.api.methodSignature"] = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MethodOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.deprecated = false; + + /** + * MethodOptions idempotencyLevel. + * @member {google.protobuf.MethodOptions.IdempotencyLevel} idempotencyLevel + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.idempotencyLevel = 0; + + /** + * MethodOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.features = null; + + /** + * MethodOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * MethodOptions .google.api.http. + * @member {google.api.IHttpRule|null|undefined} .google.api.http + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.api.http"] = null; + + /** + * MethodOptions .google.api.methodSignature. + * @member {Array.} .google.api.methodSignature + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.api.methodSignature"] = $util.emptyArray; + + /** + * MethodOptions .google.api.routing. + * @member {google.api.IRoutingRule|null|undefined} .google.api.routing + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.api.routing"] = null; + + /** + * MethodOptions .google.longrunning.operationInfo. + * @member {google.longrunning.IOperationInfo|null|undefined} .google.longrunning.operationInfo + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.longrunning.operationInfo"] = null; + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.MethodOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.MethodOptions} MethodOptions + */ + MethodOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.MethodOptions) + return object; + var message = new $root.google.protobuf.MethodOptions(); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + switch (object.idempotencyLevel) { + default: + if (typeof object.idempotencyLevel === "number") { + message.idempotencyLevel = object.idempotencyLevel; + break; + } + break; + case "IDEMPOTENCY_UNKNOWN": + case 0: + message.idempotencyLevel = 0; + break; + case "NO_SIDE_EFFECTS": + case 1: + message.idempotencyLevel = 1; + break; + case "IDEMPOTENT": + case 2: + message.idempotencyLevel = 2; + break; + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.MethodOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.MethodOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.MethodOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.http"] != null) { + if (typeof object[".google.api.http"] !== "object") + throw TypeError(".google.protobuf.MethodOptions..google.api.http: object expected"); + message[".google.api.http"] = $root.google.api.HttpRule.fromObject(object[".google.api.http"]); + } + if (object[".google.api.methodSignature"]) { + if (!Array.isArray(object[".google.api.methodSignature"])) + throw TypeError(".google.protobuf.MethodOptions..google.api.methodSignature: array expected"); + message[".google.api.methodSignature"] = []; + for (var i = 0; i < object[".google.api.methodSignature"].length; ++i) + message[".google.api.methodSignature"][i] = String(object[".google.api.methodSignature"][i]); + } + if (object[".google.api.routing"] != null) { + if (typeof object[".google.api.routing"] !== "object") + throw TypeError(".google.protobuf.MethodOptions..google.api.routing: object expected"); + message[".google.api.routing"] = $root.google.api.RoutingRule.fromObject(object[".google.api.routing"]); + } + if (object[".google.longrunning.operationInfo"] != null) { + if (typeof object[".google.longrunning.operationInfo"] !== "object") + throw TypeError(".google.protobuf.MethodOptions..google.longrunning.operationInfo: object expected"); + message[".google.longrunning.operationInfo"] = $root.google.longrunning.OperationInfo.fromObject(object[".google.longrunning.operationInfo"]); + } + return message; + }; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.MethodOptions + * @static + * @param {google.protobuf.MethodOptions} message MethodOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MethodOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.uninterpretedOption = []; + object[".google.api.methodSignature"] = []; + } + if (options.defaults) { + object.deprecated = false; + object.idempotencyLevel = options.enums === String ? "IDEMPOTENCY_UNKNOWN" : 0; + object.features = null; + object[".google.longrunning.operationInfo"] = null; + object[".google.api.http"] = null; + object[".google.api.routing"] = null; + } + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.idempotencyLevel != null && message.hasOwnProperty("idempotencyLevel")) + object.idempotencyLevel = options.enums === String ? $root.google.protobuf.MethodOptions.IdempotencyLevel[message.idempotencyLevel] === undefined ? message.idempotencyLevel : $root.google.protobuf.MethodOptions.IdempotencyLevel[message.idempotencyLevel] : message.idempotencyLevel; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.longrunning.operationInfo"] != null && message.hasOwnProperty(".google.longrunning.operationInfo")) + object[".google.longrunning.operationInfo"] = $root.google.longrunning.OperationInfo.toObject(message[".google.longrunning.operationInfo"], options); + if (message[".google.api.methodSignature"] && message[".google.api.methodSignature"].length) { + object[".google.api.methodSignature"] = []; + for (var j = 0; j < message[".google.api.methodSignature"].length; ++j) + object[".google.api.methodSignature"][j] = message[".google.api.methodSignature"][j]; + } + if (message[".google.api.http"] != null && message.hasOwnProperty(".google.api.http")) + object[".google.api.http"] = $root.google.api.HttpRule.toObject(message[".google.api.http"], options); + if (message[".google.api.routing"] != null && message.hasOwnProperty(".google.api.routing")) + object[".google.api.routing"] = $root.google.api.RoutingRule.toObject(message[".google.api.routing"], options); + return object; + }; + + /** + * Converts this MethodOptions to JSON. + * @function toJSON + * @memberof google.protobuf.MethodOptions + * @instance + * @returns {Object.} JSON object + */ + MethodOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MethodOptions + * @function getTypeUrl + * @memberof google.protobuf.MethodOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MethodOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.MethodOptions"; + }; + + /** + * IdempotencyLevel enum. + * @name google.protobuf.MethodOptions.IdempotencyLevel + * @enum {string} + * @property {string} IDEMPOTENCY_UNKNOWN=IDEMPOTENCY_UNKNOWN IDEMPOTENCY_UNKNOWN value + * @property {string} NO_SIDE_EFFECTS=NO_SIDE_EFFECTS NO_SIDE_EFFECTS value + * @property {string} IDEMPOTENT=IDEMPOTENT IDEMPOTENT value + */ + MethodOptions.IdempotencyLevel = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; + values[valuesById[1] = "NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; + values[valuesById[2] = "IDEMPOTENT"] = "IDEMPOTENT"; + return values; + })(); + + return MethodOptions; + })(); + + protobuf.UninterpretedOption = (function() { + + /** + * Properties of an UninterpretedOption. + * @memberof google.protobuf + * @interface IUninterpretedOption + * @property {Array.|null} [name] UninterpretedOption name + * @property {string|null} [identifierValue] UninterpretedOption identifierValue + * @property {number|string|null} [positiveIntValue] UninterpretedOption positiveIntValue + * @property {number|string|null} [negativeIntValue] UninterpretedOption negativeIntValue + * @property {number|null} [doubleValue] UninterpretedOption doubleValue + * @property {Uint8Array|null} [stringValue] UninterpretedOption stringValue + * @property {string|null} [aggregateValue] UninterpretedOption aggregateValue + */ + + /** + * Constructs a new UninterpretedOption. + * @memberof google.protobuf + * @classdesc Represents an UninterpretedOption. + * @implements IUninterpretedOption + * @constructor + * @param {google.protobuf.IUninterpretedOption=} [properties] Properties to set + */ + function UninterpretedOption(properties) { + this.name = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UninterpretedOption name. + * @member {Array.} name + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.name = $util.emptyArray; + + /** + * UninterpretedOption identifierValue. + * @member {string} identifierValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.identifierValue = ""; + + /** + * UninterpretedOption positiveIntValue. + * @member {number|string} positiveIntValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.positiveIntValue = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * UninterpretedOption negativeIntValue. + * @member {number|string} negativeIntValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.negativeIntValue = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * UninterpretedOption doubleValue. + * @member {number} doubleValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.doubleValue = 0; + + /** + * UninterpretedOption stringValue. + * @member {Uint8Array} stringValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.stringValue = $util.newBuffer([]); + + /** + * UninterpretedOption aggregateValue. + * @member {string} aggregateValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.aggregateValue = ""; + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.UninterpretedOption} UninterpretedOption + */ + UninterpretedOption.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UninterpretedOption) + return object; + var message = new $root.google.protobuf.UninterpretedOption(); + if (object.name) { + if (!Array.isArray(object.name)) + throw TypeError(".google.protobuf.UninterpretedOption.name: array expected"); + message.name = []; + for (var i = 0; i < object.name.length; ++i) { + if (typeof object.name[i] !== "object") + throw TypeError(".google.protobuf.UninterpretedOption.name: object expected"); + message.name[i] = $root.google.protobuf.UninterpretedOption.NamePart.fromObject(object.name[i]); + } + } + if (object.identifierValue != null) + message.identifierValue = String(object.identifierValue); + if (object.positiveIntValue != null) + if ($util.Long) + (message.positiveIntValue = $util.Long.fromValue(object.positiveIntValue)).unsigned = true; + else if (typeof object.positiveIntValue === "string") + message.positiveIntValue = parseInt(object.positiveIntValue, 10); + else if (typeof object.positiveIntValue === "number") + message.positiveIntValue = object.positiveIntValue; + else if (typeof object.positiveIntValue === "object") + message.positiveIntValue = new $util.LongBits(object.positiveIntValue.low >>> 0, object.positiveIntValue.high >>> 0).toNumber(true); + if (object.negativeIntValue != null) + if ($util.Long) + (message.negativeIntValue = $util.Long.fromValue(object.negativeIntValue)).unsigned = false; + else if (typeof object.negativeIntValue === "string") + message.negativeIntValue = parseInt(object.negativeIntValue, 10); + else if (typeof object.negativeIntValue === "number") + message.negativeIntValue = object.negativeIntValue; + else if (typeof object.negativeIntValue === "object") + message.negativeIntValue = new $util.LongBits(object.negativeIntValue.low >>> 0, object.negativeIntValue.high >>> 0).toNumber(); + if (object.doubleValue != null) + message.doubleValue = Number(object.doubleValue); + if (object.stringValue != null) + if (typeof object.stringValue === "string") + $util.base64.decode(object.stringValue, message.stringValue = $util.newBuffer($util.base64.length(object.stringValue)), 0); + else if (object.stringValue.length >= 0) + message.stringValue = object.stringValue; + if (object.aggregateValue != null) + message.aggregateValue = String(object.aggregateValue); + return message; + }; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {google.protobuf.UninterpretedOption} message UninterpretedOption + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UninterpretedOption.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.name = []; + if (options.defaults) { + object.identifierValue = ""; + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.positiveIntValue = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.positiveIntValue = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.negativeIntValue = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.negativeIntValue = options.longs === String ? "0" : 0; + object.doubleValue = 0; + if (options.bytes === String) + object.stringValue = ""; + else { + object.stringValue = []; + if (options.bytes !== Array) + object.stringValue = $util.newBuffer(object.stringValue); + } + object.aggregateValue = ""; + } + if (message.name && message.name.length) { + object.name = []; + for (var j = 0; j < message.name.length; ++j) + object.name[j] = $root.google.protobuf.UninterpretedOption.NamePart.toObject(message.name[j], options); + } + if (message.identifierValue != null && message.hasOwnProperty("identifierValue")) + object.identifierValue = message.identifierValue; + if (message.positiveIntValue != null && message.hasOwnProperty("positiveIntValue")) + if (typeof message.positiveIntValue === "number") + object.positiveIntValue = options.longs === String ? String(message.positiveIntValue) : message.positiveIntValue; + else + object.positiveIntValue = options.longs === String ? $util.Long.prototype.toString.call(message.positiveIntValue) : options.longs === Number ? new $util.LongBits(message.positiveIntValue.low >>> 0, message.positiveIntValue.high >>> 0).toNumber(true) : message.positiveIntValue; + if (message.negativeIntValue != null && message.hasOwnProperty("negativeIntValue")) + if (typeof message.negativeIntValue === "number") + object.negativeIntValue = options.longs === String ? String(message.negativeIntValue) : message.negativeIntValue; + else + object.negativeIntValue = options.longs === String ? $util.Long.prototype.toString.call(message.negativeIntValue) : options.longs === Number ? new $util.LongBits(message.negativeIntValue.low >>> 0, message.negativeIntValue.high >>> 0).toNumber() : message.negativeIntValue; + if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) + object.doubleValue = options.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue; + if (message.stringValue != null && message.hasOwnProperty("stringValue")) + object.stringValue = options.bytes === String ? $util.base64.encode(message.stringValue, 0, message.stringValue.length) : options.bytes === Array ? Array.prototype.slice.call(message.stringValue) : message.stringValue; + if (message.aggregateValue != null && message.hasOwnProperty("aggregateValue")) + object.aggregateValue = message.aggregateValue; + return object; + }; + + /** + * Converts this UninterpretedOption to JSON. + * @function toJSON + * @memberof google.protobuf.UninterpretedOption + * @instance + * @returns {Object.} JSON object + */ + UninterpretedOption.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UninterpretedOption + * @function getTypeUrl + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UninterpretedOption.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.UninterpretedOption"; + }; + + UninterpretedOption.NamePart = (function() { + + /** + * Properties of a NamePart. + * @memberof google.protobuf.UninterpretedOption + * @interface INamePart + * @property {string} namePart NamePart namePart + * @property {boolean} isExtension NamePart isExtension + */ + + /** + * Constructs a new NamePart. + * @memberof google.protobuf.UninterpretedOption + * @classdesc Represents a NamePart. + * @implements INamePart + * @constructor + * @param {google.protobuf.UninterpretedOption.INamePart=} [properties] Properties to set + */ + function NamePart(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * NamePart namePart. + * @member {string} namePart + * @memberof google.protobuf.UninterpretedOption.NamePart + * @instance + */ + NamePart.prototype.namePart = ""; + + /** + * NamePart isExtension. + * @member {boolean} isExtension + * @memberof google.protobuf.UninterpretedOption.NamePart + * @instance + */ + NamePart.prototype.isExtension = false; + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.UninterpretedOption.NamePart} NamePart + */ + NamePart.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UninterpretedOption.NamePart) + return object; + var message = new $root.google.protobuf.UninterpretedOption.NamePart(); + if (object.namePart != null) + message.namePart = String(object.namePart); + if (object.isExtension != null) + message.isExtension = Boolean(object.isExtension); + return message; + }; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {google.protobuf.UninterpretedOption.NamePart} message NamePart + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + NamePart.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.namePart = ""; + object.isExtension = false; + } + if (message.namePart != null && message.hasOwnProperty("namePart")) + object.namePart = message.namePart; + if (message.isExtension != null && message.hasOwnProperty("isExtension")) + object.isExtension = message.isExtension; + return object; + }; + + /** + * Converts this NamePart to JSON. + * @function toJSON + * @memberof google.protobuf.UninterpretedOption.NamePart + * @instance + * @returns {Object.} JSON object + */ + NamePart.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for NamePart + * @function getTypeUrl + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + NamePart.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.UninterpretedOption.NamePart"; + }; + + return NamePart; + })(); + + return UninterpretedOption; + })(); + + protobuf.FeatureSet = (function() { + + /** + * Properties of a FeatureSet. + * @memberof google.protobuf + * @interface IFeatureSet + * @property {google.protobuf.FeatureSet.FieldPresence|null} [fieldPresence] FeatureSet fieldPresence + * @property {google.protobuf.FeatureSet.EnumType|null} [enumType] FeatureSet enumType + * @property {google.protobuf.FeatureSet.RepeatedFieldEncoding|null} [repeatedFieldEncoding] FeatureSet repeatedFieldEncoding + * @property {google.protobuf.FeatureSet.Utf8Validation|null} [utf8Validation] FeatureSet utf8Validation + * @property {google.protobuf.FeatureSet.MessageEncoding|null} [messageEncoding] FeatureSet messageEncoding + * @property {google.protobuf.FeatureSet.JsonFormat|null} [jsonFormat] FeatureSet jsonFormat + */ + + /** + * Constructs a new FeatureSet. + * @memberof google.protobuf + * @classdesc Represents a FeatureSet. + * @implements IFeatureSet + * @constructor + * @param {google.protobuf.IFeatureSet=} [properties] Properties to set + */ + function FeatureSet(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FeatureSet fieldPresence. + * @member {google.protobuf.FeatureSet.FieldPresence} fieldPresence + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.fieldPresence = 0; + + /** + * FeatureSet enumType. + * @member {google.protobuf.FeatureSet.EnumType} enumType + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.enumType = 0; + + /** + * FeatureSet repeatedFieldEncoding. + * @member {google.protobuf.FeatureSet.RepeatedFieldEncoding} repeatedFieldEncoding + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.repeatedFieldEncoding = 0; + + /** + * FeatureSet utf8Validation. + * @member {google.protobuf.FeatureSet.Utf8Validation} utf8Validation + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.utf8Validation = 0; + + /** + * FeatureSet messageEncoding. + * @member {google.protobuf.FeatureSet.MessageEncoding} messageEncoding + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.messageEncoding = 0; + + /** + * FeatureSet jsonFormat. + * @member {google.protobuf.FeatureSet.JsonFormat} jsonFormat + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.jsonFormat = 0; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSet + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSet} FeatureSet + */ + FeatureSet.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSet) + return object; + var message = new $root.google.protobuf.FeatureSet(); + switch (object.fieldPresence) { + default: + if (typeof object.fieldPresence === "number") { + message.fieldPresence = object.fieldPresence; + break; + } + break; + case "FIELD_PRESENCE_UNKNOWN": + case 0: + message.fieldPresence = 0; + break; + case "EXPLICIT": + case 1: + message.fieldPresence = 1; + break; + case "IMPLICIT": + case 2: + message.fieldPresence = 2; + break; + case "LEGACY_REQUIRED": + case 3: + message.fieldPresence = 3; + break; + } + switch (object.enumType) { + default: + if (typeof object.enumType === "number") { + message.enumType = object.enumType; + break; + } + break; + case "ENUM_TYPE_UNKNOWN": + case 0: + message.enumType = 0; + break; + case "OPEN": + case 1: + message.enumType = 1; + break; + case "CLOSED": + case 2: + message.enumType = 2; + break; + } + switch (object.repeatedFieldEncoding) { + default: + if (typeof object.repeatedFieldEncoding === "number") { + message.repeatedFieldEncoding = object.repeatedFieldEncoding; + break; + } + break; + case "REPEATED_FIELD_ENCODING_UNKNOWN": + case 0: + message.repeatedFieldEncoding = 0; + break; + case "PACKED": + case 1: + message.repeatedFieldEncoding = 1; + break; + case "EXPANDED": + case 2: + message.repeatedFieldEncoding = 2; + break; + } + switch (object.utf8Validation) { + default: + if (typeof object.utf8Validation === "number") { + message.utf8Validation = object.utf8Validation; + break; + } + break; + case "UTF8_VALIDATION_UNKNOWN": + case 0: + message.utf8Validation = 0; + break; + case "VERIFY": + case 2: + message.utf8Validation = 2; + break; + case "NONE": + case 3: + message.utf8Validation = 3; + break; + } + switch (object.messageEncoding) { + default: + if (typeof object.messageEncoding === "number") { + message.messageEncoding = object.messageEncoding; + break; + } + break; + case "MESSAGE_ENCODING_UNKNOWN": + case 0: + message.messageEncoding = 0; + break; + case "LENGTH_PREFIXED": + case 1: + message.messageEncoding = 1; + break; + case "DELIMITED": + case 2: + message.messageEncoding = 2; + break; + } + switch (object.jsonFormat) { + default: + if (typeof object.jsonFormat === "number") { + message.jsonFormat = object.jsonFormat; + break; + } + break; + case "JSON_FORMAT_UNKNOWN": + case 0: + message.jsonFormat = 0; + break; + case "ALLOW": + case 1: + message.jsonFormat = 1; + break; + case "LEGACY_BEST_EFFORT": + case 2: + message.jsonFormat = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSet + * @static + * @param {google.protobuf.FeatureSet} message FeatureSet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FeatureSet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.fieldPresence = options.enums === String ? "FIELD_PRESENCE_UNKNOWN" : 0; + object.enumType = options.enums === String ? "ENUM_TYPE_UNKNOWN" : 0; + object.repeatedFieldEncoding = options.enums === String ? "REPEATED_FIELD_ENCODING_UNKNOWN" : 0; + object.utf8Validation = options.enums === String ? "UTF8_VALIDATION_UNKNOWN" : 0; + object.messageEncoding = options.enums === String ? "MESSAGE_ENCODING_UNKNOWN" : 0; + object.jsonFormat = options.enums === String ? "JSON_FORMAT_UNKNOWN" : 0; + } + if (message.fieldPresence != null && message.hasOwnProperty("fieldPresence")) + object.fieldPresence = options.enums === String ? $root.google.protobuf.FeatureSet.FieldPresence[message.fieldPresence] === undefined ? message.fieldPresence : $root.google.protobuf.FeatureSet.FieldPresence[message.fieldPresence] : message.fieldPresence; + if (message.enumType != null && message.hasOwnProperty("enumType")) + object.enumType = options.enums === String ? $root.google.protobuf.FeatureSet.EnumType[message.enumType] === undefined ? message.enumType : $root.google.protobuf.FeatureSet.EnumType[message.enumType] : message.enumType; + if (message.repeatedFieldEncoding != null && message.hasOwnProperty("repeatedFieldEncoding")) + object.repeatedFieldEncoding = options.enums === String ? $root.google.protobuf.FeatureSet.RepeatedFieldEncoding[message.repeatedFieldEncoding] === undefined ? message.repeatedFieldEncoding : $root.google.protobuf.FeatureSet.RepeatedFieldEncoding[message.repeatedFieldEncoding] : message.repeatedFieldEncoding; + if (message.utf8Validation != null && message.hasOwnProperty("utf8Validation")) + object.utf8Validation = options.enums === String ? $root.google.protobuf.FeatureSet.Utf8Validation[message.utf8Validation] === undefined ? message.utf8Validation : $root.google.protobuf.FeatureSet.Utf8Validation[message.utf8Validation] : message.utf8Validation; + if (message.messageEncoding != null && message.hasOwnProperty("messageEncoding")) + object.messageEncoding = options.enums === String ? $root.google.protobuf.FeatureSet.MessageEncoding[message.messageEncoding] === undefined ? message.messageEncoding : $root.google.protobuf.FeatureSet.MessageEncoding[message.messageEncoding] : message.messageEncoding; + if (message.jsonFormat != null && message.hasOwnProperty("jsonFormat")) + object.jsonFormat = options.enums === String ? $root.google.protobuf.FeatureSet.JsonFormat[message.jsonFormat] === undefined ? message.jsonFormat : $root.google.protobuf.FeatureSet.JsonFormat[message.jsonFormat] : message.jsonFormat; + return object; + }; + + /** + * Converts this FeatureSet to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSet + * @instance + * @returns {Object.} JSON object + */ + FeatureSet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FeatureSet + * @function getTypeUrl + * @memberof google.protobuf.FeatureSet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FeatureSet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSet"; + }; + + /** + * FieldPresence enum. + * @name google.protobuf.FeatureSet.FieldPresence + * @enum {string} + * @property {string} FIELD_PRESENCE_UNKNOWN=FIELD_PRESENCE_UNKNOWN FIELD_PRESENCE_UNKNOWN value + * @property {string} EXPLICIT=EXPLICIT EXPLICIT value + * @property {string} IMPLICIT=IMPLICIT IMPLICIT value + * @property {string} LEGACY_REQUIRED=LEGACY_REQUIRED LEGACY_REQUIRED value + */ + FeatureSet.FieldPresence = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "FIELD_PRESENCE_UNKNOWN"] = "FIELD_PRESENCE_UNKNOWN"; + values[valuesById[1] = "EXPLICIT"] = "EXPLICIT"; + values[valuesById[2] = "IMPLICIT"] = "IMPLICIT"; + values[valuesById[3] = "LEGACY_REQUIRED"] = "LEGACY_REQUIRED"; + return values; + })(); + + /** + * EnumType enum. + * @name google.protobuf.FeatureSet.EnumType + * @enum {string} + * @property {string} ENUM_TYPE_UNKNOWN=ENUM_TYPE_UNKNOWN ENUM_TYPE_UNKNOWN value + * @property {string} OPEN=OPEN OPEN value + * @property {string} CLOSED=CLOSED CLOSED value + */ + FeatureSet.EnumType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ENUM_TYPE_UNKNOWN"] = "ENUM_TYPE_UNKNOWN"; + values[valuesById[1] = "OPEN"] = "OPEN"; + values[valuesById[2] = "CLOSED"] = "CLOSED"; + return values; + })(); + + /** + * RepeatedFieldEncoding enum. + * @name google.protobuf.FeatureSet.RepeatedFieldEncoding + * @enum {string} + * @property {string} REPEATED_FIELD_ENCODING_UNKNOWN=REPEATED_FIELD_ENCODING_UNKNOWN REPEATED_FIELD_ENCODING_UNKNOWN value + * @property {string} PACKED=PACKED PACKED value + * @property {string} EXPANDED=EXPANDED EXPANDED value + */ + FeatureSet.RepeatedFieldEncoding = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "REPEATED_FIELD_ENCODING_UNKNOWN"] = "REPEATED_FIELD_ENCODING_UNKNOWN"; + values[valuesById[1] = "PACKED"] = "PACKED"; + values[valuesById[2] = "EXPANDED"] = "EXPANDED"; + return values; + })(); + + /** + * Utf8Validation enum. + * @name google.protobuf.FeatureSet.Utf8Validation + * @enum {string} + * @property {string} UTF8_VALIDATION_UNKNOWN=UTF8_VALIDATION_UNKNOWN UTF8_VALIDATION_UNKNOWN value + * @property {string} VERIFY=VERIFY VERIFY value + * @property {string} NONE=NONE NONE value + */ + FeatureSet.Utf8Validation = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UTF8_VALIDATION_UNKNOWN"] = "UTF8_VALIDATION_UNKNOWN"; + values[valuesById[2] = "VERIFY"] = "VERIFY"; + values[valuesById[3] = "NONE"] = "NONE"; + return values; + })(); + + /** + * MessageEncoding enum. + * @name google.protobuf.FeatureSet.MessageEncoding + * @enum {string} + * @property {string} MESSAGE_ENCODING_UNKNOWN=MESSAGE_ENCODING_UNKNOWN MESSAGE_ENCODING_UNKNOWN value + * @property {string} LENGTH_PREFIXED=LENGTH_PREFIXED LENGTH_PREFIXED value + * @property {string} DELIMITED=DELIMITED DELIMITED value + */ + FeatureSet.MessageEncoding = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "MESSAGE_ENCODING_UNKNOWN"] = "MESSAGE_ENCODING_UNKNOWN"; + values[valuesById[1] = "LENGTH_PREFIXED"] = "LENGTH_PREFIXED"; + values[valuesById[2] = "DELIMITED"] = "DELIMITED"; + return values; + })(); + + /** + * JsonFormat enum. + * @name google.protobuf.FeatureSet.JsonFormat + * @enum {string} + * @property {string} JSON_FORMAT_UNKNOWN=JSON_FORMAT_UNKNOWN JSON_FORMAT_UNKNOWN value + * @property {string} ALLOW=ALLOW ALLOW value + * @property {string} LEGACY_BEST_EFFORT=LEGACY_BEST_EFFORT LEGACY_BEST_EFFORT value + */ + FeatureSet.JsonFormat = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "JSON_FORMAT_UNKNOWN"] = "JSON_FORMAT_UNKNOWN"; + values[valuesById[1] = "ALLOW"] = "ALLOW"; + values[valuesById[2] = "LEGACY_BEST_EFFORT"] = "LEGACY_BEST_EFFORT"; + return values; + })(); + + return FeatureSet; + })(); + + protobuf.FeatureSetDefaults = (function() { + + /** + * Properties of a FeatureSetDefaults. + * @memberof google.protobuf + * @interface IFeatureSetDefaults + * @property {Array.|null} [defaults] FeatureSetDefaults defaults + * @property {google.protobuf.Edition|null} [minimumEdition] FeatureSetDefaults minimumEdition + * @property {google.protobuf.Edition|null} [maximumEdition] FeatureSetDefaults maximumEdition + */ + + /** + * Constructs a new FeatureSetDefaults. + * @memberof google.protobuf + * @classdesc Represents a FeatureSetDefaults. + * @implements IFeatureSetDefaults + * @constructor + * @param {google.protobuf.IFeatureSetDefaults=} [properties] Properties to set + */ + function FeatureSetDefaults(properties) { + this.defaults = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FeatureSetDefaults defaults. + * @member {Array.} defaults + * @memberof google.protobuf.FeatureSetDefaults + * @instance + */ + FeatureSetDefaults.prototype.defaults = $util.emptyArray; + + /** + * FeatureSetDefaults minimumEdition. + * @member {google.protobuf.Edition} minimumEdition + * @memberof google.protobuf.FeatureSetDefaults + * @instance + */ + FeatureSetDefaults.prototype.minimumEdition = 0; + + /** + * FeatureSetDefaults maximumEdition. + * @member {google.protobuf.Edition} maximumEdition + * @memberof google.protobuf.FeatureSetDefaults + * @instance + */ + FeatureSetDefaults.prototype.maximumEdition = 0; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSetDefaults} FeatureSetDefaults + */ + FeatureSetDefaults.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSetDefaults) + return object; + var message = new $root.google.protobuf.FeatureSetDefaults(); + if (object.defaults) { + if (!Array.isArray(object.defaults)) + throw TypeError(".google.protobuf.FeatureSetDefaults.defaults: array expected"); + message.defaults = []; + for (var i = 0; i < object.defaults.length; ++i) { + if (typeof object.defaults[i] !== "object") + throw TypeError(".google.protobuf.FeatureSetDefaults.defaults: object expected"); + message.defaults[i] = $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.fromObject(object.defaults[i]); + } + } + switch (object.minimumEdition) { + default: + if (typeof object.minimumEdition === "number") { + message.minimumEdition = object.minimumEdition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.minimumEdition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.minimumEdition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.minimumEdition = 999; + break; + case "EDITION_2023": + case 1000: + message.minimumEdition = 1000; + break; + case "EDITION_2024": + case 1001: + message.minimumEdition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.minimumEdition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.minimumEdition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.minimumEdition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.minimumEdition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.minimumEdition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.minimumEdition = 2147483647; + break; + } + switch (object.maximumEdition) { + default: + if (typeof object.maximumEdition === "number") { + message.maximumEdition = object.maximumEdition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.maximumEdition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.maximumEdition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.maximumEdition = 999; + break; + case "EDITION_2023": + case 1000: + message.maximumEdition = 1000; + break; + case "EDITION_2024": + case 1001: + message.maximumEdition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.maximumEdition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.maximumEdition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.maximumEdition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.maximumEdition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.maximumEdition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.maximumEdition = 2147483647; + break; + } + return message; + }; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {google.protobuf.FeatureSetDefaults} message FeatureSetDefaults + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FeatureSetDefaults.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.defaults = []; + if (options.defaults) { + object.minimumEdition = options.enums === String ? "EDITION_UNKNOWN" : 0; + object.maximumEdition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.defaults && message.defaults.length) { + object.defaults = []; + for (var j = 0; j < message.defaults.length; ++j) + object.defaults[j] = $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.toObject(message.defaults[j], options); + } + if (message.minimumEdition != null && message.hasOwnProperty("minimumEdition")) + object.minimumEdition = options.enums === String ? $root.google.protobuf.Edition[message.minimumEdition] === undefined ? message.minimumEdition : $root.google.protobuf.Edition[message.minimumEdition] : message.minimumEdition; + if (message.maximumEdition != null && message.hasOwnProperty("maximumEdition")) + object.maximumEdition = options.enums === String ? $root.google.protobuf.Edition[message.maximumEdition] === undefined ? message.maximumEdition : $root.google.protobuf.Edition[message.maximumEdition] : message.maximumEdition; + return object; + }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSetDefaults + * @instance + * @returns {Object.} JSON object + */ + FeatureSetDefaults.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FeatureSetDefaults + * @function getTypeUrl + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FeatureSetDefaults.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSetDefaults"; + }; + + FeatureSetDefaults.FeatureSetEditionDefault = (function() { + + /** + * Properties of a FeatureSetEditionDefault. + * @memberof google.protobuf.FeatureSetDefaults + * @interface IFeatureSetEditionDefault + * @property {google.protobuf.Edition|null} [edition] FeatureSetEditionDefault edition + * @property {google.protobuf.IFeatureSet|null} [features] FeatureSetEditionDefault features + */ + + /** + * Constructs a new FeatureSetEditionDefault. + * @memberof google.protobuf.FeatureSetDefaults + * @classdesc Represents a FeatureSetEditionDefault. + * @implements IFeatureSetEditionDefault + * @constructor + * @param {google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault=} [properties] Properties to set + */ + function FeatureSetEditionDefault(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FeatureSetEditionDefault edition. + * @member {google.protobuf.Edition} edition + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @instance + */ + FeatureSetEditionDefault.prototype.edition = 0; + + /** + * FeatureSetEditionDefault features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @instance + */ + FeatureSetEditionDefault.prototype.features = null; + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault} FeatureSetEditionDefault + */ + FeatureSetEditionDefault.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault) + return object; + var message = new $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault(); + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.edition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.edition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.edition = 999; + break; + case "EDITION_2023": + case 1000: + message.edition = 1000; + break; + case "EDITION_2024": + case 1001: + message.edition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.edition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.edition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.edition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.edition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.edition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.edition = 2147483647; + break; + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + return message; + }; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault} message FeatureSetEditionDefault + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FeatureSetEditionDefault.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.features = null; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; + return object; + }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @instance + * @returns {Object.} JSON object + */ + FeatureSetEditionDefault.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @function getTypeUrl + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FeatureSetEditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault"; + }; + + return FeatureSetEditionDefault; + })(); + + return FeatureSetDefaults; + })(); + + protobuf.SourceCodeInfo = (function() { + + /** + * Properties of a SourceCodeInfo. + * @memberof google.protobuf + * @interface ISourceCodeInfo + * @property {Array.|null} [location] SourceCodeInfo location + */ + + /** + * Constructs a new SourceCodeInfo. + * @memberof google.protobuf + * @classdesc Represents a SourceCodeInfo. + * @implements ISourceCodeInfo + * @constructor + * @param {google.protobuf.ISourceCodeInfo=} [properties] Properties to set + */ + function SourceCodeInfo(properties) { + this.location = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SourceCodeInfo location. + * @member {Array.} location + * @memberof google.protobuf.SourceCodeInfo + * @instance + */ + SourceCodeInfo.prototype.location = $util.emptyArray; + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.SourceCodeInfo} SourceCodeInfo + */ + SourceCodeInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.SourceCodeInfo) + return object; + var message = new $root.google.protobuf.SourceCodeInfo(); + if (object.location) { + if (!Array.isArray(object.location)) + throw TypeError(".google.protobuf.SourceCodeInfo.location: array expected"); + message.location = []; + for (var i = 0; i < object.location.length; ++i) { + if (typeof object.location[i] !== "object") + throw TypeError(".google.protobuf.SourceCodeInfo.location: object expected"); + message.location[i] = $root.google.protobuf.SourceCodeInfo.Location.fromObject(object.location[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {google.protobuf.SourceCodeInfo} message SourceCodeInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SourceCodeInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.location = []; + if (message.location && message.location.length) { + object.location = []; + for (var j = 0; j < message.location.length; ++j) + object.location[j] = $root.google.protobuf.SourceCodeInfo.Location.toObject(message.location[j], options); + } + return object; + }; + + /** + * Converts this SourceCodeInfo to JSON. + * @function toJSON + * @memberof google.protobuf.SourceCodeInfo + * @instance + * @returns {Object.} JSON object + */ + SourceCodeInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SourceCodeInfo + * @function getTypeUrl + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SourceCodeInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.SourceCodeInfo"; + }; + + SourceCodeInfo.Location = (function() { + + /** + * Properties of a Location. + * @memberof google.protobuf.SourceCodeInfo + * @interface ILocation + * @property {Array.|null} [path] Location path + * @property {Array.|null} [span] Location span + * @property {string|null} [leadingComments] Location leadingComments + * @property {string|null} [trailingComments] Location trailingComments + * @property {Array.|null} [leadingDetachedComments] Location leadingDetachedComments + */ + + /** + * Constructs a new Location. + * @memberof google.protobuf.SourceCodeInfo + * @classdesc Represents a Location. + * @implements ILocation + * @constructor + * @param {google.protobuf.SourceCodeInfo.ILocation=} [properties] Properties to set + */ + function Location(properties) { + this.path = []; + this.span = []; + this.leadingDetachedComments = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Location path. + * @member {Array.} path + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.path = $util.emptyArray; + + /** + * Location span. + * @member {Array.} span + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.span = $util.emptyArray; + + /** + * Location leadingComments. + * @member {string} leadingComments + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.leadingComments = ""; + + /** + * Location trailingComments. + * @member {string} trailingComments + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.trailingComments = ""; + + /** + * Location leadingDetachedComments. + * @member {Array.} leadingDetachedComments + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.leadingDetachedComments = $util.emptyArray; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.SourceCodeInfo.Location} Location + */ + Location.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.SourceCodeInfo.Location) + return object; + var message = new $root.google.protobuf.SourceCodeInfo.Location(); + if (object.path) { + if (!Array.isArray(object.path)) + throw TypeError(".google.protobuf.SourceCodeInfo.Location.path: array expected"); + message.path = []; + for (var i = 0; i < object.path.length; ++i) + message.path[i] = object.path[i] | 0; + } + if (object.span) { + if (!Array.isArray(object.span)) + throw TypeError(".google.protobuf.SourceCodeInfo.Location.span: array expected"); + message.span = []; + for (var i = 0; i < object.span.length; ++i) + message.span[i] = object.span[i] | 0; + } + if (object.leadingComments != null) + message.leadingComments = String(object.leadingComments); + if (object.trailingComments != null) + message.trailingComments = String(object.trailingComments); + if (object.leadingDetachedComments) { + if (!Array.isArray(object.leadingDetachedComments)) + throw TypeError(".google.protobuf.SourceCodeInfo.Location.leadingDetachedComments: array expected"); + message.leadingDetachedComments = []; + for (var i = 0; i < object.leadingDetachedComments.length; ++i) + message.leadingDetachedComments[i] = String(object.leadingDetachedComments[i]); + } + return message; + }; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {google.protobuf.SourceCodeInfo.Location} message Location + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Location.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.path = []; + object.span = []; + object.leadingDetachedComments = []; + } + if (options.defaults) { + object.leadingComments = ""; + object.trailingComments = ""; + } + if (message.path && message.path.length) { + object.path = []; + for (var j = 0; j < message.path.length; ++j) + object.path[j] = message.path[j]; + } + if (message.span && message.span.length) { + object.span = []; + for (var j = 0; j < message.span.length; ++j) + object.span[j] = message.span[j]; + } + if (message.leadingComments != null && message.hasOwnProperty("leadingComments")) + object.leadingComments = message.leadingComments; + if (message.trailingComments != null && message.hasOwnProperty("trailingComments")) + object.trailingComments = message.trailingComments; + if (message.leadingDetachedComments && message.leadingDetachedComments.length) { + object.leadingDetachedComments = []; + for (var j = 0; j < message.leadingDetachedComments.length; ++j) + object.leadingDetachedComments[j] = message.leadingDetachedComments[j]; + } + return object; + }; + + /** + * Converts this Location to JSON. + * @function toJSON + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + * @returns {Object.} JSON object + */ + Location.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Location + * @function getTypeUrl + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Location.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.SourceCodeInfo.Location"; + }; + + return Location; + })(); + + return SourceCodeInfo; + })(); + + protobuf.GeneratedCodeInfo = (function() { + + /** + * Properties of a GeneratedCodeInfo. + * @memberof google.protobuf + * @interface IGeneratedCodeInfo + * @property {Array.|null} [annotation] GeneratedCodeInfo annotation + */ + + /** + * Constructs a new GeneratedCodeInfo. + * @memberof google.protobuf + * @classdesc Represents a GeneratedCodeInfo. + * @implements IGeneratedCodeInfo + * @constructor + * @param {google.protobuf.IGeneratedCodeInfo=} [properties] Properties to set + */ + function GeneratedCodeInfo(properties) { + this.annotation = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GeneratedCodeInfo annotation. + * @member {Array.} annotation + * @memberof google.protobuf.GeneratedCodeInfo + * @instance + */ + GeneratedCodeInfo.prototype.annotation = $util.emptyArray; + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.GeneratedCodeInfo} GeneratedCodeInfo + */ + GeneratedCodeInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.GeneratedCodeInfo) + return object; + var message = new $root.google.protobuf.GeneratedCodeInfo(); + if (object.annotation) { + if (!Array.isArray(object.annotation)) + throw TypeError(".google.protobuf.GeneratedCodeInfo.annotation: array expected"); + message.annotation = []; + for (var i = 0; i < object.annotation.length; ++i) { + if (typeof object.annotation[i] !== "object") + throw TypeError(".google.protobuf.GeneratedCodeInfo.annotation: object expected"); + message.annotation[i] = $root.google.protobuf.GeneratedCodeInfo.Annotation.fromObject(object.annotation[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {google.protobuf.GeneratedCodeInfo} message GeneratedCodeInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GeneratedCodeInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.annotation = []; + if (message.annotation && message.annotation.length) { + object.annotation = []; + for (var j = 0; j < message.annotation.length; ++j) + object.annotation[j] = $root.google.protobuf.GeneratedCodeInfo.Annotation.toObject(message.annotation[j], options); + } + return object; + }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @function toJSON + * @memberof google.protobuf.GeneratedCodeInfo + * @instance + * @returns {Object.} JSON object + */ + GeneratedCodeInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @function getTypeUrl + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GeneratedCodeInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.GeneratedCodeInfo"; + }; + + GeneratedCodeInfo.Annotation = (function() { + + /** + * Properties of an Annotation. + * @memberof google.protobuf.GeneratedCodeInfo + * @interface IAnnotation + * @property {Array.|null} [path] Annotation path + * @property {string|null} [sourceFile] Annotation sourceFile + * @property {number|null} [begin] Annotation begin + * @property {number|null} [end] Annotation end + * @property {google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null} [semantic] Annotation semantic + */ + + /** + * Constructs a new Annotation. + * @memberof google.protobuf.GeneratedCodeInfo + * @classdesc Represents an Annotation. + * @implements IAnnotation + * @constructor + * @param {google.protobuf.GeneratedCodeInfo.IAnnotation=} [properties] Properties to set + */ + function Annotation(properties) { + this.path = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Annotation path. + * @member {Array.} path + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.path = $util.emptyArray; + + /** + * Annotation sourceFile. + * @member {string} sourceFile + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.sourceFile = ""; + + /** + * Annotation begin. + * @member {number} begin + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.begin = 0; + + /** + * Annotation end. + * @member {number} end + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.end = 0; + + /** + * Annotation semantic. + * @member {google.protobuf.GeneratedCodeInfo.Annotation.Semantic} semantic + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.semantic = 0; + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.GeneratedCodeInfo.Annotation} Annotation + */ + Annotation.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.GeneratedCodeInfo.Annotation) + return object; + var message = new $root.google.protobuf.GeneratedCodeInfo.Annotation(); + if (object.path) { + if (!Array.isArray(object.path)) + throw TypeError(".google.protobuf.GeneratedCodeInfo.Annotation.path: array expected"); + message.path = []; + for (var i = 0; i < object.path.length; ++i) + message.path[i] = object.path[i] | 0; + } + if (object.sourceFile != null) + message.sourceFile = String(object.sourceFile); + if (object.begin != null) + message.begin = object.begin | 0; + if (object.end != null) + message.end = object.end | 0; + switch (object.semantic) { + default: + if (typeof object.semantic === "number") { + message.semantic = object.semantic; + break; + } + break; + case "NONE": + case 0: + message.semantic = 0; + break; + case "SET": + case 1: + message.semantic = 1; + break; + case "ALIAS": + case 2: + message.semantic = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {google.protobuf.GeneratedCodeInfo.Annotation} message Annotation + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Annotation.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.path = []; + if (options.defaults) { + object.sourceFile = ""; + object.begin = 0; + object.end = 0; + object.semantic = options.enums === String ? "NONE" : 0; + } + if (message.path && message.path.length) { + object.path = []; + for (var j = 0; j < message.path.length; ++j) + object.path[j] = message.path[j]; + } + if (message.sourceFile != null && message.hasOwnProperty("sourceFile")) + object.sourceFile = message.sourceFile; + if (message.begin != null && message.hasOwnProperty("begin")) + object.begin = message.begin; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + if (message.semantic != null && message.hasOwnProperty("semantic")) + object.semantic = options.enums === String ? $root.google.protobuf.GeneratedCodeInfo.Annotation.Semantic[message.semantic] === undefined ? message.semantic : $root.google.protobuf.GeneratedCodeInfo.Annotation.Semantic[message.semantic] : message.semantic; + return object; + }; + + /** + * Converts this Annotation to JSON. + * @function toJSON + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + * @returns {Object.} JSON object + */ + Annotation.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Annotation + * @function getTypeUrl + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Annotation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.GeneratedCodeInfo.Annotation"; + }; + + /** + * Semantic enum. + * @name google.protobuf.GeneratedCodeInfo.Annotation.Semantic + * @enum {string} + * @property {string} NONE=NONE NONE value + * @property {string} SET=SET SET value + * @property {string} ALIAS=ALIAS ALIAS value + */ + Annotation.Semantic = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "NONE"] = "NONE"; + values[valuesById[1] = "SET"] = "SET"; + values[valuesById[2] = "ALIAS"] = "ALIAS"; + return values; + })(); + + return Annotation; + })(); + + return GeneratedCodeInfo; + })(); + + protobuf.Timestamp = (function() { + + /** + * Properties of a Timestamp. + * @memberof google.protobuf + * @interface ITimestamp + * @property {number|string|null} [seconds] Timestamp seconds + * @property {number|null} [nanos] Timestamp nanos + */ + + /** + * Constructs a new Timestamp. + * @memberof google.protobuf + * @classdesc Represents a Timestamp. + * @implements ITimestamp + * @constructor + * @param {google.protobuf.ITimestamp=} [properties] Properties to set + */ + function Timestamp(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Timestamp seconds. + * @member {number|string} seconds + * @memberof google.protobuf.Timestamp + * @instance + */ + Timestamp.prototype.seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Timestamp nanos. + * @member {number} nanos + * @memberof google.protobuf.Timestamp + * @instance + */ + Timestamp.prototype.nanos = 0; + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Timestamp + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Timestamp} Timestamp + */ + Timestamp.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Timestamp) + return object; + var message = new $root.google.protobuf.Timestamp(); + if (object.seconds != null) + if ($util.Long) + (message.seconds = $util.Long.fromValue(object.seconds)).unsigned = false; + else if (typeof object.seconds === "string") + message.seconds = parseInt(object.seconds, 10); + else if (typeof object.seconds === "number") + message.seconds = object.seconds; + else if (typeof object.seconds === "object") + message.seconds = new $util.LongBits(object.seconds.low >>> 0, object.seconds.high >>> 0).toNumber(); + if (object.nanos != null) + message.nanos = object.nanos | 0; + return message; + }; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Timestamp + * @static + * @param {google.protobuf.Timestamp} message Timestamp + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Timestamp.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.seconds = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.seconds = options.longs === String ? "0" : 0; + object.nanos = 0; + } + if (message.seconds != null && message.hasOwnProperty("seconds")) + if (typeof message.seconds === "number") + object.seconds = options.longs === String ? String(message.seconds) : message.seconds; + else + object.seconds = options.longs === String ? $util.Long.prototype.toString.call(message.seconds) : options.longs === Number ? new $util.LongBits(message.seconds.low >>> 0, message.seconds.high >>> 0).toNumber() : message.seconds; + if (message.nanos != null && message.hasOwnProperty("nanos")) + object.nanos = message.nanos; + return object; + }; + + /** + * Converts this Timestamp to JSON. + * @function toJSON + * @memberof google.protobuf.Timestamp + * @instance + * @returns {Object.} JSON object + */ + Timestamp.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Timestamp + * @function getTypeUrl + * @memberof google.protobuf.Timestamp + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Timestamp.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Timestamp"; + }; + + return Timestamp; + })(); + + protobuf.Duration = (function() { + + /** + * Properties of a Duration. + * @memberof google.protobuf + * @interface IDuration + * @property {number|string|null} [seconds] Duration seconds + * @property {number|null} [nanos] Duration nanos + */ + + /** + * Constructs a new Duration. + * @memberof google.protobuf + * @classdesc Represents a Duration. + * @implements IDuration + * @constructor + * @param {google.protobuf.IDuration=} [properties] Properties to set + */ + function Duration(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Duration seconds. + * @member {number|string} seconds + * @memberof google.protobuf.Duration + * @instance + */ + Duration.prototype.seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Duration nanos. + * @member {number} nanos + * @memberof google.protobuf.Duration + * @instance + */ + Duration.prototype.nanos = 0; + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Duration + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Duration} Duration + */ + Duration.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Duration) + return object; + var message = new $root.google.protobuf.Duration(); + if (object.seconds != null) + if ($util.Long) + (message.seconds = $util.Long.fromValue(object.seconds)).unsigned = false; + else if (typeof object.seconds === "string") + message.seconds = parseInt(object.seconds, 10); + else if (typeof object.seconds === "number") + message.seconds = object.seconds; + else if (typeof object.seconds === "object") + message.seconds = new $util.LongBits(object.seconds.low >>> 0, object.seconds.high >>> 0).toNumber(); + if (object.nanos != null) + message.nanos = object.nanos | 0; + return message; + }; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Duration + * @static + * @param {google.protobuf.Duration} message Duration + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Duration.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.seconds = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.seconds = options.longs === String ? "0" : 0; + object.nanos = 0; + } + if (message.seconds != null && message.hasOwnProperty("seconds")) + if (typeof message.seconds === "number") + object.seconds = options.longs === String ? String(message.seconds) : message.seconds; + else + object.seconds = options.longs === String ? $util.Long.prototype.toString.call(message.seconds) : options.longs === Number ? new $util.LongBits(message.seconds.low >>> 0, message.seconds.high >>> 0).toNumber() : message.seconds; + if (message.nanos != null && message.hasOwnProperty("nanos")) + object.nanos = message.nanos; + return object; + }; + + /** + * Converts this Duration to JSON. + * @function toJSON + * @memberof google.protobuf.Duration + * @instance + * @returns {Object.} JSON object + */ + Duration.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Duration + * @function getTypeUrl + * @memberof google.protobuf.Duration + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Duration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Duration"; + }; + + return Duration; + })(); + + protobuf.Any = (function() { + + /** + * Properties of an Any. + * @memberof google.protobuf + * @interface IAny + * @property {string|null} [type_url] Any type_url + * @property {Uint8Array|null} [value] Any value + */ + + /** + * Constructs a new Any. + * @memberof google.protobuf + * @classdesc Represents an Any. + * @implements IAny + * @constructor + * @param {google.protobuf.IAny=} [properties] Properties to set + */ + function Any(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Any type_url. + * @member {string} type_url + * @memberof google.protobuf.Any + * @instance + */ + Any.prototype.type_url = ""; + + /** + * Any value. + * @member {Uint8Array} value + * @memberof google.protobuf.Any + * @instance + */ + Any.prototype.value = $util.newBuffer([]); + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Any + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Any} Any + */ + Any.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Any) + return object; + var message = new $root.google.protobuf.Any(); + if (object.type_url != null) + message.type_url = String(object.type_url); + if (object.value != null) + if (typeof object.value === "string") + $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0); + else if (object.value.length >= 0) + message.value = object.value; + return message; + }; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Any + * @static + * @param {google.protobuf.Any} message Any + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Any.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.type_url = ""; + if (options.bytes === String) + object.value = ""; + else { + object.value = []; + if (options.bytes !== Array) + object.value = $util.newBuffer(object.value); + } + } + if (message.type_url != null && message.hasOwnProperty("type_url")) + object.type_url = message.type_url; + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; + return object; + }; + + /** + * Converts this Any to JSON. + * @function toJSON + * @memberof google.protobuf.Any + * @instance + * @returns {Object.} JSON object + */ + Any.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Any + * @function getTypeUrl + * @memberof google.protobuf.Any + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Any.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Any"; + }; + + return Any; + })(); + + protobuf.Empty = (function() { + + /** + * Properties of an Empty. + * @memberof google.protobuf + * @interface IEmpty + */ + + /** + * Constructs a new Empty. + * @memberof google.protobuf + * @classdesc Represents an Empty. + * @implements IEmpty + * @constructor + * @param {google.protobuf.IEmpty=} [properties] Properties to set + */ + function Empty(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Empty + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Empty} Empty + */ + Empty.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Empty) + return object; + return new $root.google.protobuf.Empty(); + }; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Empty + * @static + * @param {google.protobuf.Empty} message Empty + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Empty.toObject = function toObject() { + return {}; + }; + + /** + * Converts this Empty to JSON. + * @function toJSON + * @memberof google.protobuf.Empty + * @instance + * @returns {Object.} JSON object + */ + Empty.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Empty + * @function getTypeUrl + * @memberof google.protobuf.Empty + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Empty.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Empty"; + }; + + return Empty; + })(); + + protobuf.FieldMask = (function() { + + /** + * Properties of a FieldMask. + * @memberof google.protobuf + * @interface IFieldMask + * @property {Array.|null} [paths] FieldMask paths + */ + + /** + * Constructs a new FieldMask. + * @memberof google.protobuf + * @classdesc Represents a FieldMask. + * @implements IFieldMask + * @constructor + * @param {google.protobuf.IFieldMask=} [properties] Properties to set + */ + function FieldMask(properties) { + this.paths = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldMask paths. + * @member {Array.} paths + * @memberof google.protobuf.FieldMask + * @instance + */ + FieldMask.prototype.paths = $util.emptyArray; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldMask + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldMask} FieldMask + */ + FieldMask.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldMask) + return object; + var message = new $root.google.protobuf.FieldMask(); + if (object.paths) { + if (!Array.isArray(object.paths)) + throw TypeError(".google.protobuf.FieldMask.paths: array expected"); + message.paths = []; + for (var i = 0; i < object.paths.length; ++i) + message.paths[i] = String(object.paths[i]); + } + return message; + }; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldMask + * @static + * @param {google.protobuf.FieldMask} message FieldMask + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldMask.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.paths = []; + if (message.paths && message.paths.length) { + object.paths = []; + for (var j = 0; j < message.paths.length; ++j) + object.paths[j] = message.paths[j]; + } + return object; + }; + + /** + * Converts this FieldMask to JSON. + * @function toJSON + * @memberof google.protobuf.FieldMask + * @instance + * @returns {Object.} JSON object + */ + FieldMask.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldMask + * @function getTypeUrl + * @memberof google.protobuf.FieldMask + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldMask.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldMask"; + }; + + return FieldMask; + })(); + + protobuf.Struct = (function() { + + /** + * Properties of a Struct. + * @memberof google.protobuf + * @interface IStruct + * @property {Object.|null} [fields] Struct fields + */ + + /** + * Constructs a new Struct. + * @memberof google.protobuf + * @classdesc Represents a Struct. + * @implements IStruct + * @constructor + * @param {google.protobuf.IStruct=} [properties] Properties to set + */ + function Struct(properties) { + this.fields = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Struct fields. + * @member {Object.} fields + * @memberof google.protobuf.Struct + * @instance + */ + Struct.prototype.fields = $util.emptyObject; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Struct + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Struct} Struct + */ + Struct.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Struct) + return object; + var message = new $root.google.protobuf.Struct(); + if (object.fields) { + if (typeof object.fields !== "object") + throw TypeError(".google.protobuf.Struct.fields: object expected"); + message.fields = {}; + for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { + if (typeof object.fields[keys[i]] !== "object") + throw TypeError(".google.protobuf.Struct.fields: object expected"); + message.fields[keys[i]] = $root.google.protobuf.Value.fromObject(object.fields[keys[i]]); + } + } + return message; + }; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Struct + * @static + * @param {google.protobuf.Struct} message Struct + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Struct.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.fields = {}; + var keys2; + if (message.fields && (keys2 = Object.keys(message.fields)).length) { + object.fields = {}; + for (var j = 0; j < keys2.length; ++j) + object.fields[keys2[j]] = $root.google.protobuf.Value.toObject(message.fields[keys2[j]], options); + } + return object; + }; + + /** + * Converts this Struct to JSON. + * @function toJSON + * @memberof google.protobuf.Struct + * @instance + * @returns {Object.} JSON object + */ + Struct.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Struct + * @function getTypeUrl + * @memberof google.protobuf.Struct + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Struct.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Struct"; + }; + + return Struct; + })(); + + protobuf.Value = (function() { + + /** + * Properties of a Value. + * @memberof google.protobuf + * @interface IValue + * @property {google.protobuf.NullValue|null} [nullValue] Value nullValue + * @property {number|null} [numberValue] Value numberValue + * @property {string|null} [stringValue] Value stringValue + * @property {boolean|null} [boolValue] Value boolValue + * @property {google.protobuf.IStruct|null} [structValue] Value structValue + * @property {google.protobuf.IListValue|null} [listValue] Value listValue + */ + + /** + * Constructs a new Value. + * @memberof google.protobuf + * @classdesc Represents a Value. + * @implements IValue + * @constructor + * @param {google.protobuf.IValue=} [properties] Properties to set + */ + function Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Value nullValue. + * @member {google.protobuf.NullValue|null|undefined} nullValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.nullValue = null; + + /** + * Value numberValue. + * @member {number|null|undefined} numberValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.numberValue = null; + + /** + * Value stringValue. + * @member {string|null|undefined} stringValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.stringValue = null; + + /** + * Value boolValue. + * @member {boolean|null|undefined} boolValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.boolValue = null; + + /** + * Value structValue. + * @member {google.protobuf.IStruct|null|undefined} structValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.structValue = null; + + /** + * Value listValue. + * @member {google.protobuf.IListValue|null|undefined} listValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.listValue = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Value kind. + * @member {"nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"|undefined} kind + * @memberof google.protobuf.Value + * @instance + */ + Object.defineProperty(Value.prototype, "kind", { + get: $util.oneOfGetter($oneOfFields = ["nullValue", "numberValue", "stringValue", "boolValue", "structValue", "listValue"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Value + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Value} Value + */ + Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Value) + return object; + var message = new $root.google.protobuf.Value(); + switch (object.nullValue) { + default: + if (typeof object.nullValue === "number") { + message.nullValue = object.nullValue; + break; + } + break; + case "NULL_VALUE": + case 0: + message.nullValue = 0; + break; + } + if (object.numberValue != null) + message.numberValue = Number(object.numberValue); + if (object.stringValue != null) + message.stringValue = String(object.stringValue); + if (object.boolValue != null) + message.boolValue = Boolean(object.boolValue); + if (object.structValue != null) { + if (typeof object.structValue !== "object") + throw TypeError(".google.protobuf.Value.structValue: object expected"); + message.structValue = $root.google.protobuf.Struct.fromObject(object.structValue); + } + if (object.listValue != null) { + if (typeof object.listValue !== "object") + throw TypeError(".google.protobuf.Value.listValue: object expected"); + message.listValue = $root.google.protobuf.ListValue.fromObject(object.listValue); + } + return message; + }; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Value + * @static + * @param {google.protobuf.Value} message Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.nullValue != null && message.hasOwnProperty("nullValue")) { + object.nullValue = options.enums === String ? $root.google.protobuf.NullValue[message.nullValue] === undefined ? message.nullValue : $root.google.protobuf.NullValue[message.nullValue] : message.nullValue; + if (options.oneofs) + object.kind = "nullValue"; + } + if (message.numberValue != null && message.hasOwnProperty("numberValue")) { + object.numberValue = options.json && !isFinite(message.numberValue) ? String(message.numberValue) : message.numberValue; + if (options.oneofs) + object.kind = "numberValue"; + } + if (message.stringValue != null && message.hasOwnProperty("stringValue")) { + object.stringValue = message.stringValue; + if (options.oneofs) + object.kind = "stringValue"; + } + if (message.boolValue != null && message.hasOwnProperty("boolValue")) { + object.boolValue = message.boolValue; + if (options.oneofs) + object.kind = "boolValue"; + } + if (message.structValue != null && message.hasOwnProperty("structValue")) { + object.structValue = $root.google.protobuf.Struct.toObject(message.structValue, options); + if (options.oneofs) + object.kind = "structValue"; + } + if (message.listValue != null && message.hasOwnProperty("listValue")) { + object.listValue = $root.google.protobuf.ListValue.toObject(message.listValue, options); + if (options.oneofs) + object.kind = "listValue"; + } + return object; + }; + + /** + * Converts this Value to JSON. + * @function toJSON + * @memberof google.protobuf.Value + * @instance + * @returns {Object.} JSON object + */ + Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Value + * @function getTypeUrl + * @memberof google.protobuf.Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Value"; + }; + + return Value; + })(); + + /** + * NullValue enum. + * @name google.protobuf.NullValue + * @enum {string} + * @property {string} NULL_VALUE=NULL_VALUE NULL_VALUE value + */ + protobuf.NullValue = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "NULL_VALUE"] = "NULL_VALUE"; + return values; + })(); + + protobuf.ListValue = (function() { + + /** + * Properties of a ListValue. + * @memberof google.protobuf + * @interface IListValue + * @property {Array.|null} [values] ListValue values + */ + + /** + * Constructs a new ListValue. + * @memberof google.protobuf + * @classdesc Represents a ListValue. + * @implements IListValue + * @constructor + * @param {google.protobuf.IListValue=} [properties] Properties to set + */ + function ListValue(properties) { + this.values = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListValue values. + * @member {Array.} values + * @memberof google.protobuf.ListValue + * @instance + */ + ListValue.prototype.values = $util.emptyArray; + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ListValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ListValue} ListValue + */ + ListValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ListValue) + return object; + var message = new $root.google.protobuf.ListValue(); + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".google.protobuf.ListValue.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".google.protobuf.ListValue.values: object expected"); + message.values[i] = $root.google.protobuf.Value.fromObject(object.values[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ListValue + * @static + * @param {google.protobuf.ListValue} message ListValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.values = []; + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.google.protobuf.Value.toObject(message.values[j], options); + } + return object; + }; + + /** + * Converts this ListValue to JSON. + * @function toJSON + * @memberof google.protobuf.ListValue + * @instance + * @returns {Object.} JSON object + */ + ListValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListValue + * @function getTypeUrl + * @memberof google.protobuf.ListValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ListValue"; + }; + + return ListValue; + })(); + + protobuf.DoubleValue = (function() { + + /** + * Properties of a DoubleValue. + * @memberof google.protobuf + * @interface IDoubleValue + * @property {number|null} [value] DoubleValue value + */ + + /** + * Constructs a new DoubleValue. + * @memberof google.protobuf + * @classdesc Represents a DoubleValue. + * @implements IDoubleValue + * @constructor + * @param {google.protobuf.IDoubleValue=} [properties] Properties to set + */ + function DoubleValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DoubleValue value. + * @member {number} value + * @memberof google.protobuf.DoubleValue + * @instance + */ + DoubleValue.prototype.value = 0; + + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DoubleValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DoubleValue} DoubleValue + */ + DoubleValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DoubleValue) + return object; + var message = new $root.google.protobuf.DoubleValue(); + if (object.value != null) + message.value = Number(object.value); + return message; + }; + + /** + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.DoubleValue + * @static + * @param {google.protobuf.DoubleValue} message DoubleValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DoubleValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = 0; + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value; + return object; + }; + + /** + * Converts this DoubleValue to JSON. + * @function toJSON + * @memberof google.protobuf.DoubleValue + * @instance + * @returns {Object.} JSON object + */ + DoubleValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DoubleValue + * @function getTypeUrl + * @memberof google.protobuf.DoubleValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DoubleValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.DoubleValue"; + }; + + return DoubleValue; + })(); + + protobuf.FloatValue = (function() { + + /** + * Properties of a FloatValue. + * @memberof google.protobuf + * @interface IFloatValue + * @property {number|null} [value] FloatValue value + */ + + /** + * Constructs a new FloatValue. + * @memberof google.protobuf + * @classdesc Represents a FloatValue. + * @implements IFloatValue + * @constructor + * @param {google.protobuf.IFloatValue=} [properties] Properties to set + */ + function FloatValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FloatValue value. + * @member {number} value + * @memberof google.protobuf.FloatValue + * @instance + */ + FloatValue.prototype.value = 0; + + /** + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FloatValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FloatValue} FloatValue + */ + FloatValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FloatValue) + return object; + var message = new $root.google.protobuf.FloatValue(); + if (object.value != null) + message.value = Number(object.value); + return message; + }; + + /** + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FloatValue + * @static + * @param {google.protobuf.FloatValue} message FloatValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FloatValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = 0; + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value; + return object; + }; + + /** + * Converts this FloatValue to JSON. + * @function toJSON + * @memberof google.protobuf.FloatValue + * @instance + * @returns {Object.} JSON object + */ + FloatValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FloatValue + * @function getTypeUrl + * @memberof google.protobuf.FloatValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FloatValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FloatValue"; + }; + + return FloatValue; + })(); + + protobuf.Int64Value = (function() { + + /** + * Properties of an Int64Value. + * @memberof google.protobuf + * @interface IInt64Value + * @property {number|string|null} [value] Int64Value value + */ + + /** + * Constructs a new Int64Value. + * @memberof google.protobuf + * @classdesc Represents an Int64Value. + * @implements IInt64Value + * @constructor + * @param {google.protobuf.IInt64Value=} [properties] Properties to set + */ + function Int64Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Int64Value value. + * @member {number|string} value + * @memberof google.protobuf.Int64Value + * @instance + */ + Int64Value.prototype.value = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Int64Value + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Int64Value} Int64Value + */ + Int64Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Int64Value) + return object; + var message = new $root.google.protobuf.Int64Value(); + if (object.value != null) + if ($util.Long) + (message.value = $util.Long.fromValue(object.value)).unsigned = false; + else if (typeof object.value === "string") + message.value = parseInt(object.value, 10); + else if (typeof object.value === "number") + message.value = object.value; + else if (typeof object.value === "object") + message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Int64Value + * @static + * @param {google.protobuf.Int64Value} message Int64Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Int64Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.value = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.value = options.longs === String ? "0" : 0; + if (message.value != null && message.hasOwnProperty("value")) + if (typeof message.value === "number") + object.value = options.longs === String ? String(message.value) : message.value; + else + object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber() : message.value; + return object; + }; + + /** + * Converts this Int64Value to JSON. + * @function toJSON + * @memberof google.protobuf.Int64Value + * @instance + * @returns {Object.} JSON object + */ + Int64Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Int64Value + * @function getTypeUrl + * @memberof google.protobuf.Int64Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Int64Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Int64Value"; + }; + + return Int64Value; + })(); + + protobuf.UInt64Value = (function() { + + /** + * Properties of a UInt64Value. + * @memberof google.protobuf + * @interface IUInt64Value + * @property {number|string|null} [value] UInt64Value value + */ + + /** + * Constructs a new UInt64Value. + * @memberof google.protobuf + * @classdesc Represents a UInt64Value. + * @implements IUInt64Value + * @constructor + * @param {google.protobuf.IUInt64Value=} [properties] Properties to set + */ + function UInt64Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UInt64Value value. + * @member {number|string} value + * @memberof google.protobuf.UInt64Value + * @instance + */ + UInt64Value.prototype.value = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.UInt64Value + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.UInt64Value} UInt64Value + */ + UInt64Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UInt64Value) + return object; + var message = new $root.google.protobuf.UInt64Value(); + if (object.value != null) + if ($util.Long) + (message.value = $util.Long.fromValue(object.value)).unsigned = true; + else if (typeof object.value === "string") + message.value = parseInt(object.value, 10); + else if (typeof object.value === "number") + message.value = object.value; + else if (typeof object.value === "object") + message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(true); + return message; + }; + + /** + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.UInt64Value + * @static + * @param {google.protobuf.UInt64Value} message UInt64Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UInt64Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.value = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.value = options.longs === String ? "0" : 0; + if (message.value != null && message.hasOwnProperty("value")) + if (typeof message.value === "number") + object.value = options.longs === String ? String(message.value) : message.value; + else + object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber(true) : message.value; + return object; + }; + + /** + * Converts this UInt64Value to JSON. + * @function toJSON + * @memberof google.protobuf.UInt64Value + * @instance + * @returns {Object.} JSON object + */ + UInt64Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UInt64Value + * @function getTypeUrl + * @memberof google.protobuf.UInt64Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UInt64Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.UInt64Value"; + }; + + return UInt64Value; + })(); + + protobuf.Int32Value = (function() { + + /** + * Properties of an Int32Value. + * @memberof google.protobuf + * @interface IInt32Value + * @property {number|null} [value] Int32Value value + */ + + /** + * Constructs a new Int32Value. + * @memberof google.protobuf + * @classdesc Represents an Int32Value. + * @implements IInt32Value + * @constructor + * @param {google.protobuf.IInt32Value=} [properties] Properties to set + */ + function Int32Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Int32Value value. + * @member {number} value + * @memberof google.protobuf.Int32Value + * @instance + */ + Int32Value.prototype.value = 0; + + /** + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Int32Value + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Int32Value} Int32Value + */ + Int32Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Int32Value) + return object; + var message = new $root.google.protobuf.Int32Value(); + if (object.value != null) + message.value = object.value | 0; + return message; + }; + + /** + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Int32Value + * @static + * @param {google.protobuf.Int32Value} message Int32Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Int32Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = 0; + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + return object; + }; + + /** + * Converts this Int32Value to JSON. + * @function toJSON + * @memberof google.protobuf.Int32Value + * @instance + * @returns {Object.} JSON object + */ + Int32Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Int32Value + * @function getTypeUrl + * @memberof google.protobuf.Int32Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Int32Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Int32Value"; + }; + + return Int32Value; + })(); + + protobuf.UInt32Value = (function() { + + /** + * Properties of a UInt32Value. + * @memberof google.protobuf + * @interface IUInt32Value + * @property {number|null} [value] UInt32Value value + */ + + /** + * Constructs a new UInt32Value. + * @memberof google.protobuf + * @classdesc Represents a UInt32Value. + * @implements IUInt32Value + * @constructor + * @param {google.protobuf.IUInt32Value=} [properties] Properties to set + */ + function UInt32Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UInt32Value value. + * @member {number} value + * @memberof google.protobuf.UInt32Value + * @instance + */ + UInt32Value.prototype.value = 0; + + /** + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.UInt32Value + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.UInt32Value} UInt32Value + */ + UInt32Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UInt32Value) + return object; + var message = new $root.google.protobuf.UInt32Value(); + if (object.value != null) + message.value = object.value >>> 0; + return message; + }; + + /** + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.UInt32Value + * @static + * @param {google.protobuf.UInt32Value} message UInt32Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UInt32Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = 0; + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + return object; + }; + + /** + * Converts this UInt32Value to JSON. + * @function toJSON + * @memberof google.protobuf.UInt32Value + * @instance + * @returns {Object.} JSON object + */ + UInt32Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UInt32Value + * @function getTypeUrl + * @memberof google.protobuf.UInt32Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UInt32Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.UInt32Value"; + }; + + return UInt32Value; + })(); + + protobuf.BoolValue = (function() { + + /** + * Properties of a BoolValue. + * @memberof google.protobuf + * @interface IBoolValue + * @property {boolean|null} [value] BoolValue value + */ + + /** + * Constructs a new BoolValue. + * @memberof google.protobuf + * @classdesc Represents a BoolValue. + * @implements IBoolValue + * @constructor + * @param {google.protobuf.IBoolValue=} [properties] Properties to set + */ + function BoolValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BoolValue value. + * @member {boolean} value + * @memberof google.protobuf.BoolValue + * @instance + */ + BoolValue.prototype.value = false; + + /** + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.BoolValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.BoolValue} BoolValue + */ + BoolValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.BoolValue) + return object; + var message = new $root.google.protobuf.BoolValue(); + if (object.value != null) + message.value = Boolean(object.value); + return message; + }; + + /** + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.BoolValue + * @static + * @param {google.protobuf.BoolValue} message BoolValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BoolValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = false; + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + return object; + }; + + /** + * Converts this BoolValue to JSON. + * @function toJSON + * @memberof google.protobuf.BoolValue + * @instance + * @returns {Object.} JSON object + */ + BoolValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BoolValue + * @function getTypeUrl + * @memberof google.protobuf.BoolValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BoolValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.BoolValue"; + }; + + return BoolValue; + })(); + + protobuf.StringValue = (function() { + + /** + * Properties of a StringValue. + * @memberof google.protobuf + * @interface IStringValue + * @property {string|null} [value] StringValue value + */ + + /** + * Constructs a new StringValue. + * @memberof google.protobuf + * @classdesc Represents a StringValue. + * @implements IStringValue + * @constructor + * @param {google.protobuf.IStringValue=} [properties] Properties to set + */ + function StringValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * StringValue value. + * @member {string} value + * @memberof google.protobuf.StringValue + * @instance + */ + StringValue.prototype.value = ""; + + /** + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.StringValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.StringValue} StringValue + */ + StringValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.StringValue) + return object; + var message = new $root.google.protobuf.StringValue(); + if (object.value != null) + message.value = String(object.value); + return message; + }; + + /** + * Creates a plain object from a StringValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.StringValue + * @static + * @param {google.protobuf.StringValue} message StringValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + StringValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = ""; + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + return object; + }; + + /** + * Converts this StringValue to JSON. + * @function toJSON + * @memberof google.protobuf.StringValue + * @instance + * @returns {Object.} JSON object + */ + StringValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for StringValue + * @function getTypeUrl + * @memberof google.protobuf.StringValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + StringValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.StringValue"; + }; + + return StringValue; + })(); + + protobuf.BytesValue = (function() { + + /** + * Properties of a BytesValue. + * @memberof google.protobuf + * @interface IBytesValue + * @property {Uint8Array|null} [value] BytesValue value + */ + + /** + * Constructs a new BytesValue. + * @memberof google.protobuf + * @classdesc Represents a BytesValue. + * @implements IBytesValue + * @constructor + * @param {google.protobuf.IBytesValue=} [properties] Properties to set + */ + function BytesValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BytesValue value. + * @member {Uint8Array} value + * @memberof google.protobuf.BytesValue + * @instance + */ + BytesValue.prototype.value = $util.newBuffer([]); + + /** + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.BytesValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.BytesValue} BytesValue + */ + BytesValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.BytesValue) + return object; + var message = new $root.google.protobuf.BytesValue(); + if (object.value != null) + if (typeof object.value === "string") + $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0); + else if (object.value.length >= 0) + message.value = object.value; + return message; + }; + + /** + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.BytesValue + * @static + * @param {google.protobuf.BytesValue} message BytesValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BytesValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if (options.bytes === String) + object.value = ""; + else { + object.value = []; + if (options.bytes !== Array) + object.value = $util.newBuffer(object.value); + } + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; + return object; + }; + + /** + * Converts this BytesValue to JSON. + * @function toJSON + * @memberof google.protobuf.BytesValue + * @instance + * @returns {Object.} JSON object + */ + BytesValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BytesValue + * @function getTypeUrl + * @memberof google.protobuf.BytesValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BytesValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.BytesValue"; + }; + + return BytesValue; + })(); + + return protobuf; + })(); + + google.type = (function() { + + /** + * Namespace type. + * @memberof google + * @namespace + */ + var type = {}; + + /** + * DayOfWeek enum. + * @name google.type.DayOfWeek + * @enum {string} + * @property {string} DAY_OF_WEEK_UNSPECIFIED=DAY_OF_WEEK_UNSPECIFIED DAY_OF_WEEK_UNSPECIFIED value + * @property {string} MONDAY=MONDAY MONDAY value + * @property {string} TUESDAY=TUESDAY TUESDAY value + * @property {string} WEDNESDAY=WEDNESDAY WEDNESDAY value + * @property {string} THURSDAY=THURSDAY THURSDAY value + * @property {string} FRIDAY=FRIDAY FRIDAY value + * @property {string} SATURDAY=SATURDAY SATURDAY value + * @property {string} SUNDAY=SUNDAY SUNDAY value + */ + type.DayOfWeek = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DAY_OF_WEEK_UNSPECIFIED"] = "DAY_OF_WEEK_UNSPECIFIED"; + values[valuesById[1] = "MONDAY"] = "MONDAY"; + values[valuesById[2] = "TUESDAY"] = "TUESDAY"; + values[valuesById[3] = "WEDNESDAY"] = "WEDNESDAY"; + values[valuesById[4] = "THURSDAY"] = "THURSDAY"; + values[valuesById[5] = "FRIDAY"] = "FRIDAY"; + values[valuesById[6] = "SATURDAY"] = "SATURDAY"; + values[valuesById[7] = "SUNDAY"] = "SUNDAY"; + return values; + })(); + + type.LatLng = (function() { + + /** + * Properties of a LatLng. + * @memberof google.type + * @interface ILatLng + * @property {number|null} [latitude] LatLng latitude + * @property {number|null} [longitude] LatLng longitude + */ + + /** + * Constructs a new LatLng. + * @memberof google.type + * @classdesc Represents a LatLng. + * @implements ILatLng + * @constructor + * @param {google.type.ILatLng=} [properties] Properties to set + */ + function LatLng(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * LatLng latitude. + * @member {number} latitude + * @memberof google.type.LatLng + * @instance + */ + LatLng.prototype.latitude = 0; + + /** + * LatLng longitude. + * @member {number} longitude + * @memberof google.type.LatLng + * @instance + */ + LatLng.prototype.longitude = 0; + + /** + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.type.LatLng + * @static + * @param {Object.} object Plain object + * @returns {google.type.LatLng} LatLng + */ + LatLng.fromObject = function fromObject(object) { + if (object instanceof $root.google.type.LatLng) + return object; + var message = new $root.google.type.LatLng(); + if (object.latitude != null) + message.latitude = Number(object.latitude); + if (object.longitude != null) + message.longitude = Number(object.longitude); + return message; + }; + + /** + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @function toObject + * @memberof google.type.LatLng + * @static + * @param {google.type.LatLng} message LatLng + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + LatLng.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.latitude = 0; + object.longitude = 0; + } + if (message.latitude != null && message.hasOwnProperty("latitude")) + object.latitude = options.json && !isFinite(message.latitude) ? String(message.latitude) : message.latitude; + if (message.longitude != null && message.hasOwnProperty("longitude")) + object.longitude = options.json && !isFinite(message.longitude) ? String(message.longitude) : message.longitude; + return object; + }; + + /** + * Converts this LatLng to JSON. + * @function toJSON + * @memberof google.type.LatLng + * @instance + * @returns {Object.} JSON object + */ + LatLng.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for LatLng + * @function getTypeUrl + * @memberof google.type.LatLng + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + LatLng.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.type.LatLng"; + }; + + return LatLng; + })(); + + return type; + })(); + + google.longrunning = (function() { + + /** + * Namespace longrunning. + * @memberof google + * @namespace + */ + var longrunning = {}; + + longrunning.Operations = (function() { + + /** + * Constructs a new Operations service. + * @memberof google.longrunning + * @classdesc Represents an Operations + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function Operations(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (Operations.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = Operations; + + /** + * Callback as used by {@link google.longrunning.Operations#listOperations}. + * @memberof google.longrunning.Operations + * @typedef ListOperationsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.ListOperationsResponse} [response] ListOperationsResponse + */ + + /** + * Calls ListOperations. + * @function listOperations + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IListOperationsRequest} request ListOperationsRequest message or plain object + * @param {google.longrunning.Operations.ListOperationsCallback} callback Node-style callback called with the error, if any, and ListOperationsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.listOperations = function listOperations(request, callback) { + return this.rpcCall(listOperations, $root.google.longrunning.ListOperationsRequest, $root.google.longrunning.ListOperationsResponse, request, callback); + }, "name", { value: "ListOperations" }); + + /** + * Calls ListOperations. + * @function listOperations + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IListOperationsRequest} request ListOperationsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.longrunning.Operations#getOperation}. + * @memberof google.longrunning.Operations + * @typedef GetOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls GetOperation. + * @function getOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IGetOperationRequest} request GetOperationRequest message or plain object + * @param {google.longrunning.Operations.GetOperationCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.getOperation = function getOperation(request, callback) { + return this.rpcCall(getOperation, $root.google.longrunning.GetOperationRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "GetOperation" }); + + /** + * Calls GetOperation. + * @function getOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IGetOperationRequest} request GetOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.longrunning.Operations#deleteOperation}. + * @memberof google.longrunning.Operations + * @typedef DeleteOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteOperation. + * @function deleteOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IDeleteOperationRequest} request DeleteOperationRequest message or plain object + * @param {google.longrunning.Operations.DeleteOperationCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.deleteOperation = function deleteOperation(request, callback) { + return this.rpcCall(deleteOperation, $root.google.longrunning.DeleteOperationRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteOperation" }); + + /** + * Calls DeleteOperation. + * @function deleteOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IDeleteOperationRequest} request DeleteOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.longrunning.Operations#cancelOperation}. + * @memberof google.longrunning.Operations + * @typedef CancelOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls CancelOperation. + * @function cancelOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.ICancelOperationRequest} request CancelOperationRequest message or plain object + * @param {google.longrunning.Operations.CancelOperationCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.cancelOperation = function cancelOperation(request, callback) { + return this.rpcCall(cancelOperation, $root.google.longrunning.CancelOperationRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "CancelOperation" }); + + /** + * Calls CancelOperation. + * @function cancelOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.ICancelOperationRequest} request CancelOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.longrunning.Operations#waitOperation}. + * @memberof google.longrunning.Operations + * @typedef WaitOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls WaitOperation. + * @function waitOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IWaitOperationRequest} request WaitOperationRequest message or plain object + * @param {google.longrunning.Operations.WaitOperationCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.waitOperation = function waitOperation(request, callback) { + return this.rpcCall(waitOperation, $root.google.longrunning.WaitOperationRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "WaitOperation" }); + + /** + * Calls WaitOperation. + * @function waitOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IWaitOperationRequest} request WaitOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return Operations; + })(); + + longrunning.Operation = (function() { + + /** + * Properties of an Operation. + * @memberof google.longrunning + * @interface IOperation + * @property {string|null} [name] Operation name + * @property {google.protobuf.IAny|null} [metadata] Operation metadata + * @property {boolean|null} [done] Operation done + * @property {google.rpc.IStatus|null} [error] Operation error + * @property {google.protobuf.IAny|null} [response] Operation response + */ + + /** + * Constructs a new Operation. + * @memberof google.longrunning + * @classdesc Represents an Operation. + * @implements IOperation + * @constructor + * @param {google.longrunning.IOperation=} [properties] Properties to set + */ + function Operation(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Operation name. + * @member {string} name + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.name = ""; + + /** + * Operation metadata. + * @member {google.protobuf.IAny|null|undefined} metadata + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.metadata = null; + + /** + * Operation done. + * @member {boolean} done + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.done = false; + + /** + * Operation error. + * @member {google.rpc.IStatus|null|undefined} error + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.error = null; + + /** + * Operation response. + * @member {google.protobuf.IAny|null|undefined} response + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.response = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Operation result. + * @member {"error"|"response"|undefined} result + * @memberof google.longrunning.Operation + * @instance + */ + Object.defineProperty(Operation.prototype, "result", { + get: $util.oneOfGetter($oneOfFields = ["error", "response"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.Operation + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.Operation} Operation + */ + Operation.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.Operation) + return object; + var message = new $root.google.longrunning.Operation(); + if (object.name != null) + message.name = String(object.name); + if (object.metadata != null) { + if (typeof object.metadata !== "object") + throw TypeError(".google.longrunning.Operation.metadata: object expected"); + message.metadata = $root.google.protobuf.Any.fromObject(object.metadata); + } + if (object.done != null) + message.done = Boolean(object.done); + if (object.error != null) { + if (typeof object.error !== "object") + throw TypeError(".google.longrunning.Operation.error: object expected"); + message.error = $root.google.rpc.Status.fromObject(object.error); + } + if (object.response != null) { + if (typeof object.response !== "object") + throw TypeError(".google.longrunning.Operation.response: object expected"); + message.response = $root.google.protobuf.Any.fromObject(object.response); + } + return message; + }; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.Operation + * @static + * @param {google.longrunning.Operation} message Operation + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Operation.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.metadata = null; + object.done = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.metadata != null && message.hasOwnProperty("metadata")) + object.metadata = $root.google.protobuf.Any.toObject(message.metadata, options); + if (message.done != null && message.hasOwnProperty("done")) + object.done = message.done; + if (message.error != null && message.hasOwnProperty("error")) { + object.error = $root.google.rpc.Status.toObject(message.error, options); + if (options.oneofs) + object.result = "error"; + } + if (message.response != null && message.hasOwnProperty("response")) { + object.response = $root.google.protobuf.Any.toObject(message.response, options); + if (options.oneofs) + object.result = "response"; + } + return object; + }; + + /** + * Converts this Operation to JSON. + * @function toJSON + * @memberof google.longrunning.Operation + * @instance + * @returns {Object.} JSON object + */ + Operation.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Operation + * @function getTypeUrl + * @memberof google.longrunning.Operation + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Operation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.Operation"; + }; + + return Operation; + })(); + + longrunning.GetOperationRequest = (function() { + + /** + * Properties of a GetOperationRequest. + * @memberof google.longrunning + * @interface IGetOperationRequest + * @property {string|null} [name] GetOperationRequest name + */ + + /** + * Constructs a new GetOperationRequest. + * @memberof google.longrunning + * @classdesc Represents a GetOperationRequest. + * @implements IGetOperationRequest + * @constructor + * @param {google.longrunning.IGetOperationRequest=} [properties] Properties to set + */ + function GetOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetOperationRequest name. + * @member {string} name + * @memberof google.longrunning.GetOperationRequest + * @instance + */ + GetOperationRequest.prototype.name = ""; + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.GetOperationRequest} GetOperationRequest + */ + GetOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.GetOperationRequest) + return object; + var message = new $root.google.longrunning.GetOperationRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {google.longrunning.GetOperationRequest} message GetOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetOperationRequest to JSON. + * @function toJSON + * @memberof google.longrunning.GetOperationRequest + * @instance + * @returns {Object.} JSON object + */ + GetOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetOperationRequest + * @function getTypeUrl + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.GetOperationRequest"; + }; + + return GetOperationRequest; + })(); + + longrunning.ListOperationsRequest = (function() { + + /** + * Properties of a ListOperationsRequest. + * @memberof google.longrunning + * @interface IListOperationsRequest + * @property {string|null} [name] ListOperationsRequest name + * @property {string|null} [filter] ListOperationsRequest filter + * @property {number|null} [pageSize] ListOperationsRequest pageSize + * @property {string|null} [pageToken] ListOperationsRequest pageToken + * @property {boolean|null} [returnPartialSuccess] ListOperationsRequest returnPartialSuccess + */ + + /** + * Constructs a new ListOperationsRequest. + * @memberof google.longrunning + * @classdesc Represents a ListOperationsRequest. + * @implements IListOperationsRequest + * @constructor + * @param {google.longrunning.IListOperationsRequest=} [properties] Properties to set + */ + function ListOperationsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListOperationsRequest name. + * @member {string} name + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.name = ""; + + /** + * ListOperationsRequest filter. + * @member {string} filter + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.filter = ""; + + /** + * ListOperationsRequest pageSize. + * @member {number} pageSize + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.pageSize = 0; + + /** + * ListOperationsRequest pageToken. + * @member {string} pageToken + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.pageToken = ""; + + /** + * ListOperationsRequest returnPartialSuccess. + * @member {boolean} returnPartialSuccess + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.returnPartialSuccess = false; + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.ListOperationsRequest} ListOperationsRequest + */ + ListOperationsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.ListOperationsRequest) + return object; + var message = new $root.google.longrunning.ListOperationsRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.returnPartialSuccess != null) + message.returnPartialSuccess = Boolean(object.returnPartialSuccess); + return message; + }; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {google.longrunning.ListOperationsRequest} message ListOperationsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListOperationsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + object.name = ""; + object.returnPartialSuccess = false; + } + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) + object.returnPartialSuccess = message.returnPartialSuccess; + return object; + }; + + /** + * Converts this ListOperationsRequest to JSON. + * @function toJSON + * @memberof google.longrunning.ListOperationsRequest + * @instance + * @returns {Object.} JSON object + */ + ListOperationsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListOperationsRequest + * @function getTypeUrl + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListOperationsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.ListOperationsRequest"; + }; + + return ListOperationsRequest; + })(); + + longrunning.ListOperationsResponse = (function() { + + /** + * Properties of a ListOperationsResponse. + * @memberof google.longrunning + * @interface IListOperationsResponse + * @property {Array.|null} [operations] ListOperationsResponse operations + * @property {string|null} [nextPageToken] ListOperationsResponse nextPageToken + * @property {Array.|null} [unreachable] ListOperationsResponse unreachable + */ + + /** + * Constructs a new ListOperationsResponse. + * @memberof google.longrunning + * @classdesc Represents a ListOperationsResponse. + * @implements IListOperationsResponse + * @constructor + * @param {google.longrunning.IListOperationsResponse=} [properties] Properties to set + */ + function ListOperationsResponse(properties) { + this.operations = []; + this.unreachable = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListOperationsResponse operations. + * @member {Array.} operations + * @memberof google.longrunning.ListOperationsResponse + * @instance + */ + ListOperationsResponse.prototype.operations = $util.emptyArray; + + /** + * ListOperationsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.longrunning.ListOperationsResponse + * @instance + */ + ListOperationsResponse.prototype.nextPageToken = ""; + + /** + * ListOperationsResponse unreachable. + * @member {Array.} unreachable + * @memberof google.longrunning.ListOperationsResponse + * @instance + */ + ListOperationsResponse.prototype.unreachable = $util.emptyArray; + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.ListOperationsResponse} ListOperationsResponse + */ + ListOperationsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.ListOperationsResponse) + return object; + var message = new $root.google.longrunning.ListOperationsResponse(); + if (object.operations) { + if (!Array.isArray(object.operations)) + throw TypeError(".google.longrunning.ListOperationsResponse.operations: array expected"); + message.operations = []; + for (var i = 0; i < object.operations.length; ++i) { + if (typeof object.operations[i] !== "object") + throw TypeError(".google.longrunning.ListOperationsResponse.operations: object expected"); + message.operations[i] = $root.google.longrunning.Operation.fromObject(object.operations[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + if (object.unreachable) { + if (!Array.isArray(object.unreachable)) + throw TypeError(".google.longrunning.ListOperationsResponse.unreachable: array expected"); + message.unreachable = []; + for (var i = 0; i < object.unreachable.length; ++i) + message.unreachable[i] = String(object.unreachable[i]); + } + return message; + }; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {google.longrunning.ListOperationsResponse} message ListOperationsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListOperationsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.operations = []; + object.unreachable = []; + } + if (options.defaults) + object.nextPageToken = ""; + if (message.operations && message.operations.length) { + object.operations = []; + for (var j = 0; j < message.operations.length; ++j) + object.operations[j] = $root.google.longrunning.Operation.toObject(message.operations[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + if (message.unreachable && message.unreachable.length) { + object.unreachable = []; + for (var j = 0; j < message.unreachable.length; ++j) + object.unreachable[j] = message.unreachable[j]; + } + return object; + }; + + /** + * Converts this ListOperationsResponse to JSON. + * @function toJSON + * @memberof google.longrunning.ListOperationsResponse + * @instance + * @returns {Object.} JSON object + */ + ListOperationsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListOperationsResponse + * @function getTypeUrl + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListOperationsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.ListOperationsResponse"; + }; + + return ListOperationsResponse; + })(); + + longrunning.CancelOperationRequest = (function() { + + /** + * Properties of a CancelOperationRequest. + * @memberof google.longrunning + * @interface ICancelOperationRequest + * @property {string|null} [name] CancelOperationRequest name + */ + + /** + * Constructs a new CancelOperationRequest. + * @memberof google.longrunning + * @classdesc Represents a CancelOperationRequest. + * @implements ICancelOperationRequest + * @constructor + * @param {google.longrunning.ICancelOperationRequest=} [properties] Properties to set + */ + function CancelOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CancelOperationRequest name. + * @member {string} name + * @memberof google.longrunning.CancelOperationRequest + * @instance + */ + CancelOperationRequest.prototype.name = ""; + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.CancelOperationRequest} CancelOperationRequest + */ + CancelOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.CancelOperationRequest) + return object; + var message = new $root.google.longrunning.CancelOperationRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {google.longrunning.CancelOperationRequest} message CancelOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CancelOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this CancelOperationRequest to JSON. + * @function toJSON + * @memberof google.longrunning.CancelOperationRequest + * @instance + * @returns {Object.} JSON object + */ + CancelOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CancelOperationRequest + * @function getTypeUrl + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CancelOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.CancelOperationRequest"; + }; + + return CancelOperationRequest; + })(); + + longrunning.DeleteOperationRequest = (function() { + + /** + * Properties of a DeleteOperationRequest. + * @memberof google.longrunning + * @interface IDeleteOperationRequest + * @property {string|null} [name] DeleteOperationRequest name + */ + + /** + * Constructs a new DeleteOperationRequest. + * @memberof google.longrunning + * @classdesc Represents a DeleteOperationRequest. + * @implements IDeleteOperationRequest + * @constructor + * @param {google.longrunning.IDeleteOperationRequest=} [properties] Properties to set + */ + function DeleteOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteOperationRequest name. + * @member {string} name + * @memberof google.longrunning.DeleteOperationRequest + * @instance + */ + DeleteOperationRequest.prototype.name = ""; + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.DeleteOperationRequest} DeleteOperationRequest + */ + DeleteOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.DeleteOperationRequest) + return object; + var message = new $root.google.longrunning.DeleteOperationRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {google.longrunning.DeleteOperationRequest} message DeleteOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @function toJSON + * @memberof google.longrunning.DeleteOperationRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteOperationRequest + * @function getTypeUrl + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.DeleteOperationRequest"; + }; + + return DeleteOperationRequest; + })(); + + longrunning.WaitOperationRequest = (function() { + + /** + * Properties of a WaitOperationRequest. + * @memberof google.longrunning + * @interface IWaitOperationRequest + * @property {string|null} [name] WaitOperationRequest name + * @property {google.protobuf.IDuration|null} [timeout] WaitOperationRequest timeout + */ + + /** + * Constructs a new WaitOperationRequest. + * @memberof google.longrunning + * @classdesc Represents a WaitOperationRequest. + * @implements IWaitOperationRequest + * @constructor + * @param {google.longrunning.IWaitOperationRequest=} [properties] Properties to set + */ + function WaitOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * WaitOperationRequest name. + * @member {string} name + * @memberof google.longrunning.WaitOperationRequest + * @instance + */ + WaitOperationRequest.prototype.name = ""; + + /** + * WaitOperationRequest timeout. + * @member {google.protobuf.IDuration|null|undefined} timeout + * @memberof google.longrunning.WaitOperationRequest + * @instance + */ + WaitOperationRequest.prototype.timeout = null; + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.WaitOperationRequest} WaitOperationRequest + */ + WaitOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.WaitOperationRequest) + return object; + var message = new $root.google.longrunning.WaitOperationRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.timeout != null) { + if (typeof object.timeout !== "object") + throw TypeError(".google.longrunning.WaitOperationRequest.timeout: object expected"); + message.timeout = $root.google.protobuf.Duration.fromObject(object.timeout); + } + return message; + }; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {google.longrunning.WaitOperationRequest} message WaitOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WaitOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.timeout = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.timeout != null && message.hasOwnProperty("timeout")) + object.timeout = $root.google.protobuf.Duration.toObject(message.timeout, options); + return object; + }; + + /** + * Converts this WaitOperationRequest to JSON. + * @function toJSON + * @memberof google.longrunning.WaitOperationRequest + * @instance + * @returns {Object.} JSON object + */ + WaitOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for WaitOperationRequest + * @function getTypeUrl + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WaitOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.WaitOperationRequest"; + }; + + return WaitOperationRequest; + })(); + + longrunning.OperationInfo = (function() { + + /** + * Properties of an OperationInfo. + * @memberof google.longrunning + * @interface IOperationInfo + * @property {string|null} [responseType] OperationInfo responseType + * @property {string|null} [metadataType] OperationInfo metadataType + */ + + /** + * Constructs a new OperationInfo. + * @memberof google.longrunning + * @classdesc Represents an OperationInfo. + * @implements IOperationInfo + * @constructor + * @param {google.longrunning.IOperationInfo=} [properties] Properties to set + */ + function OperationInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OperationInfo responseType. + * @member {string} responseType + * @memberof google.longrunning.OperationInfo + * @instance + */ + OperationInfo.prototype.responseType = ""; + + /** + * OperationInfo metadataType. + * @member {string} metadataType + * @memberof google.longrunning.OperationInfo + * @instance + */ + OperationInfo.prototype.metadataType = ""; + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.OperationInfo + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.OperationInfo} OperationInfo + */ + OperationInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.OperationInfo) + return object; + var message = new $root.google.longrunning.OperationInfo(); + if (object.responseType != null) + message.responseType = String(object.responseType); + if (object.metadataType != null) + message.metadataType = String(object.metadataType); + return message; + }; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.OperationInfo + * @static + * @param {google.longrunning.OperationInfo} message OperationInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OperationInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.responseType = ""; + object.metadataType = ""; + } + if (message.responseType != null && message.hasOwnProperty("responseType")) + object.responseType = message.responseType; + if (message.metadataType != null && message.hasOwnProperty("metadataType")) + object.metadataType = message.metadataType; + return object; + }; + + /** + * Converts this OperationInfo to JSON. + * @function toJSON + * @memberof google.longrunning.OperationInfo + * @instance + * @returns {Object.} JSON object + */ + OperationInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OperationInfo + * @function getTypeUrl + * @memberof google.longrunning.OperationInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OperationInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.OperationInfo"; + }; + + return OperationInfo; + })(); + + return longrunning; + })(); + + google.rpc = (function() { + + /** + * Namespace rpc. + * @memberof google + * @namespace + */ + var rpc = {}; + + rpc.Status = (function() { + + /** + * Properties of a Status. + * @memberof google.rpc + * @interface IStatus + * @property {number|null} [code] Status code + * @property {string|null} [message] Status message + * @property {Array.|null} [details] Status details + */ + + /** + * Constructs a new Status. + * @memberof google.rpc + * @classdesc Represents a Status. + * @implements IStatus + * @constructor + * @param {google.rpc.IStatus=} [properties] Properties to set + */ + function Status(properties) { + this.details = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Status code. + * @member {number} code + * @memberof google.rpc.Status + * @instance + */ + Status.prototype.code = 0; + + /** + * Status message. + * @member {string} message + * @memberof google.rpc.Status + * @instance + */ + Status.prototype.message = ""; + + /** + * Status details. + * @member {Array.} details + * @memberof google.rpc.Status + * @instance + */ + Status.prototype.details = $util.emptyArray; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.Status + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.Status} Status + */ + Status.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.Status) + return object; + var message = new $root.google.rpc.Status(); + if (object.code != null) + message.code = object.code | 0; + if (object.message != null) + message.message = String(object.message); + if (object.details) { + if (!Array.isArray(object.details)) + throw TypeError(".google.rpc.Status.details: array expected"); + message.details = []; + for (var i = 0; i < object.details.length; ++i) { + if (typeof object.details[i] !== "object") + throw TypeError(".google.rpc.Status.details: object expected"); + message.details[i] = $root.google.protobuf.Any.fromObject(object.details[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.Status + * @static + * @param {google.rpc.Status} message Status + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Status.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.details = []; + if (options.defaults) { + object.code = 0; + object.message = ""; + } + if (message.code != null && message.hasOwnProperty("code")) + object.code = message.code; + if (message.message != null && message.hasOwnProperty("message")) + object.message = message.message; + if (message.details && message.details.length) { + object.details = []; + for (var j = 0; j < message.details.length; ++j) + object.details[j] = $root.google.protobuf.Any.toObject(message.details[j], options); + } + return object; + }; + + /** + * Converts this Status to JSON. + * @function toJSON + * @memberof google.rpc.Status + * @instance + * @returns {Object.} JSON object + */ + Status.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Status + * @function getTypeUrl + * @memberof google.rpc.Status + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Status.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.Status"; + }; + + return Status; + })(); + + return rpc; + })(); + + return google; + })(); + + return $root; +}); diff --git a/handwritten/firestore/dev/protos/firestore_v1_proto_api.d.ts b/handwritten/firestore/dev/protos/firestore_v1_proto_api.d.ts new file mode 100644 index 00000000000..333cb9f564c --- /dev/null +++ b/handwritten/firestore/dev/protos/firestore_v1_proto_api.d.ts @@ -0,0 +1,11156 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as $protobuf from "protobufjs"; +import Long = require("long"); +/** Namespace firestore. */ +export namespace firestore { + + /** Properties of a BundledQuery. */ + interface IBundledQuery { + + /** BundledQuery parent */ + parent?: (string|null); + + /** BundledQuery structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** BundledQuery limitType */ + limitType?: (firestore.BundledQuery.LimitType|null); + } + + /** Represents a BundledQuery. */ + class BundledQuery implements IBundledQuery { + + /** + * Constructs a new BundledQuery. + * @param [properties] Properties to set + */ + constructor(properties?: firestore.IBundledQuery); + + /** BundledQuery parent. */ + public parent: string; + + /** BundledQuery structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** BundledQuery limitType. */ + public limitType: firestore.BundledQuery.LimitType; + + /** BundledQuery queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a BundledQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BundledQuery + */ + public static fromObject(object: { [k: string]: any }): firestore.BundledQuery; + + /** + * Creates a plain object from a BundledQuery message. Also converts values to other types if specified. + * @param message BundledQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: firestore.BundledQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BundledQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BundledQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace BundledQuery { + + /** LimitType enum. */ + type LimitType = + "FIRST"| "LAST"; + } + + /** Properties of a NamedQuery. */ + interface INamedQuery { + + /** NamedQuery name */ + name?: (string|null); + + /** NamedQuery bundledQuery */ + bundledQuery?: (firestore.IBundledQuery|null); + + /** NamedQuery readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a NamedQuery. */ + class NamedQuery implements INamedQuery { + + /** + * Constructs a new NamedQuery. + * @param [properties] Properties to set + */ + constructor(properties?: firestore.INamedQuery); + + /** NamedQuery name. */ + public name: string; + + /** NamedQuery bundledQuery. */ + public bundledQuery?: (firestore.IBundledQuery|null); + + /** NamedQuery readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a NamedQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamedQuery + */ + public static fromObject(object: { [k: string]: any }): firestore.NamedQuery; + + /** + * Creates a plain object from a NamedQuery message. Also converts values to other types if specified. + * @param message NamedQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: firestore.NamedQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamedQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamedQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BundledDocumentMetadata. */ + interface IBundledDocumentMetadata { + + /** BundledDocumentMetadata name */ + name?: (string|null); + + /** BundledDocumentMetadata readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** BundledDocumentMetadata exists */ + exists?: (boolean|null); + + /** BundledDocumentMetadata queries */ + queries?: (string[]|null); + } + + /** Represents a BundledDocumentMetadata. */ + class BundledDocumentMetadata implements IBundledDocumentMetadata { + + /** + * Constructs a new BundledDocumentMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: firestore.IBundledDocumentMetadata); + + /** BundledDocumentMetadata name. */ + public name: string; + + /** BundledDocumentMetadata readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BundledDocumentMetadata exists. */ + public exists: boolean; + + /** BundledDocumentMetadata queries. */ + public queries: string[]; + + /** + * Creates a BundledDocumentMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BundledDocumentMetadata + */ + public static fromObject(object: { [k: string]: any }): firestore.BundledDocumentMetadata; + + /** + * Creates a plain object from a BundledDocumentMetadata message. Also converts values to other types if specified. + * @param message BundledDocumentMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: firestore.BundledDocumentMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BundledDocumentMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BundledDocumentMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BundleMetadata. */ + interface IBundleMetadata { + + /** BundleMetadata id */ + id?: (string|null); + + /** BundleMetadata createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** BundleMetadata version */ + version?: (number|null); + + /** BundleMetadata totalDocuments */ + totalDocuments?: (number|null); + + /** BundleMetadata totalBytes */ + totalBytes?: (number|string|null); + } + + /** Represents a BundleMetadata. */ + class BundleMetadata implements IBundleMetadata { + + /** + * Constructs a new BundleMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: firestore.IBundleMetadata); + + /** BundleMetadata id. */ + public id: string; + + /** BundleMetadata createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** BundleMetadata version. */ + public version: number; + + /** BundleMetadata totalDocuments. */ + public totalDocuments: number; + + /** BundleMetadata totalBytes. */ + public totalBytes: (number|string); + + /** + * Creates a BundleMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BundleMetadata + */ + public static fromObject(object: { [k: string]: any }): firestore.BundleMetadata; + + /** + * Creates a plain object from a BundleMetadata message. Also converts values to other types if specified. + * @param message BundleMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: firestore.BundleMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BundleMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BundleMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BundleElement. */ + interface IBundleElement { + + /** BundleElement metadata */ + metadata?: (firestore.IBundleMetadata|null); + + /** BundleElement namedQuery */ + namedQuery?: (firestore.INamedQuery|null); + + /** BundleElement documentMetadata */ + documentMetadata?: (firestore.IBundledDocumentMetadata|null); + + /** BundleElement document */ + document?: (google.firestore.v1.IDocument|null); + } + + /** Represents a BundleElement. */ + class BundleElement implements IBundleElement { + + /** + * Constructs a new BundleElement. + * @param [properties] Properties to set + */ + constructor(properties?: firestore.IBundleElement); + + /** BundleElement metadata. */ + public metadata?: (firestore.IBundleMetadata|null); + + /** BundleElement namedQuery. */ + public namedQuery?: (firestore.INamedQuery|null); + + /** BundleElement documentMetadata. */ + public documentMetadata?: (firestore.IBundledDocumentMetadata|null); + + /** BundleElement document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** BundleElement elementType. */ + public elementType?: ("metadata"|"namedQuery"|"documentMetadata"|"document"); + + /** + * Creates a BundleElement message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BundleElement + */ + public static fromObject(object: { [k: string]: any }): firestore.BundleElement; + + /** + * Creates a plain object from a BundleElement message. Also converts values to other types if specified. + * @param message BundleElement + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: firestore.BundleElement, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BundleElement to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BundleElement + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } +} + +/** Namespace google. */ +export namespace google { + + /** Namespace firestore. */ + namespace firestore { + + /** Namespace v1. */ + namespace v1 { + + /** Properties of an AggregationResult. */ + interface IAggregationResult { + + /** AggregationResult aggregateFields */ + aggregateFields?: ({ [k: string]: google.firestore.v1.IValue }|null); + } + + /** Represents an AggregationResult. */ + class AggregationResult implements IAggregationResult { + + /** + * Constructs a new AggregationResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IAggregationResult); + + /** AggregationResult aggregateFields. */ + public aggregateFields: { [k: string]: google.firestore.v1.IValue }; + + /** + * Creates an AggregationResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AggregationResult + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.AggregationResult; + + /** + * Creates a plain object from an AggregationResult message. Also converts values to other types if specified. + * @param message AggregationResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.AggregationResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AggregationResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AggregationResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Document. */ + interface IDocument { + + /** Document name */ + name?: (string|null); + + /** Document fields */ + fields?: ({ [k: string]: google.firestore.v1.IValue }|null); + + /** Document createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** Document updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a Document. */ + class Document implements IDocument { + + /** + * Constructs a new Document. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocument); + + /** Document name. */ + public name: string; + + /** Document fields. */ + public fields: { [k: string]: google.firestore.v1.IValue }; + + /** Document createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** Document updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a Document message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Document + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Document; + + /** + * Creates a plain object from a Document message. Also converts values to other types if specified. + * @param message Document + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Document, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Document to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Document + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value booleanValue */ + booleanValue?: (boolean|null); + + /** Value integerValue */ + integerValue?: (number|string|null); + + /** Value doubleValue */ + doubleValue?: (number|null); + + /** Value timestampValue */ + timestampValue?: (google.protobuf.ITimestamp|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value bytesValue */ + bytesValue?: (Uint8Array|null); + + /** Value referenceValue */ + referenceValue?: (string|null); + + /** Value geoPointValue */ + geoPointValue?: (google.type.ILatLng|null); + + /** Value arrayValue */ + arrayValue?: (google.firestore.v1.IArrayValue|null); + + /** Value mapValue */ + mapValue?: (google.firestore.v1.IMapValue|null); + + /** Value fieldReferenceValue */ + fieldReferenceValue?: (string|null); + + /** Value functionValue */ + functionValue?: (google.firestore.v1.IFunction|null); + + /** Value pipelineValue */ + pipelineValue?: (google.firestore.v1.IPipeline|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value booleanValue. */ + public booleanValue?: (boolean|null); + + /** Value integerValue. */ + public integerValue?: (number|string|null); + + /** Value doubleValue. */ + public doubleValue?: (number|null); + + /** Value timestampValue. */ + public timestampValue?: (google.protobuf.ITimestamp|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value bytesValue. */ + public bytesValue?: (Uint8Array|null); + + /** Value referenceValue. */ + public referenceValue?: (string|null); + + /** Value geoPointValue. */ + public geoPointValue?: (google.type.ILatLng|null); + + /** Value arrayValue. */ + public arrayValue?: (google.firestore.v1.IArrayValue|null); + + /** Value mapValue. */ + public mapValue?: (google.firestore.v1.IMapValue|null); + + /** Value fieldReferenceValue. */ + public fieldReferenceValue?: (string|null); + + /** Value functionValue. */ + public functionValue?: (google.firestore.v1.IFunction|null); + + /** Value pipelineValue. */ + public pipelineValue?: (google.firestore.v1.IPipeline|null); + + /** Value valueType. */ + public valueType?: ("nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"|"fieldReferenceValue"|"functionValue"|"pipelineValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ArrayValue. */ + interface IArrayValue { + + /** ArrayValue values */ + values?: (google.firestore.v1.IValue[]|null); + } + + /** Represents an ArrayValue. */ + class ArrayValue implements IArrayValue { + + /** + * Constructs a new ArrayValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IArrayValue); + + /** ArrayValue values. */ + public values: google.firestore.v1.IValue[]; + + /** + * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ArrayValue + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ArrayValue; + + /** + * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. + * @param message ArrayValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ArrayValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ArrayValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ArrayValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MapValue. */ + interface IMapValue { + + /** MapValue fields */ + fields?: ({ [k: string]: google.firestore.v1.IValue }|null); + } + + /** Represents a MapValue. */ + class MapValue implements IMapValue { + + /** + * Constructs a new MapValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IMapValue); + + /** MapValue fields. */ + public fields: { [k: string]: google.firestore.v1.IValue }; + + /** + * Creates a MapValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MapValue + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.MapValue; + + /** + * Creates a plain object from a MapValue message. Also converts values to other types if specified. + * @param message MapValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.MapValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MapValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MapValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Function. */ + interface IFunction { + + /** Function name */ + name?: (string|null); + + /** Function args */ + args?: (google.firestore.v1.IValue[]|null); + + /** Function options */ + options?: ({ [k: string]: google.firestore.v1.IValue }|null); + } + + /** Represents a Function. */ + class Function implements IFunction { + + /** + * Constructs a new Function. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IFunction); + + /** Function name. */ + public name: string; + + /** Function args. */ + public args: google.firestore.v1.IValue[]; + + /** Function options. */ + public options: { [k: string]: google.firestore.v1.IValue }; + + /** + * Creates a Function message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Function + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Function; + + /** + * Creates a plain object from a Function message. Also converts values to other types if specified. + * @param message Function + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Function, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Function to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Function + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Pipeline. */ + interface IPipeline { + + /** Pipeline stages */ + stages?: (google.firestore.v1.Pipeline.IStage[]|null); + } + + /** Represents a Pipeline. */ + class Pipeline implements IPipeline { + + /** + * Constructs a new Pipeline. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPipeline); + + /** Pipeline stages. */ + public stages: google.firestore.v1.Pipeline.IStage[]; + + /** + * Creates a Pipeline message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Pipeline + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Pipeline; + + /** + * Creates a plain object from a Pipeline message. Also converts values to other types if specified. + * @param message Pipeline + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Pipeline, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Pipeline to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Pipeline + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Pipeline { + + /** Properties of a Stage. */ + interface IStage { + + /** Stage name */ + name?: (string|null); + + /** Stage args */ + args?: (google.firestore.v1.IValue[]|null); + + /** Stage options */ + options?: ({ [k: string]: google.firestore.v1.IValue }|null); + } + + /** Represents a Stage. */ + class Stage implements IStage { + + /** + * Constructs a new Stage. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.Pipeline.IStage); + + /** Stage name. */ + public name: string; + + /** Stage args. */ + public args: google.firestore.v1.IValue[]; + + /** Stage options. */ + public options: { [k: string]: google.firestore.v1.IValue }; + + /** + * Creates a Stage message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Stage + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Pipeline.Stage; + + /** + * Creates a plain object from a Stage message. Also converts values to other types if specified. + * @param message Stage + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Pipeline.Stage, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Stage to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Stage + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a BitSequence. */ + interface IBitSequence { + + /** BitSequence bitmap */ + bitmap?: (Uint8Array|null); + + /** BitSequence padding */ + padding?: (number|null); + } + + /** Represents a BitSequence. */ + class BitSequence implements IBitSequence { + + /** + * Constructs a new BitSequence. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBitSequence); + + /** BitSequence bitmap. */ + public bitmap: Uint8Array; + + /** BitSequence padding. */ + public padding: number; + + /** + * Creates a BitSequence message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BitSequence + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BitSequence; + + /** + * Creates a plain object from a BitSequence message. Also converts values to other types if specified. + * @param message BitSequence + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BitSequence, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BitSequence to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BitSequence + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BloomFilter. */ + interface IBloomFilter { + + /** BloomFilter bits */ + bits?: (google.firestore.v1.IBitSequence|null); + + /** BloomFilter hashCount */ + hashCount?: (number|null); + } + + /** Represents a BloomFilter. */ + class BloomFilter implements IBloomFilter { + + /** + * Constructs a new BloomFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBloomFilter); + + /** BloomFilter bits. */ + public bits?: (google.firestore.v1.IBitSequence|null); + + /** BloomFilter hashCount. */ + public hashCount: number; + + /** + * Creates a BloomFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BloomFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BloomFilter; + + /** + * Creates a plain object from a BloomFilter message. Also converts values to other types if specified. + * @param message BloomFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BloomFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BloomFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BloomFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentMask. */ + interface IDocumentMask { + + /** DocumentMask fieldPaths */ + fieldPaths?: (string[]|null); + } + + /** Represents a DocumentMask. */ + class DocumentMask implements IDocumentMask { + + /** + * Constructs a new DocumentMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentMask); + + /** DocumentMask fieldPaths. */ + public fieldPaths: string[]; + + /** + * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentMask + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentMask; + + /** + * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. + * @param message DocumentMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Precondition. */ + interface IPrecondition { + + /** Precondition exists */ + exists?: (boolean|null); + + /** Precondition updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a Precondition. */ + class Precondition implements IPrecondition { + + /** + * Constructs a new Precondition. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPrecondition); + + /** Precondition exists. */ + public exists?: (boolean|null); + + /** Precondition updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** Precondition conditionType. */ + public conditionType?: ("exists"|"updateTime"); + + /** + * Creates a Precondition message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Precondition + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Precondition; + + /** + * Creates a plain object from a Precondition message. Also converts values to other types if specified. + * @param message Precondition + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Precondition, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Precondition to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Precondition + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TransactionOptions. */ + interface ITransactionOptions { + + /** TransactionOptions readOnly */ + readOnly?: (google.firestore.v1.TransactionOptions.IReadOnly|null); + + /** TransactionOptions readWrite */ + readWrite?: (google.firestore.v1.TransactionOptions.IReadWrite|null); + } + + /** Represents a TransactionOptions. */ + class TransactionOptions implements ITransactionOptions { + + /** + * Constructs a new TransactionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ITransactionOptions); + + /** TransactionOptions readOnly. */ + public readOnly?: (google.firestore.v1.TransactionOptions.IReadOnly|null); + + /** TransactionOptions readWrite. */ + public readWrite?: (google.firestore.v1.TransactionOptions.IReadWrite|null); + + /** TransactionOptions mode. */ + public mode?: ("readOnly"|"readWrite"); + + /** + * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TransactionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions; + + /** + * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. + * @param message TransactionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TransactionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TransactionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TransactionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TransactionOptions { + + /** Properties of a ReadWrite. */ + interface IReadWrite { + + /** ReadWrite retryTransaction */ + retryTransaction?: (Uint8Array|null); + } + + /** Represents a ReadWrite. */ + class ReadWrite implements IReadWrite { + + /** + * Constructs a new ReadWrite. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.TransactionOptions.IReadWrite); + + /** ReadWrite retryTransaction. */ + public retryTransaction: Uint8Array; + + /** + * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadWrite + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions.ReadWrite; + + /** + * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. + * @param message ReadWrite + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TransactionOptions.ReadWrite, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadWrite to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadWrite + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReadOnly. */ + interface IReadOnly { + + /** ReadOnly readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a ReadOnly. */ + class ReadOnly implements IReadOnly { + + /** + * Constructs a new ReadOnly. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.TransactionOptions.IReadOnly); + + /** ReadOnly readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ReadOnly consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadOnly + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions.ReadOnly; + + /** + * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. + * @param message ReadOnly + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TransactionOptions.ReadOnly, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadOnly to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadOnly + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExplainStats. */ + interface IExplainStats { + + /** ExplainStats data */ + data?: (google.protobuf.IAny|null); + } + + /** Represents an ExplainStats. */ + class ExplainStats implements IExplainStats { + + /** + * Constructs a new ExplainStats. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExplainStats); + + /** ExplainStats data. */ + public data?: (google.protobuf.IAny|null); + + /** + * Creates an ExplainStats message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExplainStats + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainStats; + + /** + * Creates a plain object from an ExplainStats message. Also converts values to other types if specified. + * @param message ExplainStats + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExplainStats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExplainStats to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExplainStats + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Represents a Firestore */ + class Firestore extends $protobuf.rpc.Service { + + /** + * Constructs a new Firestore service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls GetDocument. + * @param request GetDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public getDocument(request: google.firestore.v1.IGetDocumentRequest, callback: google.firestore.v1.Firestore.GetDocumentCallback): void; + + /** + * Calls GetDocument. + * @param request GetDocumentRequest message or plain object + * @returns Promise + */ + public getDocument(request: google.firestore.v1.IGetDocumentRequest): Promise; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDocumentsResponse + */ + public listDocuments(request: google.firestore.v1.IListDocumentsRequest, callback: google.firestore.v1.Firestore.ListDocumentsCallback): void; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @returns Promise + */ + public listDocuments(request: google.firestore.v1.IListDocumentsRequest): Promise; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public updateDocument(request: google.firestore.v1.IUpdateDocumentRequest, callback: google.firestore.v1.Firestore.UpdateDocumentCallback): void; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @returns Promise + */ + public updateDocument(request: google.firestore.v1.IUpdateDocumentRequest): Promise; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteDocument(request: google.firestore.v1.IDeleteDocumentRequest, callback: google.firestore.v1.Firestore.DeleteDocumentCallback): void; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @returns Promise + */ + public deleteDocument(request: google.firestore.v1.IDeleteDocumentRequest): Promise; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse + */ + public batchGetDocuments(request: google.firestore.v1.IBatchGetDocumentsRequest, callback: google.firestore.v1.Firestore.BatchGetDocumentsCallback): void; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @returns Promise + */ + public batchGetDocuments(request: google.firestore.v1.IBatchGetDocumentsRequest): Promise; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BeginTransactionResponse + */ + public beginTransaction(request: google.firestore.v1.IBeginTransactionRequest, callback: google.firestore.v1.Firestore.BeginTransactionCallback): void; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @returns Promise + */ + public beginTransaction(request: google.firestore.v1.IBeginTransactionRequest): Promise; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @param callback Node-style callback called with the error, if any, and CommitResponse + */ + public commit(request: google.firestore.v1.ICommitRequest, callback: google.firestore.v1.Firestore.CommitCallback): void; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @returns Promise + */ + public commit(request: google.firestore.v1.ICommitRequest): Promise; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public rollback(request: google.firestore.v1.IRollbackRequest, callback: google.firestore.v1.Firestore.RollbackCallback): void; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @returns Promise + */ + public rollback(request: google.firestore.v1.IRollbackRequest): Promise; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RunQueryResponse + */ + public runQuery(request: google.firestore.v1.IRunQueryRequest, callback: google.firestore.v1.Firestore.RunQueryCallback): void; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @returns Promise + */ + public runQuery(request: google.firestore.v1.IRunQueryRequest): Promise; + + /** + * Calls ExecutePipeline. + * @param request ExecutePipelineRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ExecutePipelineResponse + */ + public executePipeline(request: google.firestore.v1.IExecutePipelineRequest, callback: google.firestore.v1.Firestore.ExecutePipelineCallback): void; + + /** + * Calls ExecutePipeline. + * @param request ExecutePipelineRequest message or plain object + * @returns Promise + */ + public executePipeline(request: google.firestore.v1.IExecutePipelineRequest): Promise; + + /** + * Calls RunAggregationQuery. + * @param request RunAggregationQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RunAggregationQueryResponse + */ + public runAggregationQuery(request: google.firestore.v1.IRunAggregationQueryRequest, callback: google.firestore.v1.Firestore.RunAggregationQueryCallback): void; + + /** + * Calls RunAggregationQuery. + * @param request RunAggregationQueryRequest message or plain object + * @returns Promise + */ + public runAggregationQuery(request: google.firestore.v1.IRunAggregationQueryRequest): Promise; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and PartitionQueryResponse + */ + public partitionQuery(request: google.firestore.v1.IPartitionQueryRequest, callback: google.firestore.v1.Firestore.PartitionQueryCallback): void; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @returns Promise + */ + public partitionQuery(request: google.firestore.v1.IPartitionQueryRequest): Promise; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and WriteResponse + */ + public write(request: google.firestore.v1.IWriteRequest, callback: google.firestore.v1.Firestore.WriteCallback): void; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @returns Promise + */ + public write(request: google.firestore.v1.IWriteRequest): Promise; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListenResponse + */ + public listen(request: google.firestore.v1.IListenRequest, callback: google.firestore.v1.Firestore.ListenCallback): void; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @returns Promise + */ + public listen(request: google.firestore.v1.IListenRequest): Promise; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListCollectionIdsResponse + */ + public listCollectionIds(request: google.firestore.v1.IListCollectionIdsRequest, callback: google.firestore.v1.Firestore.ListCollectionIdsCallback): void; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @returns Promise + */ + public listCollectionIds(request: google.firestore.v1.IListCollectionIdsRequest): Promise; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchWriteResponse + */ + public batchWrite(request: google.firestore.v1.IBatchWriteRequest, callback: google.firestore.v1.Firestore.BatchWriteCallback): void; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @returns Promise + */ + public batchWrite(request: google.firestore.v1.IBatchWriteRequest): Promise; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public createDocument(request: google.firestore.v1.ICreateDocumentRequest, callback: google.firestore.v1.Firestore.CreateDocumentCallback): void; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @returns Promise + */ + public createDocument(request: google.firestore.v1.ICreateDocumentRequest): Promise; + } + + namespace Firestore { + + /** + * Callback as used by {@link google.firestore.v1.Firestore#getDocument}. + * @param error Error, if any + * @param [response] Document + */ + type GetDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listDocuments}. + * @param error Error, if any + * @param [response] ListDocumentsResponse + */ + type ListDocumentsCallback = (error: (Error|null), response?: google.firestore.v1.ListDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#updateDocument}. + * @param error Error, if any + * @param [response] Document + */ + type UpdateDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#deleteDocument}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteDocumentCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#batchGetDocuments}. + * @param error Error, if any + * @param [response] BatchGetDocumentsResponse + */ + type BatchGetDocumentsCallback = (error: (Error|null), response?: google.firestore.v1.BatchGetDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#beginTransaction}. + * @param error Error, if any + * @param [response] BeginTransactionResponse + */ + type BeginTransactionCallback = (error: (Error|null), response?: google.firestore.v1.BeginTransactionResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#commit}. + * @param error Error, if any + * @param [response] CommitResponse + */ + type CommitCallback = (error: (Error|null), response?: google.firestore.v1.CommitResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#rollback}. + * @param error Error, if any + * @param [response] Empty + */ + type RollbackCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#runQuery}. + * @param error Error, if any + * @param [response] RunQueryResponse + */ + type RunQueryCallback = (error: (Error|null), response?: google.firestore.v1.RunQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#executePipeline}. + * @param error Error, if any + * @param [response] ExecutePipelineResponse + */ + type ExecutePipelineCallback = (error: (Error|null), response?: google.firestore.v1.ExecutePipelineResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#runAggregationQuery}. + * @param error Error, if any + * @param [response] RunAggregationQueryResponse + */ + type RunAggregationQueryCallback = (error: (Error|null), response?: google.firestore.v1.RunAggregationQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#partitionQuery}. + * @param error Error, if any + * @param [response] PartitionQueryResponse + */ + type PartitionQueryCallback = (error: (Error|null), response?: google.firestore.v1.PartitionQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#write}. + * @param error Error, if any + * @param [response] WriteResponse + */ + type WriteCallback = (error: (Error|null), response?: google.firestore.v1.WriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listen}. + * @param error Error, if any + * @param [response] ListenResponse + */ + type ListenCallback = (error: (Error|null), response?: google.firestore.v1.ListenResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listCollectionIds}. + * @param error Error, if any + * @param [response] ListCollectionIdsResponse + */ + type ListCollectionIdsCallback = (error: (Error|null), response?: google.firestore.v1.ListCollectionIdsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#batchWrite}. + * @param error Error, if any + * @param [response] BatchWriteResponse + */ + type BatchWriteCallback = (error: (Error|null), response?: google.firestore.v1.BatchWriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#createDocument}. + * @param error Error, if any + * @param [response] Document + */ + type CreateDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + } + + /** Properties of a GetDocumentRequest. */ + interface IGetDocumentRequest { + + /** GetDocumentRequest name */ + name?: (string|null); + + /** GetDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** GetDocumentRequest transaction */ + transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a GetDocumentRequest. */ + class GetDocumentRequest implements IGetDocumentRequest { + + /** + * Constructs a new GetDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IGetDocumentRequest); + + /** GetDocumentRequest name. */ + public name: string; + + /** GetDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** GetDocumentRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** GetDocumentRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.GetDocumentRequest; + + /** + * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. + * @param message GetDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.GetDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsRequest. */ + interface IListDocumentsRequest { + + /** ListDocumentsRequest parent */ + parent?: (string|null); + + /** ListDocumentsRequest collectionId */ + collectionId?: (string|null); + + /** ListDocumentsRequest pageSize */ + pageSize?: (number|null); + + /** ListDocumentsRequest pageToken */ + pageToken?: (string|null); + + /** ListDocumentsRequest orderBy */ + orderBy?: (string|null); + + /** ListDocumentsRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** ListDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing */ + showMissing?: (boolean|null); + } + + /** Represents a ListDocumentsRequest. */ + class ListDocumentsRequest implements IListDocumentsRequest { + + /** + * Constructs a new ListDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListDocumentsRequest); + + /** ListDocumentsRequest parent. */ + public parent: string; + + /** ListDocumentsRequest collectionId. */ + public collectionId: string; + + /** ListDocumentsRequest pageSize. */ + public pageSize: number; + + /** ListDocumentsRequest pageToken. */ + public pageToken: string; + + /** ListDocumentsRequest orderBy. */ + public orderBy: string; + + /** ListDocumentsRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** ListDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing. */ + public showMissing: boolean; + + /** ListDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListDocumentsRequest; + + /** + * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. + * @param message ListDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsResponse. */ + interface IListDocumentsResponse { + + /** ListDocumentsResponse documents */ + documents?: (google.firestore.v1.IDocument[]|null); + + /** ListDocumentsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListDocumentsResponse. */ + class ListDocumentsResponse implements IListDocumentsResponse { + + /** + * Constructs a new ListDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListDocumentsResponse); + + /** ListDocumentsResponse documents. */ + public documents: google.firestore.v1.IDocument[]; + + /** ListDocumentsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListDocumentsResponse; + + /** + * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. + * @param message ListDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDocumentRequest. */ + interface ICreateDocumentRequest { + + /** CreateDocumentRequest parent */ + parent?: (string|null); + + /** CreateDocumentRequest collectionId */ + collectionId?: (string|null); + + /** CreateDocumentRequest documentId */ + documentId?: (string|null); + + /** CreateDocumentRequest document */ + document?: (google.firestore.v1.IDocument|null); + + /** CreateDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + } + + /** Represents a CreateDocumentRequest. */ + class CreateDocumentRequest implements ICreateDocumentRequest { + + /** + * Constructs a new CreateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICreateDocumentRequest); + + /** CreateDocumentRequest parent. */ + public parent: string; + + /** CreateDocumentRequest collectionId. */ + public collectionId: string; + + /** CreateDocumentRequest documentId. */ + public documentId: string; + + /** CreateDocumentRequest document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** CreateDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** + * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CreateDocumentRequest; + + /** + * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. + * @param message CreateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CreateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDocumentRequest. */ + interface IUpdateDocumentRequest { + + /** UpdateDocumentRequest document */ + document?: (google.firestore.v1.IDocument|null); + + /** UpdateDocumentRequest updateMask */ + updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); + } + + /** Represents an UpdateDocumentRequest. */ + class UpdateDocumentRequest implements IUpdateDocumentRequest { + + /** + * Constructs a new UpdateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IUpdateDocumentRequest); + + /** UpdateDocumentRequest document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** UpdateDocumentRequest updateMask. */ + public updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); + + /** + * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.UpdateDocumentRequest; + + /** + * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. + * @param message UpdateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.UpdateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDocumentRequest. */ + interface IDeleteDocumentRequest { + + /** DeleteDocumentRequest name */ + name?: (string|null); + + /** DeleteDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); + } + + /** Represents a DeleteDocumentRequest. */ + class DeleteDocumentRequest implements IDeleteDocumentRequest { + + /** + * Constructs a new DeleteDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDeleteDocumentRequest); + + /** DeleteDocumentRequest name. */ + public name: string; + + /** DeleteDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); + + /** + * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DeleteDocumentRequest; + + /** + * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. + * @param message DeleteDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DeleteDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsRequest. */ + interface IBatchGetDocumentsRequest { + + /** BatchGetDocumentsRequest database */ + database?: (string|null); + + /** BatchGetDocumentsRequest documents */ + documents?: (string[]|null); + + /** BatchGetDocumentsRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsRequest. */ + class BatchGetDocumentsRequest implements IBatchGetDocumentsRequest { + + /** + * Constructs a new BatchGetDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchGetDocumentsRequest); + + /** BatchGetDocumentsRequest database. */ + public database: string; + + /** BatchGetDocumentsRequest documents. */ + public documents: string[]; + + /** BatchGetDocumentsRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchGetDocumentsRequest; + + /** + * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. + * @param message BatchGetDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchGetDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsResponse. */ + interface IBatchGetDocumentsResponse { + + /** BatchGetDocumentsResponse found */ + found?: (google.firestore.v1.IDocument|null); + + /** BatchGetDocumentsResponse missing */ + missing?: (string|null); + + /** BatchGetDocumentsResponse transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsResponse. */ + class BatchGetDocumentsResponse implements IBatchGetDocumentsResponse { + + /** + * Constructs a new BatchGetDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchGetDocumentsResponse); + + /** BatchGetDocumentsResponse found. */ + public found?: (google.firestore.v1.IDocument|null); + + /** BatchGetDocumentsResponse missing. */ + public missing?: (string|null); + + /** BatchGetDocumentsResponse transaction. */ + public transaction: Uint8Array; + + /** BatchGetDocumentsResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsResponse result. */ + public result?: ("found"|"missing"); + + /** + * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchGetDocumentsResponse; + + /** + * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. + * @param message BatchGetDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchGetDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionRequest. */ + interface IBeginTransactionRequest { + + /** BeginTransactionRequest database */ + database?: (string|null); + + /** BeginTransactionRequest options */ + options?: (google.firestore.v1.ITransactionOptions|null); + } + + /** Represents a BeginTransactionRequest. */ + class BeginTransactionRequest implements IBeginTransactionRequest { + + /** + * Constructs a new BeginTransactionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBeginTransactionRequest); + + /** BeginTransactionRequest database. */ + public database: string; + + /** BeginTransactionRequest options. */ + public options?: (google.firestore.v1.ITransactionOptions|null); + + /** + * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BeginTransactionRequest; + + /** + * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. + * @param message BeginTransactionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BeginTransactionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionResponse. */ + interface IBeginTransactionResponse { + + /** BeginTransactionResponse transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a BeginTransactionResponse. */ + class BeginTransactionResponse implements IBeginTransactionResponse { + + /** + * Constructs a new BeginTransactionResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBeginTransactionResponse); + + /** BeginTransactionResponse transaction. */ + public transaction: Uint8Array; + + /** + * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BeginTransactionResponse; + + /** + * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. + * @param message BeginTransactionResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BeginTransactionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitRequest. */ + interface ICommitRequest { + + /** CommitRequest database */ + database?: (string|null); + + /** CommitRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); + + /** CommitRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a CommitRequest. */ + class CommitRequest implements ICommitRequest { + + /** + * Constructs a new CommitRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICommitRequest); + + /** CommitRequest database. */ + public database: string; + + /** CommitRequest writes. */ + public writes: google.firestore.v1.IWrite[]; + + /** CommitRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CommitRequest; + + /** + * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. + * @param message CommitRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CommitRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitResponse. */ + interface ICommitResponse { + + /** CommitResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); + + /** CommitResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a CommitResponse. */ + class CommitResponse implements ICommitResponse { + + /** + * Constructs a new CommitResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICommitResponse); + + /** CommitResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; + + /** CommitResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CommitResponse; + + /** + * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. + * @param message CommitResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CommitResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RollbackRequest. */ + interface IRollbackRequest { + + /** RollbackRequest database */ + database?: (string|null); + + /** RollbackRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a RollbackRequest. */ + class RollbackRequest implements IRollbackRequest { + + /** + * Constructs a new RollbackRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRollbackRequest); + + /** RollbackRequest database. */ + public database: string; + + /** RollbackRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RollbackRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RollbackRequest; + + /** + * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. + * @param message RollbackRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RollbackRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RollbackRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RollbackRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryRequest. */ + interface IRunQueryRequest { + + /** RunQueryRequest parent */ + parent?: (string|null); + + /** RunQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** RunQueryRequest transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryRequest explainOptions */ + explainOptions?: (google.firestore.v1.IExplainOptions|null); + } + + /** Represents a RunQueryRequest. */ + class RunQueryRequest implements IRunQueryRequest { + + /** + * Constructs a new RunQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunQueryRequest); + + /** RunQueryRequest parent. */ + public parent: string; + + /** RunQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** RunQueryRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryRequest explainOptions. */ + public explainOptions?: (google.firestore.v1.IExplainOptions|null); + + /** RunQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** RunQueryRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunQueryRequest; + + /** + * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. + * @param message RunQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryResponse. */ + interface IRunQueryResponse { + + /** RunQueryResponse transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryResponse document */ + document?: (google.firestore.v1.IDocument|null); + + /** RunQueryResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults */ + skippedResults?: (number|null); + + /** RunQueryResponse done */ + done?: (boolean|null); + + /** RunQueryResponse explainMetrics */ + explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + } + + /** Represents a RunQueryResponse. */ + class RunQueryResponse implements IRunQueryResponse { + + /** + * Constructs a new RunQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunQueryResponse); + + /** RunQueryResponse transaction. */ + public transaction: Uint8Array; + + /** RunQueryResponse document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** RunQueryResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults. */ + public skippedResults: number; + + /** RunQueryResponse done. */ + public done?: (boolean|null); + + /** RunQueryResponse explainMetrics. */ + public explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + + /** RunQueryResponse continuationSelector. */ + public continuationSelector?: "done"; + + /** + * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunQueryResponse; + + /** + * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. + * @param message RunQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExecutePipelineRequest. */ + interface IExecutePipelineRequest { + + /** ExecutePipelineRequest database */ + database?: (string|null); + + /** ExecutePipelineRequest structuredPipeline */ + structuredPipeline?: (google.firestore.v1.IStructuredPipeline|null); + + /** ExecutePipelineRequest transaction */ + transaction?: (Uint8Array|null); + + /** ExecutePipelineRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** ExecutePipelineRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an ExecutePipelineRequest. */ + class ExecutePipelineRequest implements IExecutePipelineRequest { + + /** + * Constructs a new ExecutePipelineRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExecutePipelineRequest); + + /** ExecutePipelineRequest database. */ + public database: string; + + /** ExecutePipelineRequest structuredPipeline. */ + public structuredPipeline?: (google.firestore.v1.IStructuredPipeline|null); + + /** ExecutePipelineRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** ExecutePipelineRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** ExecutePipelineRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ExecutePipelineRequest pipelineType. */ + public pipelineType?: "structuredPipeline"; + + /** ExecutePipelineRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates an ExecutePipelineRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecutePipelineRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutePipelineRequest; + + /** + * Creates a plain object from an ExecutePipelineRequest message. Also converts values to other types if specified. + * @param message ExecutePipelineRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExecutePipelineRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecutePipelineRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecutePipelineRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExecutePipelineResponse. */ + interface IExecutePipelineResponse { + + /** ExecutePipelineResponse transaction */ + transaction?: (Uint8Array|null); + + /** ExecutePipelineResponse results */ + results?: (google.firestore.v1.IDocument[]|null); + + /** ExecutePipelineResponse executionTime */ + executionTime?: (google.protobuf.ITimestamp|null); + + /** ExecutePipelineResponse explainStats */ + explainStats?: (google.firestore.v1.IExplainStats|null); + } + + /** Represents an ExecutePipelineResponse. */ + class ExecutePipelineResponse implements IExecutePipelineResponse { + + /** + * Constructs a new ExecutePipelineResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExecutePipelineResponse); + + /** ExecutePipelineResponse transaction. */ + public transaction: Uint8Array; + + /** ExecutePipelineResponse results. */ + public results: google.firestore.v1.IDocument[]; + + /** ExecutePipelineResponse executionTime. */ + public executionTime?: (google.protobuf.ITimestamp|null); + + /** ExecutePipelineResponse explainStats. */ + public explainStats?: (google.firestore.v1.IExplainStats|null); + + /** + * Creates an ExecutePipelineResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecutePipelineResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutePipelineResponse; + + /** + * Creates a plain object from an ExecutePipelineResponse message. Also converts values to other types if specified. + * @param message ExecutePipelineResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExecutePipelineResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecutePipelineResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecutePipelineResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunAggregationQueryRequest. */ + interface IRunAggregationQueryRequest { + + /** RunAggregationQueryRequest parent */ + parent?: (string|null); + + /** RunAggregationQueryRequest structuredAggregationQuery */ + structuredAggregationQuery?: (google.firestore.v1.IStructuredAggregationQuery|null); + + /** RunAggregationQueryRequest transaction */ + transaction?: (Uint8Array|null); + + /** RunAggregationQueryRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunAggregationQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryRequest explainOptions */ + explainOptions?: (google.firestore.v1.IExplainOptions|null); + } + + /** Represents a RunAggregationQueryRequest. */ + class RunAggregationQueryRequest implements IRunAggregationQueryRequest { + + /** + * Constructs a new RunAggregationQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunAggregationQueryRequest); + + /** RunAggregationQueryRequest parent. */ + public parent: string; + + /** RunAggregationQueryRequest structuredAggregationQuery. */ + public structuredAggregationQuery?: (google.firestore.v1.IStructuredAggregationQuery|null); + + /** RunAggregationQueryRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** RunAggregationQueryRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunAggregationQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryRequest explainOptions. */ + public explainOptions?: (google.firestore.v1.IExplainOptions|null); + + /** RunAggregationQueryRequest queryType. */ + public queryType?: "structuredAggregationQuery"; + + /** RunAggregationQueryRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a RunAggregationQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunAggregationQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunAggregationQueryRequest; + + /** + * Creates a plain object from a RunAggregationQueryRequest message. Also converts values to other types if specified. + * @param message RunAggregationQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunAggregationQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunAggregationQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunAggregationQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunAggregationQueryResponse. */ + interface IRunAggregationQueryResponse { + + /** RunAggregationQueryResponse result */ + result?: (google.firestore.v1.IAggregationResult|null); + + /** RunAggregationQueryResponse transaction */ + transaction?: (Uint8Array|null); + + /** RunAggregationQueryResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryResponse explainMetrics */ + explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + } + + /** Represents a RunAggregationQueryResponse. */ + class RunAggregationQueryResponse implements IRunAggregationQueryResponse { + + /** + * Constructs a new RunAggregationQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunAggregationQueryResponse); + + /** RunAggregationQueryResponse result. */ + public result?: (google.firestore.v1.IAggregationResult|null); + + /** RunAggregationQueryResponse transaction. */ + public transaction: Uint8Array; + + /** RunAggregationQueryResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryResponse explainMetrics. */ + public explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + + /** + * Creates a RunAggregationQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunAggregationQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunAggregationQueryResponse; + + /** + * Creates a plain object from a RunAggregationQueryResponse message. Also converts values to other types if specified. + * @param message RunAggregationQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunAggregationQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunAggregationQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunAggregationQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryRequest. */ + interface IPartitionQueryRequest { + + /** PartitionQueryRequest parent */ + parent?: (string|null); + + /** PartitionQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount */ + partitionCount?: (number|string|null); + + /** PartitionQueryRequest pageToken */ + pageToken?: (string|null); + + /** PartitionQueryRequest pageSize */ + pageSize?: (number|null); + + /** PartitionQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a PartitionQueryRequest. */ + class PartitionQueryRequest implements IPartitionQueryRequest { + + /** + * Constructs a new PartitionQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPartitionQueryRequest); + + /** PartitionQueryRequest parent. */ + public parent: string; + + /** PartitionQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount. */ + public partitionCount: (number|string); + + /** PartitionQueryRequest pageToken. */ + public pageToken: string; + + /** PartitionQueryRequest pageSize. */ + public pageSize: number; + + /** PartitionQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** PartitionQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** PartitionQueryRequest consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PartitionQueryRequest; + + /** + * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. + * @param message PartitionQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.PartitionQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryResponse. */ + interface IPartitionQueryResponse { + + /** PartitionQueryResponse partitions */ + partitions?: (google.firestore.v1.ICursor[]|null); + + /** PartitionQueryResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a PartitionQueryResponse. */ + class PartitionQueryResponse implements IPartitionQueryResponse { + + /** + * Constructs a new PartitionQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPartitionQueryResponse); + + /** PartitionQueryResponse partitions. */ + public partitions: google.firestore.v1.ICursor[]; + + /** PartitionQueryResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PartitionQueryResponse; + + /** + * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. + * @param message PartitionQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.PartitionQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteRequest. */ + interface IWriteRequest { + + /** WriteRequest database */ + database?: (string|null); + + /** WriteRequest streamId */ + streamId?: (string|null); + + /** WriteRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); + + /** WriteRequest streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a WriteRequest. */ + class WriteRequest implements IWriteRequest { + + /** + * Constructs a new WriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteRequest); + + /** WriteRequest database. */ + public database: string; + + /** WriteRequest streamId. */ + public streamId: string; + + /** WriteRequest writes. */ + public writes: google.firestore.v1.IWrite[]; + + /** WriteRequest streamToken. */ + public streamToken: Uint8Array; + + /** WriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteRequest; + + /** + * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. + * @param message WriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteResponse. */ + interface IWriteResponse { + + /** WriteResponse streamId */ + streamId?: (string|null); + + /** WriteResponse streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); + + /** WriteResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a WriteResponse. */ + class WriteResponse implements IWriteResponse { + + /** + * Constructs a new WriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteResponse); + + /** WriteResponse streamId. */ + public streamId: string; + + /** WriteResponse streamToken. */ + public streamToken: Uint8Array; + + /** WriteResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; + + /** WriteResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteResponse; + + /** + * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. + * @param message WriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenRequest. */ + interface IListenRequest { + + /** ListenRequest database */ + database?: (string|null); + + /** ListenRequest addTarget */ + addTarget?: (google.firestore.v1.ITarget|null); + + /** ListenRequest removeTarget */ + removeTarget?: (number|null); + + /** ListenRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a ListenRequest. */ + class ListenRequest implements IListenRequest { + + /** + * Constructs a new ListenRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListenRequest); + + /** ListenRequest database. */ + public database: string; + + /** ListenRequest addTarget. */ + public addTarget?: (google.firestore.v1.ITarget|null); + + /** ListenRequest removeTarget. */ + public removeTarget?: (number|null); + + /** ListenRequest labels. */ + public labels: { [k: string]: string }; + + /** ListenRequest targetChange. */ + public targetChange?: ("addTarget"|"removeTarget"); + + /** + * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListenRequest; + + /** + * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. + * @param message ListenRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListenRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenResponse. */ + interface IListenResponse { + + /** ListenResponse targetChange */ + targetChange?: (google.firestore.v1.ITargetChange|null); + + /** ListenResponse documentChange */ + documentChange?: (google.firestore.v1.IDocumentChange|null); + + /** ListenResponse documentDelete */ + documentDelete?: (google.firestore.v1.IDocumentDelete|null); + + /** ListenResponse documentRemove */ + documentRemove?: (google.firestore.v1.IDocumentRemove|null); + + /** ListenResponse filter */ + filter?: (google.firestore.v1.IExistenceFilter|null); + } + + /** Represents a ListenResponse. */ + class ListenResponse implements IListenResponse { + + /** + * Constructs a new ListenResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListenResponse); + + /** ListenResponse targetChange. */ + public targetChange?: (google.firestore.v1.ITargetChange|null); + + /** ListenResponse documentChange. */ + public documentChange?: (google.firestore.v1.IDocumentChange|null); + + /** ListenResponse documentDelete. */ + public documentDelete?: (google.firestore.v1.IDocumentDelete|null); + + /** ListenResponse documentRemove. */ + public documentRemove?: (google.firestore.v1.IDocumentRemove|null); + + /** ListenResponse filter. */ + public filter?: (google.firestore.v1.IExistenceFilter|null); + + /** ListenResponse responseType. */ + public responseType?: ("targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"); + + /** + * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListenResponse; + + /** + * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. + * @param message ListenResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListenResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Target. */ + interface ITarget { + + /** Target query */ + query?: (google.firestore.v1.Target.IQueryTarget|null); + + /** Target documents */ + documents?: (google.firestore.v1.Target.IDocumentsTarget|null); + + /** Target resumeToken */ + resumeToken?: (Uint8Array|null); + + /** Target readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId */ + targetId?: (number|null); + + /** Target once */ + once?: (boolean|null); + + /** Target expectedCount */ + expectedCount?: (google.protobuf.IInt32Value|null); + } + + /** Represents a Target. */ + class Target implements ITarget { + + /** + * Constructs a new Target. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ITarget); + + /** Target query. */ + public query?: (google.firestore.v1.Target.IQueryTarget|null); + + /** Target documents. */ + public documents?: (google.firestore.v1.Target.IDocumentsTarget|null); + + /** Target resumeToken. */ + public resumeToken?: (Uint8Array|null); + + /** Target readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId. */ + public targetId: number; + + /** Target once. */ + public once: boolean; + + /** Target expectedCount. */ + public expectedCount?: (google.protobuf.IInt32Value|null); + + /** Target targetType. */ + public targetType?: ("query"|"documents"); + + /** Target resumeType. */ + public resumeType?: ("resumeToken"|"readTime"); + + /** + * Creates a Target message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Target + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target; + + /** + * Creates a plain object from a Target message. Also converts values to other types if specified. + * @param message Target + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Target to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Target + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Target { + + /** Properties of a DocumentsTarget. */ + interface IDocumentsTarget { + + /** DocumentsTarget documents */ + documents?: (string[]|null); + } + + /** Represents a DocumentsTarget. */ + class DocumentsTarget implements IDocumentsTarget { + + /** + * Constructs a new DocumentsTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.Target.IDocumentsTarget); + + /** DocumentsTarget documents. */ + public documents: string[]; + + /** + * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentsTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target.DocumentsTarget; + + /** + * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. + * @param message DocumentsTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target.DocumentsTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentsTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentsTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a QueryTarget. */ + interface IQueryTarget { + + /** QueryTarget parent */ + parent?: (string|null); + + /** QueryTarget structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + } + + /** Represents a QueryTarget. */ + class QueryTarget implements IQueryTarget { + + /** + * Constructs a new QueryTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.Target.IQueryTarget); + + /** QueryTarget parent. */ + public parent: string; + + /** QueryTarget structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** QueryTarget queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QueryTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target.QueryTarget; + + /** + * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. + * @param message QueryTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target.QueryTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this QueryTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QueryTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a TargetChange. */ + interface ITargetChange { + + /** TargetChange targetChangeType */ + targetChangeType?: (google.firestore.v1.TargetChange.TargetChangeType|null); + + /** TargetChange targetIds */ + targetIds?: (number[]|null); + + /** TargetChange cause */ + cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken */ + resumeToken?: (Uint8Array|null); + + /** TargetChange readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a TargetChange. */ + class TargetChange implements ITargetChange { + + /** + * Constructs a new TargetChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ITargetChange); + + /** TargetChange targetChangeType. */ + public targetChangeType: google.firestore.v1.TargetChange.TargetChangeType; + + /** TargetChange targetIds. */ + public targetIds: number[]; + + /** TargetChange cause. */ + public cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken. */ + public resumeToken: Uint8Array; + + /** TargetChange readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TargetChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TargetChange; + + /** + * Creates a plain object from a TargetChange message. Also converts values to other types if specified. + * @param message TargetChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TargetChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TargetChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TargetChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TargetChange { + + /** TargetChangeType enum. */ + type TargetChangeType = + "NO_CHANGE"| "ADD"| "REMOVE"| "CURRENT"| "RESET"; + } + + /** Properties of a ListCollectionIdsRequest. */ + interface IListCollectionIdsRequest { + + /** ListCollectionIdsRequest parent */ + parent?: (string|null); + + /** ListCollectionIdsRequest pageSize */ + pageSize?: (number|null); + + /** ListCollectionIdsRequest pageToken */ + pageToken?: (string|null); + + /** ListCollectionIdsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a ListCollectionIdsRequest. */ + class ListCollectionIdsRequest implements IListCollectionIdsRequest { + + /** + * Constructs a new ListCollectionIdsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListCollectionIdsRequest); + + /** ListCollectionIdsRequest parent. */ + public parent: string; + + /** ListCollectionIdsRequest pageSize. */ + public pageSize: number; + + /** ListCollectionIdsRequest pageToken. */ + public pageToken: string; + + /** ListCollectionIdsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ListCollectionIdsRequest consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListCollectionIdsRequest; + + /** + * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. + * @param message ListCollectionIdsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListCollectionIdsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListCollectionIdsResponse. */ + interface IListCollectionIdsResponse { + + /** ListCollectionIdsResponse collectionIds */ + collectionIds?: (string[]|null); + + /** ListCollectionIdsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListCollectionIdsResponse. */ + class ListCollectionIdsResponse implements IListCollectionIdsResponse { + + /** + * Constructs a new ListCollectionIdsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListCollectionIdsResponse); + + /** ListCollectionIdsResponse collectionIds. */ + public collectionIds: string[]; + + /** ListCollectionIdsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListCollectionIdsResponse; + + /** + * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. + * @param message ListCollectionIdsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListCollectionIdsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteRequest. */ + interface IBatchWriteRequest { + + /** BatchWriteRequest database */ + database?: (string|null); + + /** BatchWriteRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); + + /** BatchWriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a BatchWriteRequest. */ + class BatchWriteRequest implements IBatchWriteRequest { + + /** + * Constructs a new BatchWriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchWriteRequest); + + /** BatchWriteRequest database. */ + public database: string; + + /** BatchWriteRequest writes. */ + public writes: google.firestore.v1.IWrite[]; + + /** BatchWriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchWriteRequest; + + /** + * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. + * @param message BatchWriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchWriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteResponse. */ + interface IBatchWriteResponse { + + /** BatchWriteResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); + + /** BatchWriteResponse status */ + status?: (google.rpc.IStatus[]|null); + } + + /** Represents a BatchWriteResponse. */ + class BatchWriteResponse implements IBatchWriteResponse { + + /** + * Constructs a new BatchWriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchWriteResponse); + + /** BatchWriteResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; + + /** BatchWriteResponse status. */ + public status: google.rpc.IStatus[]; + + /** + * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchWriteResponse; + + /** + * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. + * @param message BatchWriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchWriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StructuredPipeline. */ + interface IStructuredPipeline { + + /** StructuredPipeline pipeline */ + pipeline?: (google.firestore.v1.IPipeline|null); + + /** StructuredPipeline options */ + options?: ({ [k: string]: google.firestore.v1.IValue }|null); + } + + /** Represents a StructuredPipeline. */ + class StructuredPipeline implements IStructuredPipeline { + + /** + * Constructs a new StructuredPipeline. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IStructuredPipeline); + + /** StructuredPipeline pipeline. */ + public pipeline?: (google.firestore.v1.IPipeline|null); + + /** StructuredPipeline options. */ + public options: { [k: string]: google.firestore.v1.IValue }; + + /** + * Creates a StructuredPipeline message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredPipeline + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredPipeline; + + /** + * Creates a plain object from a StructuredPipeline message. Also converts values to other types if specified. + * @param message StructuredPipeline + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredPipeline, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructuredPipeline to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredPipeline + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StructuredQuery. */ + interface IStructuredQuery { + + /** StructuredQuery select */ + select?: (google.firestore.v1.StructuredQuery.IProjection|null); + + /** StructuredQuery from */ + from?: (google.firestore.v1.StructuredQuery.ICollectionSelector[]|null); + + /** StructuredQuery where */ + where?: (google.firestore.v1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy */ + orderBy?: (google.firestore.v1.StructuredQuery.IOrder[]|null); + + /** StructuredQuery startAt */ + startAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery endAt */ + endAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery offset */ + offset?: (number|null); + + /** StructuredQuery limit */ + limit?: (google.protobuf.IInt32Value|null); + + /** StructuredQuery findNearest */ + findNearest?: (google.firestore.v1.StructuredQuery.IFindNearest|null); + } + + /** Represents a StructuredQuery. */ + class StructuredQuery implements IStructuredQuery { + + /** + * Constructs a new StructuredQuery. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IStructuredQuery); + + /** StructuredQuery select. */ + public select?: (google.firestore.v1.StructuredQuery.IProjection|null); + + /** StructuredQuery from. */ + public from: google.firestore.v1.StructuredQuery.ICollectionSelector[]; + + /** StructuredQuery where. */ + public where?: (google.firestore.v1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy. */ + public orderBy: google.firestore.v1.StructuredQuery.IOrder[]; + + /** StructuredQuery startAt. */ + public startAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery endAt. */ + public endAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery offset. */ + public offset: number; + + /** StructuredQuery limit. */ + public limit?: (google.protobuf.IInt32Value|null); + + /** StructuredQuery findNearest. */ + public findNearest?: (google.firestore.v1.StructuredQuery.IFindNearest|null); + + /** + * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredQuery + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery; + + /** + * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. + * @param message StructuredQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructuredQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace StructuredQuery { + + /** Properties of a CollectionSelector. */ + interface ICollectionSelector { + + /** CollectionSelector collectionId */ + collectionId?: (string|null); + + /** CollectionSelector allDescendants */ + allDescendants?: (boolean|null); + } + + /** Represents a CollectionSelector. */ + class CollectionSelector implements ICollectionSelector { + + /** + * Constructs a new CollectionSelector. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.ICollectionSelector); + + /** CollectionSelector collectionId. */ + public collectionId: string; + + /** CollectionSelector allDescendants. */ + public allDescendants: boolean; + + /** + * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CollectionSelector + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.CollectionSelector; + + /** + * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. + * @param message CollectionSelector + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.CollectionSelector, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CollectionSelector to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CollectionSelector + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Filter. */ + interface IFilter { + + /** Filter compositeFilter */ + compositeFilter?: (google.firestore.v1.StructuredQuery.ICompositeFilter|null); + + /** Filter fieldFilter */ + fieldFilter?: (google.firestore.v1.StructuredQuery.IFieldFilter|null); + + /** Filter unaryFilter */ + unaryFilter?: (google.firestore.v1.StructuredQuery.IUnaryFilter|null); + } + + /** Represents a Filter. */ + class Filter implements IFilter { + + /** + * Constructs a new Filter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFilter); + + /** Filter compositeFilter. */ + public compositeFilter?: (google.firestore.v1.StructuredQuery.ICompositeFilter|null); + + /** Filter fieldFilter. */ + public fieldFilter?: (google.firestore.v1.StructuredQuery.IFieldFilter|null); + + /** Filter unaryFilter. */ + public unaryFilter?: (google.firestore.v1.StructuredQuery.IUnaryFilter|null); + + /** Filter filterType. */ + public filterType?: ("compositeFilter"|"fieldFilter"|"unaryFilter"); + + /** + * Creates a Filter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Filter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Filter; + + /** + * Creates a plain object from a Filter message. Also converts values to other types if specified. + * @param message Filter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Filter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Filter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Filter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CompositeFilter. */ + interface ICompositeFilter { + + /** CompositeFilter op */ + op?: (google.firestore.v1.StructuredQuery.CompositeFilter.Operator|null); + + /** CompositeFilter filters */ + filters?: (google.firestore.v1.StructuredQuery.IFilter[]|null); + } + + /** Represents a CompositeFilter. */ + class CompositeFilter implements ICompositeFilter { + + /** + * Constructs a new CompositeFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.ICompositeFilter); + + /** CompositeFilter op. */ + public op: google.firestore.v1.StructuredQuery.CompositeFilter.Operator; + + /** CompositeFilter filters. */ + public filters: google.firestore.v1.StructuredQuery.IFilter[]; + + /** + * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CompositeFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.CompositeFilter; + + /** + * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. + * @param message CompositeFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.CompositeFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CompositeFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CompositeFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace CompositeFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "AND"| "OR"; + } + + /** Properties of a FieldFilter. */ + interface IFieldFilter { + + /** FieldFilter field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op */ + op?: (google.firestore.v1.StructuredQuery.FieldFilter.Operator|null); + + /** FieldFilter value */ + value?: (google.firestore.v1.IValue|null); + } + + /** Represents a FieldFilter. */ + class FieldFilter implements IFieldFilter { + + /** + * Constructs a new FieldFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFieldFilter); + + /** FieldFilter field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op. */ + public op: google.firestore.v1.StructuredQuery.FieldFilter.Operator; + + /** FieldFilter value. */ + public value?: (google.firestore.v1.IValue|null); + + /** + * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FieldFilter; + + /** + * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. + * @param message FieldFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FieldFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "LESS_THAN"| "LESS_THAN_OR_EQUAL"| "GREATER_THAN"| "GREATER_THAN_OR_EQUAL"| "EQUAL"| "NOT_EQUAL"| "ARRAY_CONTAINS"| "IN"| "ARRAY_CONTAINS_ANY"| "NOT_IN"; + } + + /** Properties of an UnaryFilter. */ + interface IUnaryFilter { + + /** UnaryFilter op */ + op?: (google.firestore.v1.StructuredQuery.UnaryFilter.Operator|null); + + /** UnaryFilter field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } + + /** Represents an UnaryFilter. */ + class UnaryFilter implements IUnaryFilter { + + /** + * Constructs a new UnaryFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IUnaryFilter); + + /** UnaryFilter op. */ + public op: google.firestore.v1.StructuredQuery.UnaryFilter.Operator; + + /** UnaryFilter field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** UnaryFilter operandType. */ + public operandType?: "field"; + + /** + * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UnaryFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.UnaryFilter; + + /** + * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. + * @param message UnaryFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.UnaryFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UnaryFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UnaryFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UnaryFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "IS_NAN"| "IS_NULL"| "IS_NOT_NAN"| "IS_NOT_NULL"; + } + + /** Properties of an Order. */ + interface IOrder { + + /** Order field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** Order direction */ + direction?: (google.firestore.v1.StructuredQuery.Direction|null); + } + + /** Represents an Order. */ + class Order implements IOrder { + + /** + * Constructs a new Order. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IOrder); + + /** Order field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** Order direction. */ + public direction: google.firestore.v1.StructuredQuery.Direction; + + /** + * Creates an Order message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Order + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Order; + + /** + * Creates a plain object from an Order message. Also converts values to other types if specified. + * @param message Order + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Order, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Order to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Order + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Direction enum. */ + type Direction = + "DIRECTION_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; + + /** Properties of a FieldReference. */ + interface IFieldReference { + + /** FieldReference fieldPath */ + fieldPath?: (string|null); + } + + /** Represents a FieldReference. */ + class FieldReference implements IFieldReference { + + /** + * Constructs a new FieldReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFieldReference); + + /** FieldReference fieldPath. */ + public fieldPath: string; + + /** + * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldReference + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FieldReference; + + /** + * Creates a plain object from a FieldReference message. Also converts values to other types if specified. + * @param message FieldReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FieldReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Projection. */ + interface IProjection { + + /** Projection fields */ + fields?: (google.firestore.v1.StructuredQuery.IFieldReference[]|null); + } + + /** Represents a Projection. */ + class Projection implements IProjection { + + /** + * Constructs a new Projection. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IProjection); + + /** Projection fields. */ + public fields: google.firestore.v1.StructuredQuery.IFieldReference[]; + + /** + * Creates a Projection message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Projection + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Projection; + + /** + * Creates a plain object from a Projection message. Also converts values to other types if specified. + * @param message Projection + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Projection, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Projection to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Projection + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FindNearest. */ + interface IFindNearest { + + /** FindNearest vectorField */ + vectorField?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FindNearest queryVector */ + queryVector?: (google.firestore.v1.IValue|null); + + /** FindNearest distanceMeasure */ + distanceMeasure?: (google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure|null); + + /** FindNearest limit */ + limit?: (google.protobuf.IInt32Value|null); + + /** FindNearest distanceResultField */ + distanceResultField?: (string|null); + + /** FindNearest distanceThreshold */ + distanceThreshold?: (google.protobuf.IDoubleValue|null); + } + + /** Represents a FindNearest. */ + class FindNearest implements IFindNearest { + + /** + * Constructs a new FindNearest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFindNearest); + + /** FindNearest vectorField. */ + public vectorField?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FindNearest queryVector. */ + public queryVector?: (google.firestore.v1.IValue|null); + + /** FindNearest distanceMeasure. */ + public distanceMeasure: google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure; + + /** FindNearest limit. */ + public limit?: (google.protobuf.IInt32Value|null); + + /** FindNearest distanceResultField. */ + public distanceResultField: string; + + /** FindNearest distanceThreshold. */ + public distanceThreshold?: (google.protobuf.IDoubleValue|null); + + /** + * Creates a FindNearest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FindNearest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FindNearest; + + /** + * Creates a plain object from a FindNearest message. Also converts values to other types if specified. + * @param message FindNearest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FindNearest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FindNearest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FindNearest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FindNearest { + + /** DistanceMeasure enum. */ + type DistanceMeasure = + "DISTANCE_MEASURE_UNSPECIFIED"| "EUCLIDEAN"| "COSINE"| "DOT_PRODUCT"; + } + } + + /** Properties of a StructuredAggregationQuery. */ + interface IStructuredAggregationQuery { + + /** StructuredAggregationQuery structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** StructuredAggregationQuery aggregations */ + aggregations?: (google.firestore.v1.StructuredAggregationQuery.IAggregation[]|null); + } + + /** Represents a StructuredAggregationQuery. */ + class StructuredAggregationQuery implements IStructuredAggregationQuery { + + /** + * Constructs a new StructuredAggregationQuery. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IStructuredAggregationQuery); + + /** StructuredAggregationQuery structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** StructuredAggregationQuery aggregations. */ + public aggregations: google.firestore.v1.StructuredAggregationQuery.IAggregation[]; + + /** StructuredAggregationQuery queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a StructuredAggregationQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredAggregationQuery + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery; + + /** + * Creates a plain object from a StructuredAggregationQuery message. Also converts values to other types if specified. + * @param message StructuredAggregationQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructuredAggregationQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredAggregationQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace StructuredAggregationQuery { + + /** Properties of an Aggregation. */ + interface IAggregation { + + /** Aggregation count */ + count?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null); + + /** Aggregation sum */ + sum?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null); + + /** Aggregation avg */ + avg?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null); + + /** Aggregation alias */ + alias?: (string|null); + } + + /** Represents an Aggregation. */ + class Aggregation implements IAggregation { + + /** + * Constructs a new Aggregation. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.IAggregation); + + /** Aggregation count. */ + public count?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null); + + /** Aggregation sum. */ + public sum?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null); + + /** Aggregation avg. */ + public avg?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null); + + /** Aggregation alias. */ + public alias: string; + + /** Aggregation operator. */ + public operator?: ("count"|"sum"|"avg"); + + /** + * Creates an Aggregation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Aggregation + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation; + + /** + * Creates a plain object from an Aggregation message. Also converts values to other types if specified. + * @param message Aggregation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Aggregation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Aggregation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Aggregation { + + /** Properties of a Count. */ + interface ICount { + + /** Count upTo */ + upTo?: (google.protobuf.IInt64Value|null); + } + + /** Represents a Count. */ + class Count implements ICount { + + /** + * Constructs a new Count. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount); + + /** Count upTo. */ + public upTo?: (google.protobuf.IInt64Value|null); + + /** + * Creates a Count message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Count + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Count; + + /** + * Creates a plain object from a Count message. Also converts values to other types if specified. + * @param message Count + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Count, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Count to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Count + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Sum. */ + interface ISum { + + /** Sum field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } + + /** Represents a Sum. */ + class Sum implements ISum { + + /** + * Constructs a new Sum. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum); + + /** Sum field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** + * Creates a Sum message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Sum + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum; + + /** + * Creates a plain object from a Sum message. Also converts values to other types if specified. + * @param message Sum + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Sum to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Sum + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Avg. */ + interface IAvg { + + /** Avg field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } + + /** Represents an Avg. */ + class Avg implements IAvg { + + /** + * Constructs a new Avg. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg); + + /** Avg field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** + * Creates an Avg message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Avg + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg; + + /** + * Creates a plain object from an Avg message. Also converts values to other types if specified. + * @param message Avg + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Avg to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Avg + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** Properties of a Cursor. */ + interface ICursor { + + /** Cursor values */ + values?: (google.firestore.v1.IValue[]|null); + + /** Cursor before */ + before?: (boolean|null); + } + + /** Represents a Cursor. */ + class Cursor implements ICursor { + + /** + * Constructs a new Cursor. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICursor); + + /** Cursor values. */ + public values: google.firestore.v1.IValue[]; + + /** Cursor before. */ + public before: boolean; + + /** + * Creates a Cursor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Cursor + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Cursor; + + /** + * Creates a plain object from a Cursor message. Also converts values to other types if specified. + * @param message Cursor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Cursor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Cursor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Cursor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExplainOptions. */ + interface IExplainOptions { + + /** ExplainOptions analyze */ + analyze?: (boolean|null); + } + + /** Represents an ExplainOptions. */ + class ExplainOptions implements IExplainOptions { + + /** + * Constructs a new ExplainOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExplainOptions); + + /** ExplainOptions analyze. */ + public analyze: boolean; + + /** + * Creates an ExplainOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExplainOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainOptions; + + /** + * Creates a plain object from an ExplainOptions message. Also converts values to other types if specified. + * @param message ExplainOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExplainOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExplainOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExplainOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExplainMetrics. */ + interface IExplainMetrics { + + /** ExplainMetrics planSummary */ + planSummary?: (google.firestore.v1.IPlanSummary|null); + + /** ExplainMetrics executionStats */ + executionStats?: (google.firestore.v1.IExecutionStats|null); + } + + /** Represents an ExplainMetrics. */ + class ExplainMetrics implements IExplainMetrics { + + /** + * Constructs a new ExplainMetrics. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExplainMetrics); + + /** ExplainMetrics planSummary. */ + public planSummary?: (google.firestore.v1.IPlanSummary|null); + + /** ExplainMetrics executionStats. */ + public executionStats?: (google.firestore.v1.IExecutionStats|null); + + /** + * Creates an ExplainMetrics message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExplainMetrics + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainMetrics; + + /** + * Creates a plain object from an ExplainMetrics message. Also converts values to other types if specified. + * @param message ExplainMetrics + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExplainMetrics, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExplainMetrics to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExplainMetrics + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PlanSummary. */ + interface IPlanSummary { + + /** PlanSummary indexesUsed */ + indexesUsed?: (google.protobuf.IStruct[]|null); + } + + /** Represents a PlanSummary. */ + class PlanSummary implements IPlanSummary { + + /** + * Constructs a new PlanSummary. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPlanSummary); + + /** PlanSummary indexesUsed. */ + public indexesUsed: google.protobuf.IStruct[]; + + /** + * Creates a PlanSummary message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PlanSummary + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PlanSummary; + + /** + * Creates a plain object from a PlanSummary message. Also converts values to other types if specified. + * @param message PlanSummary + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.PlanSummary, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PlanSummary to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PlanSummary + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExecutionStats. */ + interface IExecutionStats { + + /** ExecutionStats resultsReturned */ + resultsReturned?: (number|string|null); + + /** ExecutionStats executionDuration */ + executionDuration?: (google.protobuf.IDuration|null); + + /** ExecutionStats readOperations */ + readOperations?: (number|string|null); + + /** ExecutionStats debugStats */ + debugStats?: (google.protobuf.IStruct|null); + } + + /** Represents an ExecutionStats. */ + class ExecutionStats implements IExecutionStats { + + /** + * Constructs a new ExecutionStats. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExecutionStats); + + /** ExecutionStats resultsReturned. */ + public resultsReturned: (number|string); + + /** ExecutionStats executionDuration. */ + public executionDuration?: (google.protobuf.IDuration|null); + + /** ExecutionStats readOperations. */ + public readOperations: (number|string); + + /** ExecutionStats debugStats. */ + public debugStats?: (google.protobuf.IStruct|null); + + /** + * Creates an ExecutionStats message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecutionStats + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutionStats; + + /** + * Creates a plain object from an ExecutionStats message. Also converts values to other types if specified. + * @param message ExecutionStats + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExecutionStats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecutionStats to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecutionStats + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Write. */ + interface IWrite { + + /** Write update */ + update?: (google.firestore.v1.IDocument|null); + + /** Write delete */ + "delete"?: (string|null); + + /** Write transform */ + transform?: (google.firestore.v1.IDocumentTransform|null); + + /** Write updateMask */ + updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** Write updateTransforms */ + updateTransforms?: (google.firestore.v1.DocumentTransform.IFieldTransform[]|null); + + /** Write currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); + } + + /** Represents a Write. */ + class Write implements IWrite { + + /** + * Constructs a new Write. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWrite); + + /** Write update. */ + public update?: (google.firestore.v1.IDocument|null); + + /** Write delete. */ + public delete?: (string|null); + + /** Write transform. */ + public transform?: (google.firestore.v1.IDocumentTransform|null); + + /** Write updateMask. */ + public updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** Write updateTransforms. */ + public updateTransforms: google.firestore.v1.DocumentTransform.IFieldTransform[]; + + /** Write currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); + + /** Write operation. */ + public operation?: ("update"|"delete"|"transform"); + + /** + * Creates a Write message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Write + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Write; + + /** + * Creates a plain object from a Write message. Also converts values to other types if specified. + * @param message Write + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Write, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Write to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Write + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentTransform. */ + interface IDocumentTransform { + + /** DocumentTransform document */ + document?: (string|null); + + /** DocumentTransform fieldTransforms */ + fieldTransforms?: (google.firestore.v1.DocumentTransform.IFieldTransform[]|null); + } + + /** Represents a DocumentTransform. */ + class DocumentTransform implements IDocumentTransform { + + /** + * Constructs a new DocumentTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentTransform); + + /** DocumentTransform document. */ + public document: string; + + /** DocumentTransform fieldTransforms. */ + public fieldTransforms: google.firestore.v1.DocumentTransform.IFieldTransform[]; + + /** + * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentTransform; + + /** + * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. + * @param message DocumentTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DocumentTransform { + + /** Properties of a FieldTransform. */ + interface IFieldTransform { + + /** FieldTransform fieldPath */ + fieldPath?: (string|null); + + /** FieldTransform setToServerValue */ + setToServerValue?: (google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment */ + increment?: (google.firestore.v1.IValue|null); + + /** FieldTransform maximum */ + maximum?: (google.firestore.v1.IValue|null); + + /** FieldTransform minimum */ + minimum?: (google.firestore.v1.IValue|null); + + /** FieldTransform appendMissingElements */ + appendMissingElements?: (google.firestore.v1.IArrayValue|null); + + /** FieldTransform removeAllFromArray */ + removeAllFromArray?: (google.firestore.v1.IArrayValue|null); + } + + /** Represents a FieldTransform. */ + class FieldTransform implements IFieldTransform { + + /** + * Constructs a new FieldTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.DocumentTransform.IFieldTransform); + + /** FieldTransform fieldPath. */ + public fieldPath: string; + + /** FieldTransform setToServerValue. */ + public setToServerValue?: (google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment. */ + public increment?: (google.firestore.v1.IValue|null); + + /** FieldTransform maximum. */ + public maximum?: (google.firestore.v1.IValue|null); + + /** FieldTransform minimum. */ + public minimum?: (google.firestore.v1.IValue|null); + + /** FieldTransform appendMissingElements. */ + public appendMissingElements?: (google.firestore.v1.IArrayValue|null); + + /** FieldTransform removeAllFromArray. */ + public removeAllFromArray?: (google.firestore.v1.IArrayValue|null); + + /** FieldTransform transformType. */ + public transformType?: ("setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"); + + /** + * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentTransform.FieldTransform; + + /** + * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. + * @param message FieldTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentTransform.FieldTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldTransform { + + /** ServerValue enum. */ + type ServerValue = + "SERVER_VALUE_UNSPECIFIED"| "REQUEST_TIME"; + } + } + + /** Properties of a WriteResult. */ + interface IWriteResult { + + /** WriteResult updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** WriteResult transformResults */ + transformResults?: (google.firestore.v1.IValue[]|null); + } + + /** Represents a WriteResult. */ + class WriteResult implements IWriteResult { + + /** + * Constructs a new WriteResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteResult); + + /** WriteResult updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** WriteResult transformResults. */ + public transformResults: google.firestore.v1.IValue[]; + + /** + * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResult + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteResult; + + /** + * Creates a plain object from a WriteResult message. Also converts values to other types if specified. + * @param message WriteResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentChange. */ + interface IDocumentChange { + + /** DocumentChange document */ + document?: (google.firestore.v1.IDocument|null); + + /** DocumentChange targetIds */ + targetIds?: (number[]|null); + + /** DocumentChange removedTargetIds */ + removedTargetIds?: (number[]|null); + } + + /** Represents a DocumentChange. */ + class DocumentChange implements IDocumentChange { + + /** + * Constructs a new DocumentChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentChange); + + /** DocumentChange document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** DocumentChange targetIds. */ + public targetIds: number[]; + + /** DocumentChange removedTargetIds. */ + public removedTargetIds: number[]; + + /** + * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentChange; + + /** + * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. + * @param message DocumentChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentDelete. */ + interface IDocumentDelete { + + /** DocumentDelete document */ + document?: (string|null); + + /** DocumentDelete removedTargetIds */ + removedTargetIds?: (number[]|null); + + /** DocumentDelete readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a DocumentDelete. */ + class DocumentDelete implements IDocumentDelete { + + /** + * Constructs a new DocumentDelete. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentDelete); + + /** DocumentDelete document. */ + public document: string; + + /** DocumentDelete removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentDelete readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentDelete + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentDelete; + + /** + * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. + * @param message DocumentDelete + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentDelete, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentDelete to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentDelete + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentRemove. */ + interface IDocumentRemove { + + /** DocumentRemove document */ + document?: (string|null); + + /** DocumentRemove removedTargetIds */ + removedTargetIds?: (number[]|null); + + /** DocumentRemove readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a DocumentRemove. */ + class DocumentRemove implements IDocumentRemove { + + /** + * Constructs a new DocumentRemove. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentRemove); + + /** DocumentRemove document. */ + public document: string; + + /** DocumentRemove removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentRemove readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentRemove + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentRemove; + + /** + * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. + * @param message DocumentRemove + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentRemove, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentRemove to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentRemove + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExistenceFilter. */ + interface IExistenceFilter { + + /** ExistenceFilter targetId */ + targetId?: (number|null); + + /** ExistenceFilter count */ + count?: (number|null); + + /** ExistenceFilter unchangedNames */ + unchangedNames?: (google.firestore.v1.IBloomFilter|null); + } + + /** Represents an ExistenceFilter. */ + class ExistenceFilter implements IExistenceFilter { + + /** + * Constructs a new ExistenceFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExistenceFilter); + + /** ExistenceFilter targetId. */ + public targetId: number; + + /** ExistenceFilter count. */ + public count: number; + + /** ExistenceFilter unchangedNames. */ + public unchangedNames?: (google.firestore.v1.IBloomFilter|null); + + /** + * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExistenceFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExistenceFilter; + + /** + * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. + * @param message ExistenceFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExistenceFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExistenceFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExistenceFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** Namespace api. */ + namespace api { + + /** FieldBehavior enum. */ + type FieldBehavior = + "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { + + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); + + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + } + + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { + + /** + * Constructs a new CommonLanguageSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICommonLanguageSettings); + + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; + + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; + + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommonLanguageSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { + + /** ClientLibrarySettings version */ + version?: (string|null); + + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|null); + + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); + + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } + + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { + + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); + + /** ClientLibrarySettings version. */ + public version: string; + + /** ClientLibrarySettings launchStage. */ + public launchStage: google.api.LaunchStage; + + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; + + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Publishing. */ + interface IPublishing { + + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); + + /** Publishing newIssueUri */ + newIssueUri?: (string|null); + + /** Publishing documentationUri */ + documentationUri?: (string|null); + + /** Publishing apiShortName */ + apiShortName?: (string|null); + + /** Publishing githubLabel */ + githubLabel?: (string|null); + + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); + + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); + + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|null); + + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); + + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); + + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } + + /** Represents a Publishing. */ + class Publishing implements IPublishing { + + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); + + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; + + /** Publishing newIssueUri. */ + public newIssueUri: string; + + /** Publishing documentationUri. */ + public documentationUri: string; + + /** Publishing apiShortName. */ + public apiShortName: string; + + /** Publishing githubLabel. */ + public githubLabel: string; + + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; + + /** Publishing docTagPrefix. */ + public docTagPrefix: string; + + /** Publishing organization. */ + public organization: google.api.ClientLibraryOrganization; + + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; + + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; + + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a JavaSettings. */ + interface IJavaSettings { + + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); + + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); + + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { + + /** + * Constructs a new JavaSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IJavaSettings); + + /** JavaSettings libraryPackage. */ + public libraryPackage: string; + + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; + + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns JavaSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this JavaSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CppSettings. */ + interface ICppSettings { + + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { + + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); + + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PhpSettings. */ + interface IPhpSettings { + + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { + + /** + * Constructs a new PhpSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPhpSettings); + + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PythonSettings. */ + interface IPythonSettings { + + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + } + + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { + + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); + + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PythonSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PythonSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PythonSettings { + + /** Properties of an ExperimentalFeatures. */ + interface IExperimentalFeatures { + + /** ExperimentalFeatures restAsyncIoEnabled */ + restAsyncIoEnabled?: (boolean|null); + + /** ExperimentalFeatures protobufPythonicTypesEnabled */ + protobufPythonicTypesEnabled?: (boolean|null); + + /** ExperimentalFeatures unversionedPackageDisabled */ + unversionedPackageDisabled?: (boolean|null); + } + + /** Represents an ExperimentalFeatures. */ + class ExperimentalFeatures implements IExperimentalFeatures { + + /** + * Constructs a new ExperimentalFeatures. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.PythonSettings.IExperimentalFeatures); + + /** ExperimentalFeatures restAsyncIoEnabled. */ + public restAsyncIoEnabled: boolean; + + /** ExperimentalFeatures protobufPythonicTypesEnabled. */ + public protobufPythonicTypesEnabled: boolean; + + /** ExperimentalFeatures unversionedPackageDisabled. */ + public unversionedPackageDisabled: boolean; + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExperimentalFeatures + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @param message ExperimentalFeatures + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings.ExperimentalFeatures, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExperimentalFeatures + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a NodeSettings. */ + interface INodeSettings { + + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { + + /** + * Constructs a new NodeSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.INodeSettings); + + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NodeSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NodeSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { + + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); + + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); + + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); + + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); + } + + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { + + /** + * Constructs a new DotnetSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IDotnetSettings); + + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; + + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; + + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; + + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DotnetSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DotnetSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RubySettings. */ + interface IRubySettings { + + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { + + /** + * Constructs a new RubySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRubySettings); + + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GoSettings. */ + interface IGoSettings { + + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + } + + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { + + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); + + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodSettings. */ + interface IMethodSettings { + + /** MethodSettings selector */ + selector?: (string|null); + + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); + } + + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { + + /** + * Constructs a new MethodSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IMethodSettings); + + /** MethodSettings selector. */ + public selector: string; + + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodSettings { + + /** Properties of a LongRunning. */ + interface ILongRunning { + + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); + + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); + } + + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { + + /** + * Constructs a new LongRunning. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.MethodSettings.ILongRunning); + + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; + + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LongRunning + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LongRunning to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LongRunning + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** ClientLibraryOrganization enum. */ + type ClientLibraryOrganization = + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; + + /** ClientLibraryDestination enum. */ + type ClientLibraryDestination = + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; + + /** Properties of a SelectiveGapicGeneration. */ + interface ISelectiveGapicGeneration { + + /** SelectiveGapicGeneration methods */ + methods?: (string[]|null); + + /** SelectiveGapicGeneration generateOmittedAsInternal */ + generateOmittedAsInternal?: (boolean|null); + } + + /** Represents a SelectiveGapicGeneration. */ + class SelectiveGapicGeneration implements ISelectiveGapicGeneration { + + /** + * Constructs a new SelectiveGapicGeneration. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ISelectiveGapicGeneration); + + /** SelectiveGapicGeneration methods. */ + public methods: string[]; + + /** SelectiveGapicGeneration generateOmittedAsInternal. */ + public generateOmittedAsInternal: boolean; + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SelectiveGapicGeneration + */ + public static fromObject(object: { [k: string]: any }): google.api.SelectiveGapicGeneration; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @param message SelectiveGapicGeneration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.SelectiveGapicGeneration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; + + /** Properties of a RoutingRule. */ + interface IRoutingRule { + + /** RoutingRule routingParameters */ + routingParameters?: (google.api.IRoutingParameter[]|null); + } + + /** Represents a RoutingRule. */ + class RoutingRule implements IRoutingRule { + + /** + * Constructs a new RoutingRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRoutingRule); + + /** RoutingRule routingParameters. */ + public routingParameters: google.api.IRoutingParameter[]; + + /** + * Creates a RoutingRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingRule + */ + public static fromObject(object: { [k: string]: any }): google.api.RoutingRule; + + /** + * Creates a plain object from a RoutingRule message. Also converts values to other types if specified. + * @param message RoutingRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RoutingRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RoutingParameter. */ + interface IRoutingParameter { + + /** RoutingParameter field */ + field?: (string|null); + + /** RoutingParameter pathTemplate */ + pathTemplate?: (string|null); + } + + /** Represents a RoutingParameter. */ + class RoutingParameter implements IRoutingParameter { + + /** + * Constructs a new RoutingParameter. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRoutingParameter); + + /** RoutingParameter field. */ + public field: string; + + /** RoutingParameter pathTemplate. */ + public pathTemplate: string; + + /** + * Creates a RoutingParameter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingParameter + */ + public static fromObject(object: { [k: string]: any }): google.api.RoutingParameter; + + /** + * Creates a plain object from a RoutingParameter message. Also converts values to other types if specified. + * @param message RoutingParameter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RoutingParameter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingParameter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingParameter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { + + /** ResourceDescriptor type */ + type?: (string|null); + + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); + + /** ResourceDescriptor nameField */ + nameField?: (string|null); + + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|null); + + /** ResourceDescriptor plural */ + plural?: (string|null); + + /** ResourceDescriptor singular */ + singular?: (string|null); + + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } + + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { + + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); + + /** ResourceDescriptor type. */ + public type: string; + + /** ResourceDescriptor pattern. */ + public pattern: string[]; + + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: google.api.ResourceDescriptor.History; + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ResourceDescriptor { + + /** History enum. */ + type History = + "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; + + /** Style enum. */ + type Style = + "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + } + + /** Properties of a ResourceReference. */ + interface IResourceReference { + + /** ResourceReference type */ + type?: (string|null); + + /** ResourceReference childType */ + childType?: (string|null); + } + + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { + + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); + + /** ResourceReference type. */ + public type: string; + + /** ResourceReference childType. */ + public childType: string; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); + + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Edition enum. */ + type Edition = + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; + + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { + + /** FileDescriptorProto name */ + name?: (string|null); + + /** FileDescriptorProto package */ + "package"?: (string|null); + + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); + + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); + + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); + + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); + + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); + + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax */ + syntax?: (string|null); + + /** FileDescriptorProto edition */ + edition?: (google.protobuf.Edition|null); + } + + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { + + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); + + /** FileDescriptorProto name. */ + public name: string; + + /** FileDescriptorProto package. */ + public package: string; + + /** FileDescriptorProto dependency. */ + public dependency: string[]; + + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; + + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; + + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; + + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; + + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax. */ + public syntax: string; + + /** FileDescriptorProto edition. */ + public edition: google.protobuf.Edition; + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { + + /** DescriptorProto name */ + name?: (string|null); + + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { + + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); + + /** DescriptorProto name. */ + public name: string; + + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; + + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + + /** DescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DescriptorProto { + + /** Properties of an ExtensionRange. */ + interface IExtensionRange { + + /** ExtensionRange start */ + start?: (number|null); + + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); + } + + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { + + /** + * Constructs a new ExtensionRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + + /** ExtensionRange start. */ + public start: number; + + /** ExtensionRange end. */ + public end: number; + + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReservedRange. */ + interface IReservedRange { + + /** ReservedRange start */ + start?: (number|null); + + /** ReservedRange end */ + end?: (number|null); + } + + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { + + /** + * Constructs a new ReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + + /** ReservedRange start. */ + public start: number; + + /** ReservedRange end. */ + public end: number; + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ExtensionRangeOptions declaration */ + declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); + + /** ExtensionRangeOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification */ + verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** ExtensionRangeOptions declaration. */ + public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; + + /** ExtensionRangeOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification. */ + public verification: google.protobuf.ExtensionRangeOptions.VerificationState; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExtensionRangeOptions { + + /** Properties of a Declaration. */ + interface IDeclaration { + + /** Declaration number */ + number?: (number|null); + + /** Declaration fullName */ + fullName?: (string|null); + + /** Declaration type */ + type?: (string|null); + + /** Declaration reserved */ + reserved?: (boolean|null); + + /** Declaration repeated */ + repeated?: (boolean|null); + } + + /** Represents a Declaration. */ + class Declaration implements IDeclaration { + + /** + * Constructs a new Declaration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); + + /** Declaration number. */ + public number: number; + + /** Declaration fullName. */ + public fullName: string; + + /** Declaration type. */ + public type: string; + + /** Declaration reserved. */ + public reserved: boolean; + + /** Declaration repeated. */ + public repeated: boolean; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Declaration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @param message Declaration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Declaration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Declaration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** VerificationState enum. */ + type VerificationState = + "DECLARATION"| "UNVERIFIED"; + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; + + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldDescriptorProto { + + /** Type enum. */ + type Type = + "TYPE_DOUBLE"| "TYPE_FLOAT"| "TYPE_INT64"| "TYPE_UINT64"| "TYPE_INT32"| "TYPE_FIXED64"| "TYPE_FIXED32"| "TYPE_BOOL"| "TYPE_STRING"| "TYPE_GROUP"| "TYPE_MESSAGE"| "TYPE_BYTES"| "TYPE_UINT32"| "TYPE_ENUM"| "TYPE_SFIXED32"| "TYPE_SFIXED64"| "TYPE_SINT32"| "TYPE_SINT64"; + + /** Label enum. */ + type Label = + "LABEL_OPTIONAL"| "LABEL_REPEATED"| "LABEL_REQUIRED"; + } + + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { + + /** OneofDescriptorProto name */ + name?: (string|null); + + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } + + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { + + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); + + /** OneofDescriptorProto name. */ + public name: string; + + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { + + /** EnumDescriptorProto name */ + name?: (string|null); + + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { + + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); + + /** EnumDescriptorProto name. */ + public name: string; + + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; + + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { + + /** EnumValueDescriptorProto name */ + name?: (string|null); + + /** EnumValueDescriptorProto number */ + number?: (number|null); + + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } + + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + + /** EnumValueDescriptorProto name. */ + public name: string; + + /** EnumValueDescriptorProto number. */ + public number: number; + + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { + + /** ServiceDescriptorProto name */ + name?: (string|null); + + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); + + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } + + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { + + /** FileOptions javaPackage */ + javaPackage?: (string|null); + + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); + + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); + + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); + + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); + + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + + /** FileOptions goPackage */ + goPackage?: (string|null); + + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); + + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); + + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); + + /** FileOptions deprecated */ + deprecated?: (boolean|null); + + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); + + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); + + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); + + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); + } + + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { + + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); + + /** FileOptions javaPackage. */ + public javaPackage: string; + + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; + + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; + + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; + + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; + + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + + /** FileOptions goPackage. */ + public goPackage: string; + + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; + + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; + + /** FileOptions deprecated. */ + public deprecated: boolean; + + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; + + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; + + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + type OptimizeMode = + "SPEED"| "CODE_SIZE"| "LITE_RUNTIME"; + } + + /** Properties of a MessageOptions. */ + interface IMessageOptions { + + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); + + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); + + /** MessageOptions deprecated */ + deprecated?: (boolean|null); + + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); + + /** MessageOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** MessageOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MessageOptions .google.api.resource */ + ".google.api.resource"?: (google.api.IResourceDescriptor|null); + } + + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { + + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); + + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; + + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; + + /** MessageOptions deprecated. */ + public deprecated: boolean; + + /** MessageOptions mapEntry. */ + public mapEntry: boolean; + + /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** MessageOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MessageOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldOptions. */ + interface IFieldOptions { + + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); + + /** FieldOptions packed */ + packed?: (boolean|null); + + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); + + /** FieldOptions lazy */ + lazy?: (boolean|null); + + /** FieldOptions unverifiedLazy */ + unverifiedLazy?: (boolean|null); + + /** FieldOptions deprecated */ + deprecated?: (boolean|null); + + /** FieldOptions weak */ + weak?: (boolean|null); + + /** FieldOptions debugRedact */ + debugRedact?: (boolean|null); + + /** FieldOptions retention */ + retention?: (google.protobuf.FieldOptions.OptionRetention|null); + + /** FieldOptions targets */ + targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); + + /** FieldOptions editionDefaults */ + editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); + + /** FieldOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FieldOptions .google.api.fieldBehavior */ + ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); + + /** FieldOptions .google.api.resourceReference */ + ".google.api.resourceReference"?: (google.api.IResourceReference|null); + } + + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { + + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); + + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; + + /** FieldOptions packed. */ + public packed: boolean; + + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; + + /** FieldOptions lazy. */ + public lazy: boolean; + + /** FieldOptions unverifiedLazy. */ + public unverifiedLazy: boolean; + + /** FieldOptions deprecated. */ + public deprecated: boolean; + + /** FieldOptions weak. */ + public weak: boolean; + + /** FieldOptions debugRedact. */ + public debugRedact: boolean; + + /** FieldOptions retention. */ + public retention: google.protobuf.FieldOptions.OptionRetention; + + /** FieldOptions targets. */ + public targets: google.protobuf.FieldOptions.OptionTargetType[]; + + /** FieldOptions editionDefaults. */ + public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; + + /** FieldOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldOptions { + + /** CType enum. */ + type CType = + "STRING"| "CORD"| "STRING_PIECE"; + + /** JSType enum. */ + type JSType = + "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; + + /** OptionRetention enum. */ + type OptionRetention = + "RETENTION_UNKNOWN"| "RETENTION_RUNTIME"| "RETENTION_SOURCE"; + + /** OptionTargetType enum. */ + type OptionTargetType = + "TARGET_TYPE_UNKNOWN"| "TARGET_TYPE_FILE"| "TARGET_TYPE_EXTENSION_RANGE"| "TARGET_TYPE_MESSAGE"| "TARGET_TYPE_FIELD"| "TARGET_TYPE_ONEOF"| "TARGET_TYPE_ENUM"| "TARGET_TYPE_ENUM_ENTRY"| "TARGET_TYPE_SERVICE"| "TARGET_TYPE_METHOD"; + + /** Properties of an EditionDefault. */ + interface IEditionDefault { + + /** EditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** EditionDefault value */ + value?: (string|null); + } + + /** Represents an EditionDefault. */ + class EditionDefault implements IEditionDefault { + + /** + * Constructs a new EditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); + + /** EditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** EditionDefault value. */ + public value: string; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @param message EditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an OneofOptions. */ + interface IOneofOptions { + + /** OneofOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { + + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); + + /** OneofOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumOptions. */ + interface IEnumOptions { + + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); + + /** EnumOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** EnumOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { + + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** EnumOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact */ + debugRedact?: (boolean|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { + + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); + + /** EnumValueOptions deprecated. */ + public deprecated: boolean; + + /** EnumValueOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact. */ + public debugRedact: boolean; + + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceOptions. */ + interface IServiceOptions { + + /** ServiceOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); + + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); + + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); + + /** ServiceOptions .google.api.apiVersion */ + ".google.api.apiVersion"?: (string|null); + } + + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { + + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); + + /** ServiceOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated. */ + public deprecated: boolean; + + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodOptions. */ + interface IMethodOptions { + + /** MethodOptions deprecated */ + deprecated?: (boolean|null); + + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); + + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); + + /** MethodOptions .google.api.routing */ + ".google.api.routing"?: (google.api.IRoutingRule|null); + + /** MethodOptions .google.longrunning.operationInfo */ + ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); + } + + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { + + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); + + /** MethodOptions deprecated. */ + public deprecated: boolean; + + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + type IdempotencyLevel = + "IDEMPOTENCY_UNKNOWN"| "NO_SIDE_EFFECTS"| "IDEMPOTENT"; + } + + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { + + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); + + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|string|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|string|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|string); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|string); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UninterpretedOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamePart + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a FeatureSet. */ + interface IFeatureSet { + + /** FeatureSet fieldPresence */ + fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|null); + + /** FeatureSet enumType */ + enumType?: (google.protobuf.FeatureSet.EnumType|null); + + /** FeatureSet repeatedFieldEncoding */ + repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|null); + + /** FeatureSet utf8Validation */ + utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|null); + + /** FeatureSet messageEncoding */ + messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|null); + + /** FeatureSet jsonFormat */ + jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|null); + } + + /** Represents a FeatureSet. */ + class FeatureSet implements IFeatureSet { + + /** + * Constructs a new FeatureSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSet); + + /** FeatureSet fieldPresence. */ + public fieldPresence: google.protobuf.FeatureSet.FieldPresence; + + /** FeatureSet enumType. */ + public enumType: google.protobuf.FeatureSet.EnumType; + + /** FeatureSet repeatedFieldEncoding. */ + public repeatedFieldEncoding: google.protobuf.FeatureSet.RepeatedFieldEncoding; + + /** FeatureSet utf8Validation. */ + public utf8Validation: google.protobuf.FeatureSet.Utf8Validation; + + /** FeatureSet messageEncoding. */ + public messageEncoding: google.protobuf.FeatureSet.MessageEncoding; + + /** FeatureSet jsonFormat. */ + public jsonFormat: google.protobuf.FeatureSet.JsonFormat; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @param message FeatureSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSet { + + /** FieldPresence enum. */ + type FieldPresence = + "FIELD_PRESENCE_UNKNOWN"| "EXPLICIT"| "IMPLICIT"| "LEGACY_REQUIRED"; + + /** EnumType enum. */ + type EnumType = + "ENUM_TYPE_UNKNOWN"| "OPEN"| "CLOSED"; + + /** RepeatedFieldEncoding enum. */ + type RepeatedFieldEncoding = + "REPEATED_FIELD_ENCODING_UNKNOWN"| "PACKED"| "EXPANDED"; + + /** Utf8Validation enum. */ + type Utf8Validation = + "UTF8_VALIDATION_UNKNOWN"| "VERIFY"| "NONE"; + + /** MessageEncoding enum. */ + type MessageEncoding = + "MESSAGE_ENCODING_UNKNOWN"| "LENGTH_PREFIXED"| "DELIMITED"; + + /** JsonFormat enum. */ + type JsonFormat = + "JSON_FORMAT_UNKNOWN"| "ALLOW"| "LEGACY_BEST_EFFORT"; + } + + /** Properties of a FeatureSetDefaults. */ + interface IFeatureSetDefaults { + + /** FeatureSetDefaults defaults */ + defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); + + /** FeatureSetDefaults minimumEdition */ + minimumEdition?: (google.protobuf.Edition|null); + + /** FeatureSetDefaults maximumEdition */ + maximumEdition?: (google.protobuf.Edition|null); + } + + /** Represents a FeatureSetDefaults. */ + class FeatureSetDefaults implements IFeatureSetDefaults { + + /** + * Constructs a new FeatureSetDefaults. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSetDefaults); + + /** FeatureSetDefaults defaults. */ + public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; + + /** FeatureSetDefaults minimumEdition. */ + public minimumEdition: google.protobuf.Edition; + + /** FeatureSetDefaults maximumEdition. */ + public maximumEdition: google.protobuf.Edition; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetDefaults + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @param message FeatureSetDefaults + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetDefaults + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSetDefaults { + + /** Properties of a FeatureSetEditionDefault. */ + interface IFeatureSetEditionDefault { + + /** FeatureSetEditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); + } + + /** Represents a FeatureSetEditionDefault. */ + class FeatureSetEditionDefault implements IFeatureSetEditionDefault { + + /** + * Constructs a new FeatureSetEditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); + + /** FeatureSetEditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetEditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @param message FeatureSetEditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { + + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } + + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { + + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); + + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SourceCodeInfo { + + /** Properties of a Location. */ + interface ILocation { + + /** Location path */ + path?: (number[]|null); + + /** Location span */ + span?: (number[]|null); + + /** Location leadingComments */ + leadingComments?: (string|null); + + /** Location trailingComments */ + trailingComments?: (string|null); + + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + + /** Location path. */ + public path: number[]; + + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Location + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { + + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } + + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { + + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); + + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + + /** Annotation semantic */ + semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); + } + + /** Represents an Annotation. */ + class Annotation implements IAnnotation { + + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); + + /** Annotation path. */ + public path: number[]; + + /** Annotation sourceFile. */ + public sourceFile: string; + + /** Annotation begin. */ + public begin: number; + + /** Annotation end. */ + public end: number; + + /** Annotation semantic. */ + public semantic: google.protobuf.GeneratedCodeInfo.Annotation.Semantic; + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Annotation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Annotation { + + /** Semantic enum. */ + type Semantic = + "NONE"| "SET"| "ALIAS"; + } + } + + /** Properties of a Struct. */ + interface IStruct { + + /** Struct fields */ + fields?: ({ [k: string]: google.protobuf.IValue }|null); + } + + /** Represents a Struct. */ + class Struct implements IStruct { + + /** + * Constructs a new Struct. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStruct); + + /** Struct fields. */ + public fields: { [k: string]: google.protobuf.IValue }; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Struct + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @param message Struct + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Struct to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Struct + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue */ + numberValue?: (number|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value boolValue */ + boolValue?: (boolean|null); + + /** Value structValue */ + structValue?: (google.protobuf.IStruct|null); + + /** Value listValue */ + listValue?: (google.protobuf.IListValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue. */ + public numberValue?: (number|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value boolValue. */ + public boolValue?: (boolean|null); + + /** Value structValue. */ + public structValue?: (google.protobuf.IStruct|null); + + /** Value listValue. */ + public listValue?: (google.protobuf.IListValue|null); + + /** Value kind. */ + public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** NullValue enum. */ + type NullValue = + "NULL_VALUE"; + + /** Properties of a ListValue. */ + interface IListValue { + + /** ListValue values */ + values?: (google.protobuf.IValue[]|null); + } + + /** Represents a ListValue. */ + class ListValue implements IListValue { + + /** + * Constructs a new ListValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IListValue); + + /** ListValue values. */ + public values: google.protobuf.IValue[]; + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @param message ListValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Timestamp. */ + interface ITimestamp { + + /** Timestamp seconds */ + seconds?: (number|string|null); + + /** Timestamp nanos */ + nanos?: (number|null); + } + + /** Represents a Timestamp. */ + class Timestamp implements ITimestamp { + + /** + * Constructs a new Timestamp. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ITimestamp); + + /** Timestamp seconds. */ + public seconds: (number|string); + + /** Timestamp nanos. */ + public nanos: number; + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Timestamp + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @param message Timestamp + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Timestamp to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Timestamp + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Any. */ + interface IAny { + + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|null); + } + + /** Represents an Any. */ + class Any implements IAny { + + /** + * Constructs a new Any. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IAny); + + /** Any type_url. */ + public type_url: string; + + /** Any value. */ + public value: Uint8Array; + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Any + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Any to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Any + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Duration. */ + interface IDuration { + + /** Duration seconds */ + seconds?: (number|string|null); + + /** Duration nanos */ + nanos?: (number|null); + } + + /** Represents a Duration. */ + class Duration implements IDuration { + + /** + * Constructs a new Duration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDuration); + + /** Duration seconds. */ + public seconds: (number|string); + + /** Duration nanos. */ + public nanos: number; + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Duration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Duration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Duration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DoubleValue. */ + interface IDoubleValue { + + /** DoubleValue value */ + value?: (number|null); + } + + /** Represents a DoubleValue. */ + class DoubleValue implements IDoubleValue { + + /** + * Constructs a new DoubleValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDoubleValue); + + /** DoubleValue value. */ + public value: number; + + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DoubleValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; + + /** + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @param message DoubleValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DoubleValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DoubleValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FloatValue. */ + interface IFloatValue { + + /** FloatValue value */ + value?: (number|null); + } + + /** Represents a FloatValue. */ + class FloatValue implements IFloatValue { + + /** + * Constructs a new FloatValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFloatValue); + + /** FloatValue value. */ + public value: number; + + /** + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FloatValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; + + /** + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. + * @param message FloatValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FloatValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FloatValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int64Value. */ + interface IInt64Value { + + /** Int64Value value */ + value?: (number|string|null); + } + + /** Represents an Int64Value. */ + class Int64Value implements IInt64Value { + + /** + * Constructs a new Int64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt64Value); + + /** Int64Value value. */ + public value: (number|string); + + /** + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; + + /** + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. + * @param message Int64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt64Value. */ + interface IUInt64Value { + + /** UInt64Value value */ + value?: (number|string|null); + } + + /** Represents a UInt64Value. */ + class UInt64Value implements IUInt64Value { + + /** + * Constructs a new UInt64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt64Value); + + /** UInt64Value value. */ + public value: (number|string); + + /** + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; + + /** + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. + * @param message UInt64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int32Value. */ + interface IInt32Value { + + /** Int32Value value */ + value?: (number|null); + } + + /** Represents an Int32Value. */ + class Int32Value implements IInt32Value { + + /** + * Constructs a new Int32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt32Value); + + /** Int32Value value. */ + public value: number; + + /** + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; + + /** + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. + * @param message Int32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt32Value. */ + interface IUInt32Value { + + /** UInt32Value value */ + value?: (number|null); + } + + /** Represents a UInt32Value. */ + class UInt32Value implements IUInt32Value { + + /** + * Constructs a new UInt32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt32Value); + + /** UInt32Value value. */ + public value: number; + + /** + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; + + /** + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. + * @param message UInt32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BoolValue. */ + interface IBoolValue { + + /** BoolValue value */ + value?: (boolean|null); + } + + /** Represents a BoolValue. */ + class BoolValue implements IBoolValue { + + /** + * Constructs a new BoolValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBoolValue); + + /** BoolValue value. */ + public value: boolean; + + /** + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BoolValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; + + /** + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. + * @param message BoolValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BoolValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BoolValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StringValue. */ + interface IStringValue { + + /** StringValue value */ + value?: (string|null); + } + + /** Represents a StringValue. */ + class StringValue implements IStringValue { + + /** + * Constructs a new StringValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStringValue); + + /** StringValue value. */ + public value: string; + + /** + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StringValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; + + /** + * Creates a plain object from a StringValue message. Also converts values to other types if specified. + * @param message StringValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StringValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StringValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BytesValue. */ + interface IBytesValue { + + /** BytesValue value */ + value?: (Uint8Array|null); + } + + /** Represents a BytesValue. */ + class BytesValue implements IBytesValue { + + /** + * Constructs a new BytesValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBytesValue); + + /** BytesValue value. */ + public value: Uint8Array; + + /** + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BytesValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; + + /** + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. + * @param message BytesValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BytesValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BytesValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Empty. */ + interface IEmpty { + } + + /** Represents an Empty. */ + class Empty implements IEmpty { + + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Empty + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldMask. */ + interface IFieldMask { + + /** FieldMask paths */ + paths?: (string[]|null); + } + + /** Represents a FieldMask. */ + class FieldMask implements IFieldMask { + + /** + * Constructs a new FieldMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldMask); + + /** FieldMask paths. */ + public paths: string[]; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldMask + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @param message FieldMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace type. */ + namespace type { + + /** Properties of a LatLng. */ + interface ILatLng { + + /** LatLng latitude */ + latitude?: (number|null); + + /** LatLng longitude */ + longitude?: (number|null); + } + + /** Represents a LatLng. */ + class LatLng implements ILatLng { + + /** + * Constructs a new LatLng. + * @param [properties] Properties to set + */ + constructor(properties?: google.type.ILatLng); + + /** LatLng latitude. */ + public latitude: number; + + /** LatLng longitude. */ + public longitude: number; + + /** + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LatLng + */ + public static fromObject(object: { [k: string]: any }): google.type.LatLng; + + /** + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @param message LatLng + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LatLng to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LatLng + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** DayOfWeek enum. */ + type DayOfWeek = + "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; + } + + /** Namespace rpc. */ + namespace rpc { + + /** Properties of a Status. */ + interface IStatus { + + /** Status code */ + code?: (number|null); + + /** Status message */ + message?: (string|null); + + /** Status details */ + details?: (google.protobuf.IAny[]|null); + } + + /** Represents a Status. */ + class Status implements IStatus { + + /** + * Constructs a new Status. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IStatus); + + /** Status code. */ + public code: number; + + /** Status message. */ + public message: string; + + /** Status details. */ + public details: google.protobuf.IAny[]; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Status + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Status; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @param message Status + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Status to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Status + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace longrunning. */ + namespace longrunning { + + /** Represents an Operations */ + class Operations extends $protobuf.rpc.Service { + + /** + * Constructs a new Operations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListOperationsResponse + */ + public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void; + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @returns Promise + */ + public listOperations(request: google.longrunning.IListOperationsRequest): Promise; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @returns Promise + */ + public getOperation(request: google.longrunning.IGetOperationRequest): Promise; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @returns Promise + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @returns Promise + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @returns Promise + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise; + } + + namespace Operations { + + /** + * Callback as used by {@link google.longrunning.Operations#listOperations}. + * @param error Error, if any + * @param [response] ListOperationsResponse + */ + type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#getOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#deleteOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#cancelOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#waitOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of an Operation. */ + interface IOperation { + + /** Operation name */ + name?: (string|null); + + /** Operation metadata */ + metadata?: (google.protobuf.IAny|null); + + /** Operation done */ + done?: (boolean|null); + + /** Operation error */ + error?: (google.rpc.IStatus|null); + + /** Operation response */ + response?: (google.protobuf.IAny|null); + } + + /** Represents an Operation. */ + class Operation implements IOperation { + + /** + * Constructs a new Operation. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperation); + + /** Operation name. */ + public name: string; + + /** Operation metadata. */ + public metadata?: (google.protobuf.IAny|null); + + /** Operation done. */ + public done: boolean; + + /** Operation error. */ + public error?: (google.rpc.IStatus|null); + + /** Operation response. */ + public response?: (google.protobuf.IAny|null); + + /** Operation result. */ + public result?: ("error"|"response"); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Operation + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.Operation; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @param message Operation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Operation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Operation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetOperationRequest. */ + interface IGetOperationRequest { + + /** GetOperationRequest name */ + name?: (string|null); + } + + /** Represents a GetOperationRequest. */ + class GetOperationRequest implements IGetOperationRequest { + + /** + * Constructs a new GetOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IGetOperationRequest); + + /** GetOperationRequest name. */ + public name: string; + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @param message GetOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsRequest. */ + interface IListOperationsRequest { + + /** ListOperationsRequest name */ + name?: (string|null); + + /** ListOperationsRequest filter */ + filter?: (string|null); + + /** ListOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListOperationsRequest pageToken */ + pageToken?: (string|null); + + /** ListOperationsRequest returnPartialSuccess */ + returnPartialSuccess?: (boolean|null); + } + + /** Represents a ListOperationsRequest. */ + class ListOperationsRequest implements IListOperationsRequest { + + /** + * Constructs a new ListOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsRequest); + + /** ListOperationsRequest name. */ + public name: string; + + /** ListOperationsRequest filter. */ + public filter: string; + + /** ListOperationsRequest pageSize. */ + public pageSize: number; + + /** ListOperationsRequest pageToken. */ + public pageToken: string; + + /** ListOperationsRequest returnPartialSuccess. */ + public returnPartialSuccess: boolean; + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @param message ListOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsResponse. */ + interface IListOperationsResponse { + + /** ListOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + + /** ListOperationsResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListOperationsResponse. */ + class ListOperationsResponse implements IListOperationsResponse { + + /** + * Constructs a new ListOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsResponse); + + /** ListOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** ListOperationsResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @param message ListOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CancelOperationRequest. */ + interface ICancelOperationRequest { + + /** CancelOperationRequest name */ + name?: (string|null); + } + + /** Represents a CancelOperationRequest. */ + class CancelOperationRequest implements ICancelOperationRequest { + + /** + * Constructs a new CancelOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.ICancelOperationRequest); + + /** CancelOperationRequest name. */ + public name: string; + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CancelOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @param message CancelOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CancelOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteOperationRequest. */ + interface IDeleteOperationRequest { + + /** DeleteOperationRequest name */ + name?: (string|null); + } + + /** Represents a DeleteOperationRequest. */ + class DeleteOperationRequest implements IDeleteOperationRequest { + + /** + * Constructs a new DeleteOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IDeleteOperationRequest); + + /** DeleteOperationRequest name. */ + public name: string; + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @param message DeleteOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WaitOperationRequest. */ + interface IWaitOperationRequest { + + /** WaitOperationRequest name */ + name?: (string|null); + + /** WaitOperationRequest timeout */ + timeout?: (google.protobuf.IDuration|null); + } + + /** Represents a WaitOperationRequest. */ + class WaitOperationRequest implements IWaitOperationRequest { + + /** + * Constructs a new WaitOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IWaitOperationRequest); + + /** WaitOperationRequest name. */ + public name: string; + + /** WaitOperationRequest timeout. */ + public timeout?: (google.protobuf.IDuration|null); + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @param message WaitOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WaitOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an OperationInfo. */ + interface IOperationInfo { + + /** OperationInfo responseType */ + responseType?: (string|null); + + /** OperationInfo metadataType */ + metadataType?: (string|null); + } + + /** Represents an OperationInfo. */ + class OperationInfo implements IOperationInfo { + + /** + * Constructs a new OperationInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperationInfo); + + /** OperationInfo responseType. */ + public responseType: string; + + /** OperationInfo metadataType. */ + public metadataType: string; + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationInfo + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @param message OperationInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } +} diff --git a/handwritten/firestore/dev/protos/firestore_v1_proto_api.js b/handwritten/firestore/dev/protos/firestore_v1_proto_api.js new file mode 100644 index 00000000000..b53bbf22768 --- /dev/null +++ b/handwritten/firestore/dev/protos/firestore_v1_proto_api.js @@ -0,0 +1,27185 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/ +(function(global, factory) { /* global define, require, module */ + + /* AMD */ if (typeof define === 'function' && define.amd) + define(["protobufjs/minimal"], factory); + + /* CommonJS */ else if (typeof require === 'function' && typeof module === 'object' && module && module.exports) + module.exports = factory(require("protobufjs/minimal")); + +})(this, function($protobuf) { + "use strict"; + + // Common aliases + var $util = $protobuf.util; + + // Exported root namespace + var $root = $protobuf.roots.firestore_v1 || ($protobuf.roots.firestore_v1 = {}); + + $root.firestore = (function() { + + /** + * Namespace firestore. + * @exports firestore + * @namespace + */ + var firestore = {}; + + firestore.BundledQuery = (function() { + + /** + * Properties of a BundledQuery. + * @memberof firestore + * @interface IBundledQuery + * @property {string|null} [parent] BundledQuery parent + * @property {google.firestore.v1.IStructuredQuery|null} [structuredQuery] BundledQuery structuredQuery + * @property {firestore.BundledQuery.LimitType|null} [limitType] BundledQuery limitType + */ + + /** + * Constructs a new BundledQuery. + * @memberof firestore + * @classdesc Represents a BundledQuery. + * @implements IBundledQuery + * @constructor + * @param {firestore.IBundledQuery=} [properties] Properties to set + */ + function BundledQuery(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BundledQuery parent. + * @member {string} parent + * @memberof firestore.BundledQuery + * @instance + */ + BundledQuery.prototype.parent = ""; + + /** + * BundledQuery structuredQuery. + * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery + * @memberof firestore.BundledQuery + * @instance + */ + BundledQuery.prototype.structuredQuery = null; + + /** + * BundledQuery limitType. + * @member {firestore.BundledQuery.LimitType} limitType + * @memberof firestore.BundledQuery + * @instance + */ + BundledQuery.prototype.limitType = 0; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * BundledQuery queryType. + * @member {"structuredQuery"|undefined} queryType + * @memberof firestore.BundledQuery + * @instance + */ + Object.defineProperty(BundledQuery.prototype, "queryType", { + get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a BundledQuery message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof firestore.BundledQuery + * @static + * @param {Object.} object Plain object + * @returns {firestore.BundledQuery} BundledQuery + */ + BundledQuery.fromObject = function fromObject(object) { + if (object instanceof $root.firestore.BundledQuery) + return object; + var message = new $root.firestore.BundledQuery(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.structuredQuery != null) { + if (typeof object.structuredQuery !== "object") + throw TypeError(".firestore.BundledQuery.structuredQuery: object expected"); + message.structuredQuery = $root.google.firestore.v1.StructuredQuery.fromObject(object.structuredQuery); + } + switch (object.limitType) { + default: + if (typeof object.limitType === "number") { + message.limitType = object.limitType; + break; + } + break; + case "FIRST": + case 0: + message.limitType = 0; + break; + case "LAST": + case 1: + message.limitType = 1; + break; + } + return message; + }; + + /** + * Creates a plain object from a BundledQuery message. Also converts values to other types if specified. + * @function toObject + * @memberof firestore.BundledQuery + * @static + * @param {firestore.BundledQuery} message BundledQuery + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BundledQuery.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.limitType = options.enums === String ? "FIRST" : 0; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { + object.structuredQuery = $root.google.firestore.v1.StructuredQuery.toObject(message.structuredQuery, options); + if (options.oneofs) + object.queryType = "structuredQuery"; + } + if (message.limitType != null && message.hasOwnProperty("limitType")) + object.limitType = options.enums === String ? $root.firestore.BundledQuery.LimitType[message.limitType] === undefined ? message.limitType : $root.firestore.BundledQuery.LimitType[message.limitType] : message.limitType; + return object; + }; + + /** + * Converts this BundledQuery to JSON. + * @function toJSON + * @memberof firestore.BundledQuery + * @instance + * @returns {Object.} JSON object + */ + BundledQuery.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BundledQuery + * @function getTypeUrl + * @memberof firestore.BundledQuery + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BundledQuery.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/firestore.BundledQuery"; + }; + + /** + * LimitType enum. + * @name firestore.BundledQuery.LimitType + * @enum {string} + * @property {string} FIRST=FIRST FIRST value + * @property {string} LAST=LAST LAST value + */ + BundledQuery.LimitType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "FIRST"] = "FIRST"; + values[valuesById[1] = "LAST"] = "LAST"; + return values; + })(); + + return BundledQuery; + })(); + + firestore.NamedQuery = (function() { + + /** + * Properties of a NamedQuery. + * @memberof firestore + * @interface INamedQuery + * @property {string|null} [name] NamedQuery name + * @property {firestore.IBundledQuery|null} [bundledQuery] NamedQuery bundledQuery + * @property {google.protobuf.ITimestamp|null} [readTime] NamedQuery readTime + */ + + /** + * Constructs a new NamedQuery. + * @memberof firestore + * @classdesc Represents a NamedQuery. + * @implements INamedQuery + * @constructor + * @param {firestore.INamedQuery=} [properties] Properties to set + */ + function NamedQuery(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * NamedQuery name. + * @member {string} name + * @memberof firestore.NamedQuery + * @instance + */ + NamedQuery.prototype.name = ""; + + /** + * NamedQuery bundledQuery. + * @member {firestore.IBundledQuery|null|undefined} bundledQuery + * @memberof firestore.NamedQuery + * @instance + */ + NamedQuery.prototype.bundledQuery = null; + + /** + * NamedQuery readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof firestore.NamedQuery + * @instance + */ + NamedQuery.prototype.readTime = null; + + /** + * Creates a NamedQuery message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof firestore.NamedQuery + * @static + * @param {Object.} object Plain object + * @returns {firestore.NamedQuery} NamedQuery + */ + NamedQuery.fromObject = function fromObject(object) { + if (object instanceof $root.firestore.NamedQuery) + return object; + var message = new $root.firestore.NamedQuery(); + if (object.name != null) + message.name = String(object.name); + if (object.bundledQuery != null) { + if (typeof object.bundledQuery !== "object") + throw TypeError(".firestore.NamedQuery.bundledQuery: object expected"); + message.bundledQuery = $root.firestore.BundledQuery.fromObject(object.bundledQuery); + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".firestore.NamedQuery.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a NamedQuery message. Also converts values to other types if specified. + * @function toObject + * @memberof firestore.NamedQuery + * @static + * @param {firestore.NamedQuery} message NamedQuery + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + NamedQuery.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.bundledQuery = null; + object.readTime = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.bundledQuery != null && message.hasOwnProperty("bundledQuery")) + object.bundledQuery = $root.firestore.BundledQuery.toObject(message.bundledQuery, options); + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + return object; + }; + + /** + * Converts this NamedQuery to JSON. + * @function toJSON + * @memberof firestore.NamedQuery + * @instance + * @returns {Object.} JSON object + */ + NamedQuery.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for NamedQuery + * @function getTypeUrl + * @memberof firestore.NamedQuery + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + NamedQuery.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/firestore.NamedQuery"; + }; + + return NamedQuery; + })(); + + firestore.BundledDocumentMetadata = (function() { + + /** + * Properties of a BundledDocumentMetadata. + * @memberof firestore + * @interface IBundledDocumentMetadata + * @property {string|null} [name] BundledDocumentMetadata name + * @property {google.protobuf.ITimestamp|null} [readTime] BundledDocumentMetadata readTime + * @property {boolean|null} [exists] BundledDocumentMetadata exists + * @property {Array.|null} [queries] BundledDocumentMetadata queries + */ + + /** + * Constructs a new BundledDocumentMetadata. + * @memberof firestore + * @classdesc Represents a BundledDocumentMetadata. + * @implements IBundledDocumentMetadata + * @constructor + * @param {firestore.IBundledDocumentMetadata=} [properties] Properties to set + */ + function BundledDocumentMetadata(properties) { + this.queries = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BundledDocumentMetadata name. + * @member {string} name + * @memberof firestore.BundledDocumentMetadata + * @instance + */ + BundledDocumentMetadata.prototype.name = ""; + + /** + * BundledDocumentMetadata readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof firestore.BundledDocumentMetadata + * @instance + */ + BundledDocumentMetadata.prototype.readTime = null; + + /** + * BundledDocumentMetadata exists. + * @member {boolean} exists + * @memberof firestore.BundledDocumentMetadata + * @instance + */ + BundledDocumentMetadata.prototype.exists = false; + + /** + * BundledDocumentMetadata queries. + * @member {Array.} queries + * @memberof firestore.BundledDocumentMetadata + * @instance + */ + BundledDocumentMetadata.prototype.queries = $util.emptyArray; + + /** + * Creates a BundledDocumentMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof firestore.BundledDocumentMetadata + * @static + * @param {Object.} object Plain object + * @returns {firestore.BundledDocumentMetadata} BundledDocumentMetadata + */ + BundledDocumentMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.firestore.BundledDocumentMetadata) + return object; + var message = new $root.firestore.BundledDocumentMetadata(); + if (object.name != null) + message.name = String(object.name); + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".firestore.BundledDocumentMetadata.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.exists != null) + message.exists = Boolean(object.exists); + if (object.queries) { + if (!Array.isArray(object.queries)) + throw TypeError(".firestore.BundledDocumentMetadata.queries: array expected"); + message.queries = []; + for (var i = 0; i < object.queries.length; ++i) + message.queries[i] = String(object.queries[i]); + } + return message; + }; + + /** + * Creates a plain object from a BundledDocumentMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof firestore.BundledDocumentMetadata + * @static + * @param {firestore.BundledDocumentMetadata} message BundledDocumentMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BundledDocumentMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.queries = []; + if (options.defaults) { + object.name = ""; + object.readTime = null; + object.exists = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (message.exists != null && message.hasOwnProperty("exists")) + object.exists = message.exists; + if (message.queries && message.queries.length) { + object.queries = []; + for (var j = 0; j < message.queries.length; ++j) + object.queries[j] = message.queries[j]; + } + return object; + }; + + /** + * Converts this BundledDocumentMetadata to JSON. + * @function toJSON + * @memberof firestore.BundledDocumentMetadata + * @instance + * @returns {Object.} JSON object + */ + BundledDocumentMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BundledDocumentMetadata + * @function getTypeUrl + * @memberof firestore.BundledDocumentMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BundledDocumentMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/firestore.BundledDocumentMetadata"; + }; + + return BundledDocumentMetadata; + })(); + + firestore.BundleMetadata = (function() { + + /** + * Properties of a BundleMetadata. + * @memberof firestore + * @interface IBundleMetadata + * @property {string|null} [id] BundleMetadata id + * @property {google.protobuf.ITimestamp|null} [createTime] BundleMetadata createTime + * @property {number|null} [version] BundleMetadata version + * @property {number|null} [totalDocuments] BundleMetadata totalDocuments + * @property {number|string|null} [totalBytes] BundleMetadata totalBytes + */ + + /** + * Constructs a new BundleMetadata. + * @memberof firestore + * @classdesc Represents a BundleMetadata. + * @implements IBundleMetadata + * @constructor + * @param {firestore.IBundleMetadata=} [properties] Properties to set + */ + function BundleMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BundleMetadata id. + * @member {string} id + * @memberof firestore.BundleMetadata + * @instance + */ + BundleMetadata.prototype.id = ""; + + /** + * BundleMetadata createTime. + * @member {google.protobuf.ITimestamp|null|undefined} createTime + * @memberof firestore.BundleMetadata + * @instance + */ + BundleMetadata.prototype.createTime = null; + + /** + * BundleMetadata version. + * @member {number} version + * @memberof firestore.BundleMetadata + * @instance + */ + BundleMetadata.prototype.version = 0; + + /** + * BundleMetadata totalDocuments. + * @member {number} totalDocuments + * @memberof firestore.BundleMetadata + * @instance + */ + BundleMetadata.prototype.totalDocuments = 0; + + /** + * BundleMetadata totalBytes. + * @member {number|string} totalBytes + * @memberof firestore.BundleMetadata + * @instance + */ + BundleMetadata.prototype.totalBytes = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * Creates a BundleMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof firestore.BundleMetadata + * @static + * @param {Object.} object Plain object + * @returns {firestore.BundleMetadata} BundleMetadata + */ + BundleMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.firestore.BundleMetadata) + return object; + var message = new $root.firestore.BundleMetadata(); + if (object.id != null) + message.id = String(object.id); + if (object.createTime != null) { + if (typeof object.createTime !== "object") + throw TypeError(".firestore.BundleMetadata.createTime: object expected"); + message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime); + } + if (object.version != null) + message.version = object.version >>> 0; + if (object.totalDocuments != null) + message.totalDocuments = object.totalDocuments >>> 0; + if (object.totalBytes != null) + if ($util.Long) + (message.totalBytes = $util.Long.fromValue(object.totalBytes)).unsigned = true; + else if (typeof object.totalBytes === "string") + message.totalBytes = parseInt(object.totalBytes, 10); + else if (typeof object.totalBytes === "number") + message.totalBytes = object.totalBytes; + else if (typeof object.totalBytes === "object") + message.totalBytes = new $util.LongBits(object.totalBytes.low >>> 0, object.totalBytes.high >>> 0).toNumber(true); + return message; + }; + + /** + * Creates a plain object from a BundleMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof firestore.BundleMetadata + * @static + * @param {firestore.BundleMetadata} message BundleMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BundleMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.id = ""; + object.createTime = null; + object.version = 0; + object.totalDocuments = 0; + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.totalBytes = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.totalBytes = options.longs === String ? "0" : 0; + } + if (message.id != null && message.hasOwnProperty("id")) + object.id = message.id; + if (message.createTime != null && message.hasOwnProperty("createTime")) + object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); + if (message.version != null && message.hasOwnProperty("version")) + object.version = message.version; + if (message.totalDocuments != null && message.hasOwnProperty("totalDocuments")) + object.totalDocuments = message.totalDocuments; + if (message.totalBytes != null && message.hasOwnProperty("totalBytes")) + if (typeof message.totalBytes === "number") + object.totalBytes = options.longs === String ? String(message.totalBytes) : message.totalBytes; + else + object.totalBytes = options.longs === String ? $util.Long.prototype.toString.call(message.totalBytes) : options.longs === Number ? new $util.LongBits(message.totalBytes.low >>> 0, message.totalBytes.high >>> 0).toNumber(true) : message.totalBytes; + return object; + }; + + /** + * Converts this BundleMetadata to JSON. + * @function toJSON + * @memberof firestore.BundleMetadata + * @instance + * @returns {Object.} JSON object + */ + BundleMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BundleMetadata + * @function getTypeUrl + * @memberof firestore.BundleMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BundleMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/firestore.BundleMetadata"; + }; + + return BundleMetadata; + })(); + + firestore.BundleElement = (function() { + + /** + * Properties of a BundleElement. + * @memberof firestore + * @interface IBundleElement + * @property {firestore.IBundleMetadata|null} [metadata] BundleElement metadata + * @property {firestore.INamedQuery|null} [namedQuery] BundleElement namedQuery + * @property {firestore.IBundledDocumentMetadata|null} [documentMetadata] BundleElement documentMetadata + * @property {google.firestore.v1.IDocument|null} [document] BundleElement document + */ + + /** + * Constructs a new BundleElement. + * @memberof firestore + * @classdesc Represents a BundleElement. + * @implements IBundleElement + * @constructor + * @param {firestore.IBundleElement=} [properties] Properties to set + */ + function BundleElement(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BundleElement metadata. + * @member {firestore.IBundleMetadata|null|undefined} metadata + * @memberof firestore.BundleElement + * @instance + */ + BundleElement.prototype.metadata = null; + + /** + * BundleElement namedQuery. + * @member {firestore.INamedQuery|null|undefined} namedQuery + * @memberof firestore.BundleElement + * @instance + */ + BundleElement.prototype.namedQuery = null; + + /** + * BundleElement documentMetadata. + * @member {firestore.IBundledDocumentMetadata|null|undefined} documentMetadata + * @memberof firestore.BundleElement + * @instance + */ + BundleElement.prototype.documentMetadata = null; + + /** + * BundleElement document. + * @member {google.firestore.v1.IDocument|null|undefined} document + * @memberof firestore.BundleElement + * @instance + */ + BundleElement.prototype.document = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * BundleElement elementType. + * @member {"metadata"|"namedQuery"|"documentMetadata"|"document"|undefined} elementType + * @memberof firestore.BundleElement + * @instance + */ + Object.defineProperty(BundleElement.prototype, "elementType", { + get: $util.oneOfGetter($oneOfFields = ["metadata", "namedQuery", "documentMetadata", "document"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a BundleElement message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof firestore.BundleElement + * @static + * @param {Object.} object Plain object + * @returns {firestore.BundleElement} BundleElement + */ + BundleElement.fromObject = function fromObject(object) { + if (object instanceof $root.firestore.BundleElement) + return object; + var message = new $root.firestore.BundleElement(); + if (object.metadata != null) { + if (typeof object.metadata !== "object") + throw TypeError(".firestore.BundleElement.metadata: object expected"); + message.metadata = $root.firestore.BundleMetadata.fromObject(object.metadata); + } + if (object.namedQuery != null) { + if (typeof object.namedQuery !== "object") + throw TypeError(".firestore.BundleElement.namedQuery: object expected"); + message.namedQuery = $root.firestore.NamedQuery.fromObject(object.namedQuery); + } + if (object.documentMetadata != null) { + if (typeof object.documentMetadata !== "object") + throw TypeError(".firestore.BundleElement.documentMetadata: object expected"); + message.documentMetadata = $root.firestore.BundledDocumentMetadata.fromObject(object.documentMetadata); + } + if (object.document != null) { + if (typeof object.document !== "object") + throw TypeError(".firestore.BundleElement.document: object expected"); + message.document = $root.google.firestore.v1.Document.fromObject(object.document); + } + return message; + }; + + /** + * Creates a plain object from a BundleElement message. Also converts values to other types if specified. + * @function toObject + * @memberof firestore.BundleElement + * @static + * @param {firestore.BundleElement} message BundleElement + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BundleElement.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.metadata != null && message.hasOwnProperty("metadata")) { + object.metadata = $root.firestore.BundleMetadata.toObject(message.metadata, options); + if (options.oneofs) + object.elementType = "metadata"; + } + if (message.namedQuery != null && message.hasOwnProperty("namedQuery")) { + object.namedQuery = $root.firestore.NamedQuery.toObject(message.namedQuery, options); + if (options.oneofs) + object.elementType = "namedQuery"; + } + if (message.documentMetadata != null && message.hasOwnProperty("documentMetadata")) { + object.documentMetadata = $root.firestore.BundledDocumentMetadata.toObject(message.documentMetadata, options); + if (options.oneofs) + object.elementType = "documentMetadata"; + } + if (message.document != null && message.hasOwnProperty("document")) { + object.document = $root.google.firestore.v1.Document.toObject(message.document, options); + if (options.oneofs) + object.elementType = "document"; + } + return object; + }; + + /** + * Converts this BundleElement to JSON. + * @function toJSON + * @memberof firestore.BundleElement + * @instance + * @returns {Object.} JSON object + */ + BundleElement.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BundleElement + * @function getTypeUrl + * @memberof firestore.BundleElement + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BundleElement.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/firestore.BundleElement"; + }; + + return BundleElement; + })(); + + return firestore; + })(); + + $root.google = (function() { + + /** + * Namespace google. + * @exports google + * @namespace + */ + var google = {}; + + google.firestore = (function() { + + /** + * Namespace firestore. + * @memberof google + * @namespace + */ + var firestore = {}; + + firestore.v1 = (function() { + + /** + * Namespace v1. + * @memberof google.firestore + * @namespace + */ + var v1 = {}; + + v1.AggregationResult = (function() { + + /** + * Properties of an AggregationResult. + * @memberof google.firestore.v1 + * @interface IAggregationResult + * @property {Object.|null} [aggregateFields] AggregationResult aggregateFields + */ + + /** + * Constructs a new AggregationResult. + * @memberof google.firestore.v1 + * @classdesc Represents an AggregationResult. + * @implements IAggregationResult + * @constructor + * @param {google.firestore.v1.IAggregationResult=} [properties] Properties to set + */ + function AggregationResult(properties) { + this.aggregateFields = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * AggregationResult aggregateFields. + * @member {Object.} aggregateFields + * @memberof google.firestore.v1.AggregationResult + * @instance + */ + AggregationResult.prototype.aggregateFields = $util.emptyObject; + + /** + * Creates an AggregationResult message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.AggregationResult + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.AggregationResult} AggregationResult + */ + AggregationResult.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.AggregationResult) + return object; + var message = new $root.google.firestore.v1.AggregationResult(); + if (object.aggregateFields) { + if (typeof object.aggregateFields !== "object") + throw TypeError(".google.firestore.v1.AggregationResult.aggregateFields: object expected"); + message.aggregateFields = {}; + for (var keys = Object.keys(object.aggregateFields), i = 0; i < keys.length; ++i) { + if (typeof object.aggregateFields[keys[i]] !== "object") + throw TypeError(".google.firestore.v1.AggregationResult.aggregateFields: object expected"); + message.aggregateFields[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.aggregateFields[keys[i]]); + } + } + return message; + }; + + /** + * Creates a plain object from an AggregationResult message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.AggregationResult + * @static + * @param {google.firestore.v1.AggregationResult} message AggregationResult + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AggregationResult.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.aggregateFields = {}; + var keys2; + if (message.aggregateFields && (keys2 = Object.keys(message.aggregateFields)).length) { + object.aggregateFields = {}; + for (var j = 0; j < keys2.length; ++j) + object.aggregateFields[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.aggregateFields[keys2[j]], options); + } + return object; + }; + + /** + * Converts this AggregationResult to JSON. + * @function toJSON + * @memberof google.firestore.v1.AggregationResult + * @instance + * @returns {Object.} JSON object + */ + AggregationResult.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AggregationResult + * @function getTypeUrl + * @memberof google.firestore.v1.AggregationResult + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AggregationResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.AggregationResult"; + }; + + return AggregationResult; + })(); + + v1.Document = (function() { + + /** + * Properties of a Document. + * @memberof google.firestore.v1 + * @interface IDocument + * @property {string|null} [name] Document name + * @property {Object.|null} [fields] Document fields + * @property {google.protobuf.ITimestamp|null} [createTime] Document createTime + * @property {google.protobuf.ITimestamp|null} [updateTime] Document updateTime + */ + + /** + * Constructs a new Document. + * @memberof google.firestore.v1 + * @classdesc Represents a Document. + * @implements IDocument + * @constructor + * @param {google.firestore.v1.IDocument=} [properties] Properties to set + */ + function Document(properties) { + this.fields = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Document name. + * @member {string} name + * @memberof google.firestore.v1.Document + * @instance + */ + Document.prototype.name = ""; + + /** + * Document fields. + * @member {Object.} fields + * @memberof google.firestore.v1.Document + * @instance + */ + Document.prototype.fields = $util.emptyObject; + + /** + * Document createTime. + * @member {google.protobuf.ITimestamp|null|undefined} createTime + * @memberof google.firestore.v1.Document + * @instance + */ + Document.prototype.createTime = null; + + /** + * Document updateTime. + * @member {google.protobuf.ITimestamp|null|undefined} updateTime + * @memberof google.firestore.v1.Document + * @instance + */ + Document.prototype.updateTime = null; + + /** + * Creates a Document message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Document + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Document} Document + */ + Document.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Document) + return object; + var message = new $root.google.firestore.v1.Document(); + if (object.name != null) + message.name = String(object.name); + if (object.fields) { + if (typeof object.fields !== "object") + throw TypeError(".google.firestore.v1.Document.fields: object expected"); + message.fields = {}; + for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { + if (typeof object.fields[keys[i]] !== "object") + throw TypeError(".google.firestore.v1.Document.fields: object expected"); + message.fields[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.fields[keys[i]]); + } + } + if (object.createTime != null) { + if (typeof object.createTime !== "object") + throw TypeError(".google.firestore.v1.Document.createTime: object expected"); + message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime); + } + if (object.updateTime != null) { + if (typeof object.updateTime !== "object") + throw TypeError(".google.firestore.v1.Document.updateTime: object expected"); + message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + } + return message; + }; + + /** + * Creates a plain object from a Document message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Document + * @static + * @param {google.firestore.v1.Document} message Document + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Document.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.fields = {}; + if (options.defaults) { + object.name = ""; + object.createTime = null; + object.updateTime = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + var keys2; + if (message.fields && (keys2 = Object.keys(message.fields)).length) { + object.fields = {}; + for (var j = 0; j < keys2.length; ++j) + object.fields[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.fields[keys2[j]], options); + } + if (message.createTime != null && message.hasOwnProperty("createTime")) + object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); + if (message.updateTime != null && message.hasOwnProperty("updateTime")) + object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + return object; + }; + + /** + * Converts this Document to JSON. + * @function toJSON + * @memberof google.firestore.v1.Document + * @instance + * @returns {Object.} JSON object + */ + Document.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Document + * @function getTypeUrl + * @memberof google.firestore.v1.Document + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Document.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Document"; + }; + + return Document; + })(); + + v1.Value = (function() { + + /** + * Properties of a Value. + * @memberof google.firestore.v1 + * @interface IValue + * @property {google.protobuf.NullValue|null} [nullValue] Value nullValue + * @property {boolean|null} [booleanValue] Value booleanValue + * @property {number|string|null} [integerValue] Value integerValue + * @property {number|null} [doubleValue] Value doubleValue + * @property {google.protobuf.ITimestamp|null} [timestampValue] Value timestampValue + * @property {string|null} [stringValue] Value stringValue + * @property {Uint8Array|null} [bytesValue] Value bytesValue + * @property {string|null} [referenceValue] Value referenceValue + * @property {google.type.ILatLng|null} [geoPointValue] Value geoPointValue + * @property {google.firestore.v1.IArrayValue|null} [arrayValue] Value arrayValue + * @property {google.firestore.v1.IMapValue|null} [mapValue] Value mapValue + * @property {string|null} [fieldReferenceValue] Value fieldReferenceValue + * @property {google.firestore.v1.IFunction|null} [functionValue] Value functionValue + * @property {google.firestore.v1.IPipeline|null} [pipelineValue] Value pipelineValue + */ + + /** + * Constructs a new Value. + * @memberof google.firestore.v1 + * @classdesc Represents a Value. + * @implements IValue + * @constructor + * @param {google.firestore.v1.IValue=} [properties] Properties to set + */ + function Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Value nullValue. + * @member {google.protobuf.NullValue|null|undefined} nullValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.nullValue = null; + + /** + * Value booleanValue. + * @member {boolean|null|undefined} booleanValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.booleanValue = null; + + /** + * Value integerValue. + * @member {number|string|null|undefined} integerValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.integerValue = null; + + /** + * Value doubleValue. + * @member {number|null|undefined} doubleValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.doubleValue = null; + + /** + * Value timestampValue. + * @member {google.protobuf.ITimestamp|null|undefined} timestampValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.timestampValue = null; + + /** + * Value stringValue. + * @member {string|null|undefined} stringValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.stringValue = null; + + /** + * Value bytesValue. + * @member {Uint8Array|null|undefined} bytesValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.bytesValue = null; + + /** + * Value referenceValue. + * @member {string|null|undefined} referenceValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.referenceValue = null; + + /** + * Value geoPointValue. + * @member {google.type.ILatLng|null|undefined} geoPointValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.geoPointValue = null; + + /** + * Value arrayValue. + * @member {google.firestore.v1.IArrayValue|null|undefined} arrayValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.arrayValue = null; + + /** + * Value mapValue. + * @member {google.firestore.v1.IMapValue|null|undefined} mapValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.mapValue = null; + + /** + * Value fieldReferenceValue. + * @member {string|null|undefined} fieldReferenceValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.fieldReferenceValue = null; + + /** + * Value functionValue. + * @member {google.firestore.v1.IFunction|null|undefined} functionValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.functionValue = null; + + /** + * Value pipelineValue. + * @member {google.firestore.v1.IPipeline|null|undefined} pipelineValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.pipelineValue = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Value valueType. + * @member {"nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"|"fieldReferenceValue"|"functionValue"|"pipelineValue"|undefined} valueType + * @memberof google.firestore.v1.Value + * @instance + */ + Object.defineProperty(Value.prototype, "valueType", { + get: $util.oneOfGetter($oneOfFields = ["nullValue", "booleanValue", "integerValue", "doubleValue", "timestampValue", "stringValue", "bytesValue", "referenceValue", "geoPointValue", "arrayValue", "mapValue", "fieldReferenceValue", "functionValue", "pipelineValue"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Value + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Value} Value + */ + Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Value) + return object; + var message = new $root.google.firestore.v1.Value(); + switch (object.nullValue) { + default: + if (typeof object.nullValue === "number") { + message.nullValue = object.nullValue; + break; + } + break; + case "NULL_VALUE": + case 0: + message.nullValue = 0; + break; + } + if (object.booleanValue != null) + message.booleanValue = Boolean(object.booleanValue); + if (object.integerValue != null) + if ($util.Long) + (message.integerValue = $util.Long.fromValue(object.integerValue)).unsigned = false; + else if (typeof object.integerValue === "string") + message.integerValue = parseInt(object.integerValue, 10); + else if (typeof object.integerValue === "number") + message.integerValue = object.integerValue; + else if (typeof object.integerValue === "object") + message.integerValue = new $util.LongBits(object.integerValue.low >>> 0, object.integerValue.high >>> 0).toNumber(); + if (object.doubleValue != null) + message.doubleValue = Number(object.doubleValue); + if (object.timestampValue != null) { + if (typeof object.timestampValue !== "object") + throw TypeError(".google.firestore.v1.Value.timestampValue: object expected"); + message.timestampValue = $root.google.protobuf.Timestamp.fromObject(object.timestampValue); + } + if (object.stringValue != null) + message.stringValue = String(object.stringValue); + if (object.bytesValue != null) + if (typeof object.bytesValue === "string") + $util.base64.decode(object.bytesValue, message.bytesValue = $util.newBuffer($util.base64.length(object.bytesValue)), 0); + else if (object.bytesValue.length >= 0) + message.bytesValue = object.bytesValue; + if (object.referenceValue != null) + message.referenceValue = String(object.referenceValue); + if (object.geoPointValue != null) { + if (typeof object.geoPointValue !== "object") + throw TypeError(".google.firestore.v1.Value.geoPointValue: object expected"); + message.geoPointValue = $root.google.type.LatLng.fromObject(object.geoPointValue); + } + if (object.arrayValue != null) { + if (typeof object.arrayValue !== "object") + throw TypeError(".google.firestore.v1.Value.arrayValue: object expected"); + message.arrayValue = $root.google.firestore.v1.ArrayValue.fromObject(object.arrayValue); + } + if (object.mapValue != null) { + if (typeof object.mapValue !== "object") + throw TypeError(".google.firestore.v1.Value.mapValue: object expected"); + message.mapValue = $root.google.firestore.v1.MapValue.fromObject(object.mapValue); + } + if (object.fieldReferenceValue != null) + message.fieldReferenceValue = String(object.fieldReferenceValue); + if (object.functionValue != null) { + if (typeof object.functionValue !== "object") + throw TypeError(".google.firestore.v1.Value.functionValue: object expected"); + message.functionValue = $root.google.firestore.v1.Function.fromObject(object.functionValue); + } + if (object.pipelineValue != null) { + if (typeof object.pipelineValue !== "object") + throw TypeError(".google.firestore.v1.Value.pipelineValue: object expected"); + message.pipelineValue = $root.google.firestore.v1.Pipeline.fromObject(object.pipelineValue); + } + return message; + }; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Value + * @static + * @param {google.firestore.v1.Value} message Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.booleanValue != null && message.hasOwnProperty("booleanValue")) { + object.booleanValue = message.booleanValue; + if (options.oneofs) + object.valueType = "booleanValue"; + } + if (message.integerValue != null && message.hasOwnProperty("integerValue")) { + if (typeof message.integerValue === "number") + object.integerValue = options.longs === String ? String(message.integerValue) : message.integerValue; + else + object.integerValue = options.longs === String ? $util.Long.prototype.toString.call(message.integerValue) : options.longs === Number ? new $util.LongBits(message.integerValue.low >>> 0, message.integerValue.high >>> 0).toNumber() : message.integerValue; + if (options.oneofs) + object.valueType = "integerValue"; + } + if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) { + object.doubleValue = options.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue; + if (options.oneofs) + object.valueType = "doubleValue"; + } + if (message.referenceValue != null && message.hasOwnProperty("referenceValue")) { + object.referenceValue = message.referenceValue; + if (options.oneofs) + object.valueType = "referenceValue"; + } + if (message.mapValue != null && message.hasOwnProperty("mapValue")) { + object.mapValue = $root.google.firestore.v1.MapValue.toObject(message.mapValue, options); + if (options.oneofs) + object.valueType = "mapValue"; + } + if (message.geoPointValue != null && message.hasOwnProperty("geoPointValue")) { + object.geoPointValue = $root.google.type.LatLng.toObject(message.geoPointValue, options); + if (options.oneofs) + object.valueType = "geoPointValue"; + } + if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) { + object.arrayValue = $root.google.firestore.v1.ArrayValue.toObject(message.arrayValue, options); + if (options.oneofs) + object.valueType = "arrayValue"; + } + if (message.timestampValue != null && message.hasOwnProperty("timestampValue")) { + object.timestampValue = $root.google.protobuf.Timestamp.toObject(message.timestampValue, options); + if (options.oneofs) + object.valueType = "timestampValue"; + } + if (message.nullValue != null && message.hasOwnProperty("nullValue")) { + object.nullValue = options.enums === String ? $root.google.protobuf.NullValue[message.nullValue] === undefined ? message.nullValue : $root.google.protobuf.NullValue[message.nullValue] : message.nullValue; + if (options.oneofs) + object.valueType = "nullValue"; + } + if (message.stringValue != null && message.hasOwnProperty("stringValue")) { + object.stringValue = message.stringValue; + if (options.oneofs) + object.valueType = "stringValue"; + } + if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) { + object.bytesValue = options.bytes === String ? $util.base64.encode(message.bytesValue, 0, message.bytesValue.length) : options.bytes === Array ? Array.prototype.slice.call(message.bytesValue) : message.bytesValue; + if (options.oneofs) + object.valueType = "bytesValue"; + } + if (message.fieldReferenceValue != null && message.hasOwnProperty("fieldReferenceValue")) { + object.fieldReferenceValue = message.fieldReferenceValue; + if (options.oneofs) + object.valueType = "fieldReferenceValue"; + } + if (message.functionValue != null && message.hasOwnProperty("functionValue")) { + object.functionValue = $root.google.firestore.v1.Function.toObject(message.functionValue, options); + if (options.oneofs) + object.valueType = "functionValue"; + } + if (message.pipelineValue != null && message.hasOwnProperty("pipelineValue")) { + object.pipelineValue = $root.google.firestore.v1.Pipeline.toObject(message.pipelineValue, options); + if (options.oneofs) + object.valueType = "pipelineValue"; + } + return object; + }; + + /** + * Converts this Value to JSON. + * @function toJSON + * @memberof google.firestore.v1.Value + * @instance + * @returns {Object.} JSON object + */ + Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Value + * @function getTypeUrl + * @memberof google.firestore.v1.Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Value"; + }; + + return Value; + })(); + + v1.ArrayValue = (function() { + + /** + * Properties of an ArrayValue. + * @memberof google.firestore.v1 + * @interface IArrayValue + * @property {Array.|null} [values] ArrayValue values + */ + + /** + * Constructs a new ArrayValue. + * @memberof google.firestore.v1 + * @classdesc Represents an ArrayValue. + * @implements IArrayValue + * @constructor + * @param {google.firestore.v1.IArrayValue=} [properties] Properties to set + */ + function ArrayValue(properties) { + this.values = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ArrayValue values. + * @member {Array.} values + * @memberof google.firestore.v1.ArrayValue + * @instance + */ + ArrayValue.prototype.values = $util.emptyArray; + + /** + * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ArrayValue + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ArrayValue} ArrayValue + */ + ArrayValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ArrayValue) + return object; + var message = new $root.google.firestore.v1.ArrayValue(); + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".google.firestore.v1.ArrayValue.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".google.firestore.v1.ArrayValue.values: object expected"); + message.values[i] = $root.google.firestore.v1.Value.fromObject(object.values[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ArrayValue + * @static + * @param {google.firestore.v1.ArrayValue} message ArrayValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ArrayValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.values = []; + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.google.firestore.v1.Value.toObject(message.values[j], options); + } + return object; + }; + + /** + * Converts this ArrayValue to JSON. + * @function toJSON + * @memberof google.firestore.v1.ArrayValue + * @instance + * @returns {Object.} JSON object + */ + ArrayValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ArrayValue + * @function getTypeUrl + * @memberof google.firestore.v1.ArrayValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ArrayValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ArrayValue"; + }; + + return ArrayValue; + })(); + + v1.MapValue = (function() { + + /** + * Properties of a MapValue. + * @memberof google.firestore.v1 + * @interface IMapValue + * @property {Object.|null} [fields] MapValue fields + */ + + /** + * Constructs a new MapValue. + * @memberof google.firestore.v1 + * @classdesc Represents a MapValue. + * @implements IMapValue + * @constructor + * @param {google.firestore.v1.IMapValue=} [properties] Properties to set + */ + function MapValue(properties) { + this.fields = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MapValue fields. + * @member {Object.} fields + * @memberof google.firestore.v1.MapValue + * @instance + */ + MapValue.prototype.fields = $util.emptyObject; + + /** + * Creates a MapValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.MapValue + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.MapValue} MapValue + */ + MapValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.MapValue) + return object; + var message = new $root.google.firestore.v1.MapValue(); + if (object.fields) { + if (typeof object.fields !== "object") + throw TypeError(".google.firestore.v1.MapValue.fields: object expected"); + message.fields = {}; + for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { + if (typeof object.fields[keys[i]] !== "object") + throw TypeError(".google.firestore.v1.MapValue.fields: object expected"); + message.fields[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.fields[keys[i]]); + } + } + return message; + }; + + /** + * Creates a plain object from a MapValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.MapValue + * @static + * @param {google.firestore.v1.MapValue} message MapValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MapValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.fields = {}; + var keys2; + if (message.fields && (keys2 = Object.keys(message.fields)).length) { + object.fields = {}; + for (var j = 0; j < keys2.length; ++j) + object.fields[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.fields[keys2[j]], options); + } + return object; + }; + + /** + * Converts this MapValue to JSON. + * @function toJSON + * @memberof google.firestore.v1.MapValue + * @instance + * @returns {Object.} JSON object + */ + MapValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MapValue + * @function getTypeUrl + * @memberof google.firestore.v1.MapValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MapValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.MapValue"; + }; + + return MapValue; + })(); + + v1.Function = (function() { + + /** + * Properties of a Function. + * @memberof google.firestore.v1 + * @interface IFunction + * @property {string|null} [name] Function name + * @property {Array.|null} [args] Function args + * @property {Object.|null} [options] Function options + */ + + /** + * Constructs a new Function. + * @memberof google.firestore.v1 + * @classdesc Represents a Function. + * @implements IFunction + * @constructor + * @param {google.firestore.v1.IFunction=} [properties] Properties to set + */ + function Function(properties) { + this.args = []; + this.options = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Function name. + * @member {string} name + * @memberof google.firestore.v1.Function + * @instance + */ + Function.prototype.name = ""; + + /** + * Function args. + * @member {Array.} args + * @memberof google.firestore.v1.Function + * @instance + */ + Function.prototype.args = $util.emptyArray; + + /** + * Function options. + * @member {Object.} options + * @memberof google.firestore.v1.Function + * @instance + */ + Function.prototype.options = $util.emptyObject; + + /** + * Creates a Function message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Function + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Function} Function + */ + Function.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Function) + return object; + var message = new $root.google.firestore.v1.Function(); + if (object.name != null) + message.name = String(object.name); + if (object.args) { + if (!Array.isArray(object.args)) + throw TypeError(".google.firestore.v1.Function.args: array expected"); + message.args = []; + for (var i = 0; i < object.args.length; ++i) { + if (typeof object.args[i] !== "object") + throw TypeError(".google.firestore.v1.Function.args: object expected"); + message.args[i] = $root.google.firestore.v1.Value.fromObject(object.args[i]); + } + } + if (object.options) { + if (typeof object.options !== "object") + throw TypeError(".google.firestore.v1.Function.options: object expected"); + message.options = {}; + for (var keys = Object.keys(object.options), i = 0; i < keys.length; ++i) { + if (typeof object.options[keys[i]] !== "object") + throw TypeError(".google.firestore.v1.Function.options: object expected"); + message.options[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.options[keys[i]]); + } + } + return message; + }; + + /** + * Creates a plain object from a Function message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Function + * @static + * @param {google.firestore.v1.Function} message Function + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Function.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.args = []; + if (options.objects || options.defaults) + object.options = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.args && message.args.length) { + object.args = []; + for (var j = 0; j < message.args.length; ++j) + object.args[j] = $root.google.firestore.v1.Value.toObject(message.args[j], options); + } + var keys2; + if (message.options && (keys2 = Object.keys(message.options)).length) { + object.options = {}; + for (var j = 0; j < keys2.length; ++j) + object.options[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.options[keys2[j]], options); + } + return object; + }; + + /** + * Converts this Function to JSON. + * @function toJSON + * @memberof google.firestore.v1.Function + * @instance + * @returns {Object.} JSON object + */ + Function.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Function + * @function getTypeUrl + * @memberof google.firestore.v1.Function + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Function.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Function"; + }; + + return Function; + })(); + + v1.Pipeline = (function() { + + /** + * Properties of a Pipeline. + * @memberof google.firestore.v1 + * @interface IPipeline + * @property {Array.|null} [stages] Pipeline stages + */ + + /** + * Constructs a new Pipeline. + * @memberof google.firestore.v1 + * @classdesc Represents a Pipeline. + * @implements IPipeline + * @constructor + * @param {google.firestore.v1.IPipeline=} [properties] Properties to set + */ + function Pipeline(properties) { + this.stages = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Pipeline stages. + * @member {Array.} stages + * @memberof google.firestore.v1.Pipeline + * @instance + */ + Pipeline.prototype.stages = $util.emptyArray; + + /** + * Creates a Pipeline message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Pipeline + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Pipeline} Pipeline + */ + Pipeline.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Pipeline) + return object; + var message = new $root.google.firestore.v1.Pipeline(); + if (object.stages) { + if (!Array.isArray(object.stages)) + throw TypeError(".google.firestore.v1.Pipeline.stages: array expected"); + message.stages = []; + for (var i = 0; i < object.stages.length; ++i) { + if (typeof object.stages[i] !== "object") + throw TypeError(".google.firestore.v1.Pipeline.stages: object expected"); + message.stages[i] = $root.google.firestore.v1.Pipeline.Stage.fromObject(object.stages[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a Pipeline message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Pipeline + * @static + * @param {google.firestore.v1.Pipeline} message Pipeline + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Pipeline.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.stages = []; + if (message.stages && message.stages.length) { + object.stages = []; + for (var j = 0; j < message.stages.length; ++j) + object.stages[j] = $root.google.firestore.v1.Pipeline.Stage.toObject(message.stages[j], options); + } + return object; + }; + + /** + * Converts this Pipeline to JSON. + * @function toJSON + * @memberof google.firestore.v1.Pipeline + * @instance + * @returns {Object.} JSON object + */ + Pipeline.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Pipeline + * @function getTypeUrl + * @memberof google.firestore.v1.Pipeline + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Pipeline.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Pipeline"; + }; + + Pipeline.Stage = (function() { + + /** + * Properties of a Stage. + * @memberof google.firestore.v1.Pipeline + * @interface IStage + * @property {string|null} [name] Stage name + * @property {Array.|null} [args] Stage args + * @property {Object.|null} [options] Stage options + */ + + /** + * Constructs a new Stage. + * @memberof google.firestore.v1.Pipeline + * @classdesc Represents a Stage. + * @implements IStage + * @constructor + * @param {google.firestore.v1.Pipeline.IStage=} [properties] Properties to set + */ + function Stage(properties) { + this.args = []; + this.options = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Stage name. + * @member {string} name + * @memberof google.firestore.v1.Pipeline.Stage + * @instance + */ + Stage.prototype.name = ""; + + /** + * Stage args. + * @member {Array.} args + * @memberof google.firestore.v1.Pipeline.Stage + * @instance + */ + Stage.prototype.args = $util.emptyArray; + + /** + * Stage options. + * @member {Object.} options + * @memberof google.firestore.v1.Pipeline.Stage + * @instance + */ + Stage.prototype.options = $util.emptyObject; + + /** + * Creates a Stage message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Pipeline.Stage + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Pipeline.Stage} Stage + */ + Stage.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Pipeline.Stage) + return object; + var message = new $root.google.firestore.v1.Pipeline.Stage(); + if (object.name != null) + message.name = String(object.name); + if (object.args) { + if (!Array.isArray(object.args)) + throw TypeError(".google.firestore.v1.Pipeline.Stage.args: array expected"); + message.args = []; + for (var i = 0; i < object.args.length; ++i) { + if (typeof object.args[i] !== "object") + throw TypeError(".google.firestore.v1.Pipeline.Stage.args: object expected"); + message.args[i] = $root.google.firestore.v1.Value.fromObject(object.args[i]); + } + } + if (object.options) { + if (typeof object.options !== "object") + throw TypeError(".google.firestore.v1.Pipeline.Stage.options: object expected"); + message.options = {}; + for (var keys = Object.keys(object.options), i = 0; i < keys.length; ++i) { + if (typeof object.options[keys[i]] !== "object") + throw TypeError(".google.firestore.v1.Pipeline.Stage.options: object expected"); + message.options[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.options[keys[i]]); + } + } + return message; + }; + + /** + * Creates a plain object from a Stage message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Pipeline.Stage + * @static + * @param {google.firestore.v1.Pipeline.Stage} message Stage + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Stage.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.args = []; + if (options.objects || options.defaults) + object.options = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.args && message.args.length) { + object.args = []; + for (var j = 0; j < message.args.length; ++j) + object.args[j] = $root.google.firestore.v1.Value.toObject(message.args[j], options); + } + var keys2; + if (message.options && (keys2 = Object.keys(message.options)).length) { + object.options = {}; + for (var j = 0; j < keys2.length; ++j) + object.options[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.options[keys2[j]], options); + } + return object; + }; + + /** + * Converts this Stage to JSON. + * @function toJSON + * @memberof google.firestore.v1.Pipeline.Stage + * @instance + * @returns {Object.} JSON object + */ + Stage.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Stage + * @function getTypeUrl + * @memberof google.firestore.v1.Pipeline.Stage + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Stage.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Pipeline.Stage"; + }; + + return Stage; + })(); + + return Pipeline; + })(); + + v1.BitSequence = (function() { + + /** + * Properties of a BitSequence. + * @memberof google.firestore.v1 + * @interface IBitSequence + * @property {Uint8Array|null} [bitmap] BitSequence bitmap + * @property {number|null} [padding] BitSequence padding + */ + + /** + * Constructs a new BitSequence. + * @memberof google.firestore.v1 + * @classdesc Represents a BitSequence. + * @implements IBitSequence + * @constructor + * @param {google.firestore.v1.IBitSequence=} [properties] Properties to set + */ + function BitSequence(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BitSequence bitmap. + * @member {Uint8Array} bitmap + * @memberof google.firestore.v1.BitSequence + * @instance + */ + BitSequence.prototype.bitmap = $util.newBuffer([]); + + /** + * BitSequence padding. + * @member {number} padding + * @memberof google.firestore.v1.BitSequence + * @instance + */ + BitSequence.prototype.padding = 0; + + /** + * Creates a BitSequence message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.BitSequence + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.BitSequence} BitSequence + */ + BitSequence.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.BitSequence) + return object; + var message = new $root.google.firestore.v1.BitSequence(); + if (object.bitmap != null) + if (typeof object.bitmap === "string") + $util.base64.decode(object.bitmap, message.bitmap = $util.newBuffer($util.base64.length(object.bitmap)), 0); + else if (object.bitmap.length >= 0) + message.bitmap = object.bitmap; + if (object.padding != null) + message.padding = object.padding | 0; + return message; + }; + + /** + * Creates a plain object from a BitSequence message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.BitSequence + * @static + * @param {google.firestore.v1.BitSequence} message BitSequence + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BitSequence.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if (options.bytes === String) + object.bitmap = ""; + else { + object.bitmap = []; + if (options.bytes !== Array) + object.bitmap = $util.newBuffer(object.bitmap); + } + object.padding = 0; + } + if (message.bitmap != null && message.hasOwnProperty("bitmap")) + object.bitmap = options.bytes === String ? $util.base64.encode(message.bitmap, 0, message.bitmap.length) : options.bytes === Array ? Array.prototype.slice.call(message.bitmap) : message.bitmap; + if (message.padding != null && message.hasOwnProperty("padding")) + object.padding = message.padding; + return object; + }; + + /** + * Converts this BitSequence to JSON. + * @function toJSON + * @memberof google.firestore.v1.BitSequence + * @instance + * @returns {Object.} JSON object + */ + BitSequence.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BitSequence + * @function getTypeUrl + * @memberof google.firestore.v1.BitSequence + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BitSequence.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.BitSequence"; + }; + + return BitSequence; + })(); + + v1.BloomFilter = (function() { + + /** + * Properties of a BloomFilter. + * @memberof google.firestore.v1 + * @interface IBloomFilter + * @property {google.firestore.v1.IBitSequence|null} [bits] BloomFilter bits + * @property {number|null} [hashCount] BloomFilter hashCount + */ + + /** + * Constructs a new BloomFilter. + * @memberof google.firestore.v1 + * @classdesc Represents a BloomFilter. + * @implements IBloomFilter + * @constructor + * @param {google.firestore.v1.IBloomFilter=} [properties] Properties to set + */ + function BloomFilter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BloomFilter bits. + * @member {google.firestore.v1.IBitSequence|null|undefined} bits + * @memberof google.firestore.v1.BloomFilter + * @instance + */ + BloomFilter.prototype.bits = null; + + /** + * BloomFilter hashCount. + * @member {number} hashCount + * @memberof google.firestore.v1.BloomFilter + * @instance + */ + BloomFilter.prototype.hashCount = 0; + + /** + * Creates a BloomFilter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.BloomFilter + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.BloomFilter} BloomFilter + */ + BloomFilter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.BloomFilter) + return object; + var message = new $root.google.firestore.v1.BloomFilter(); + if (object.bits != null) { + if (typeof object.bits !== "object") + throw TypeError(".google.firestore.v1.BloomFilter.bits: object expected"); + message.bits = $root.google.firestore.v1.BitSequence.fromObject(object.bits); + } + if (object.hashCount != null) + message.hashCount = object.hashCount | 0; + return message; + }; + + /** + * Creates a plain object from a BloomFilter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.BloomFilter + * @static + * @param {google.firestore.v1.BloomFilter} message BloomFilter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BloomFilter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.bits = null; + object.hashCount = 0; + } + if (message.bits != null && message.hasOwnProperty("bits")) + object.bits = $root.google.firestore.v1.BitSequence.toObject(message.bits, options); + if (message.hashCount != null && message.hasOwnProperty("hashCount")) + object.hashCount = message.hashCount; + return object; + }; + + /** + * Converts this BloomFilter to JSON. + * @function toJSON + * @memberof google.firestore.v1.BloomFilter + * @instance + * @returns {Object.} JSON object + */ + BloomFilter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BloomFilter + * @function getTypeUrl + * @memberof google.firestore.v1.BloomFilter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BloomFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.BloomFilter"; + }; + + return BloomFilter; + })(); + + v1.DocumentMask = (function() { + + /** + * Properties of a DocumentMask. + * @memberof google.firestore.v1 + * @interface IDocumentMask + * @property {Array.|null} [fieldPaths] DocumentMask fieldPaths + */ + + /** + * Constructs a new DocumentMask. + * @memberof google.firestore.v1 + * @classdesc Represents a DocumentMask. + * @implements IDocumentMask + * @constructor + * @param {google.firestore.v1.IDocumentMask=} [properties] Properties to set + */ + function DocumentMask(properties) { + this.fieldPaths = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DocumentMask fieldPaths. + * @member {Array.} fieldPaths + * @memberof google.firestore.v1.DocumentMask + * @instance + */ + DocumentMask.prototype.fieldPaths = $util.emptyArray; + + /** + * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.DocumentMask + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.DocumentMask} DocumentMask + */ + DocumentMask.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.DocumentMask) + return object; + var message = new $root.google.firestore.v1.DocumentMask(); + if (object.fieldPaths) { + if (!Array.isArray(object.fieldPaths)) + throw TypeError(".google.firestore.v1.DocumentMask.fieldPaths: array expected"); + message.fieldPaths = []; + for (var i = 0; i < object.fieldPaths.length; ++i) + message.fieldPaths[i] = String(object.fieldPaths[i]); + } + return message; + }; + + /** + * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.DocumentMask + * @static + * @param {google.firestore.v1.DocumentMask} message DocumentMask + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DocumentMask.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.fieldPaths = []; + if (message.fieldPaths && message.fieldPaths.length) { + object.fieldPaths = []; + for (var j = 0; j < message.fieldPaths.length; ++j) + object.fieldPaths[j] = message.fieldPaths[j]; + } + return object; + }; + + /** + * Converts this DocumentMask to JSON. + * @function toJSON + * @memberof google.firestore.v1.DocumentMask + * @instance + * @returns {Object.} JSON object + */ + DocumentMask.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DocumentMask + * @function getTypeUrl + * @memberof google.firestore.v1.DocumentMask + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DocumentMask.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.DocumentMask"; + }; + + return DocumentMask; + })(); + + v1.Precondition = (function() { + + /** + * Properties of a Precondition. + * @memberof google.firestore.v1 + * @interface IPrecondition + * @property {boolean|null} [exists] Precondition exists + * @property {google.protobuf.ITimestamp|null} [updateTime] Precondition updateTime + */ + + /** + * Constructs a new Precondition. + * @memberof google.firestore.v1 + * @classdesc Represents a Precondition. + * @implements IPrecondition + * @constructor + * @param {google.firestore.v1.IPrecondition=} [properties] Properties to set + */ + function Precondition(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Precondition exists. + * @member {boolean|null|undefined} exists + * @memberof google.firestore.v1.Precondition + * @instance + */ + Precondition.prototype.exists = null; + + /** + * Precondition updateTime. + * @member {google.protobuf.ITimestamp|null|undefined} updateTime + * @memberof google.firestore.v1.Precondition + * @instance + */ + Precondition.prototype.updateTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Precondition conditionType. + * @member {"exists"|"updateTime"|undefined} conditionType + * @memberof google.firestore.v1.Precondition + * @instance + */ + Object.defineProperty(Precondition.prototype, "conditionType", { + get: $util.oneOfGetter($oneOfFields = ["exists", "updateTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a Precondition message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Precondition + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Precondition} Precondition + */ + Precondition.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Precondition) + return object; + var message = new $root.google.firestore.v1.Precondition(); + if (object.exists != null) + message.exists = Boolean(object.exists); + if (object.updateTime != null) { + if (typeof object.updateTime !== "object") + throw TypeError(".google.firestore.v1.Precondition.updateTime: object expected"); + message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + } + return message; + }; + + /** + * Creates a plain object from a Precondition message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Precondition + * @static + * @param {google.firestore.v1.Precondition} message Precondition + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Precondition.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.exists != null && message.hasOwnProperty("exists")) { + object.exists = message.exists; + if (options.oneofs) + object.conditionType = "exists"; + } + if (message.updateTime != null && message.hasOwnProperty("updateTime")) { + object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + if (options.oneofs) + object.conditionType = "updateTime"; + } + return object; + }; + + /** + * Converts this Precondition to JSON. + * @function toJSON + * @memberof google.firestore.v1.Precondition + * @instance + * @returns {Object.} JSON object + */ + Precondition.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Precondition + * @function getTypeUrl + * @memberof google.firestore.v1.Precondition + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Precondition.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Precondition"; + }; + + return Precondition; + })(); + + v1.TransactionOptions = (function() { + + /** + * Properties of a TransactionOptions. + * @memberof google.firestore.v1 + * @interface ITransactionOptions + * @property {google.firestore.v1.TransactionOptions.IReadOnly|null} [readOnly] TransactionOptions readOnly + * @property {google.firestore.v1.TransactionOptions.IReadWrite|null} [readWrite] TransactionOptions readWrite + */ + + /** + * Constructs a new TransactionOptions. + * @memberof google.firestore.v1 + * @classdesc Represents a TransactionOptions. + * @implements ITransactionOptions + * @constructor + * @param {google.firestore.v1.ITransactionOptions=} [properties] Properties to set + */ + function TransactionOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TransactionOptions readOnly. + * @member {google.firestore.v1.TransactionOptions.IReadOnly|null|undefined} readOnly + * @memberof google.firestore.v1.TransactionOptions + * @instance + */ + TransactionOptions.prototype.readOnly = null; + + /** + * TransactionOptions readWrite. + * @member {google.firestore.v1.TransactionOptions.IReadWrite|null|undefined} readWrite + * @memberof google.firestore.v1.TransactionOptions + * @instance + */ + TransactionOptions.prototype.readWrite = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * TransactionOptions mode. + * @member {"readOnly"|"readWrite"|undefined} mode + * @memberof google.firestore.v1.TransactionOptions + * @instance + */ + Object.defineProperty(TransactionOptions.prototype, "mode", { + get: $util.oneOfGetter($oneOfFields = ["readOnly", "readWrite"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.TransactionOptions + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.TransactionOptions} TransactionOptions + */ + TransactionOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.TransactionOptions) + return object; + var message = new $root.google.firestore.v1.TransactionOptions(); + if (object.readOnly != null) { + if (typeof object.readOnly !== "object") + throw TypeError(".google.firestore.v1.TransactionOptions.readOnly: object expected"); + message.readOnly = $root.google.firestore.v1.TransactionOptions.ReadOnly.fromObject(object.readOnly); + } + if (object.readWrite != null) { + if (typeof object.readWrite !== "object") + throw TypeError(".google.firestore.v1.TransactionOptions.readWrite: object expected"); + message.readWrite = $root.google.firestore.v1.TransactionOptions.ReadWrite.fromObject(object.readWrite); + } + return message; + }; + + /** + * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.TransactionOptions + * @static + * @param {google.firestore.v1.TransactionOptions} message TransactionOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TransactionOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.readOnly != null && message.hasOwnProperty("readOnly")) { + object.readOnly = $root.google.firestore.v1.TransactionOptions.ReadOnly.toObject(message.readOnly, options); + if (options.oneofs) + object.mode = "readOnly"; + } + if (message.readWrite != null && message.hasOwnProperty("readWrite")) { + object.readWrite = $root.google.firestore.v1.TransactionOptions.ReadWrite.toObject(message.readWrite, options); + if (options.oneofs) + object.mode = "readWrite"; + } + return object; + }; + + /** + * Converts this TransactionOptions to JSON. + * @function toJSON + * @memberof google.firestore.v1.TransactionOptions + * @instance + * @returns {Object.} JSON object + */ + TransactionOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TransactionOptions + * @function getTypeUrl + * @memberof google.firestore.v1.TransactionOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TransactionOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.TransactionOptions"; + }; + + TransactionOptions.ReadWrite = (function() { + + /** + * Properties of a ReadWrite. + * @memberof google.firestore.v1.TransactionOptions + * @interface IReadWrite + * @property {Uint8Array|null} [retryTransaction] ReadWrite retryTransaction + */ + + /** + * Constructs a new ReadWrite. + * @memberof google.firestore.v1.TransactionOptions + * @classdesc Represents a ReadWrite. + * @implements IReadWrite + * @constructor + * @param {google.firestore.v1.TransactionOptions.IReadWrite=} [properties] Properties to set + */ + function ReadWrite(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReadWrite retryTransaction. + * @member {Uint8Array} retryTransaction + * @memberof google.firestore.v1.TransactionOptions.ReadWrite + * @instance + */ + ReadWrite.prototype.retryTransaction = $util.newBuffer([]); + + /** + * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.TransactionOptions.ReadWrite + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.TransactionOptions.ReadWrite} ReadWrite + */ + ReadWrite.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.TransactionOptions.ReadWrite) + return object; + var message = new $root.google.firestore.v1.TransactionOptions.ReadWrite(); + if (object.retryTransaction != null) + if (typeof object.retryTransaction === "string") + $util.base64.decode(object.retryTransaction, message.retryTransaction = $util.newBuffer($util.base64.length(object.retryTransaction)), 0); + else if (object.retryTransaction.length >= 0) + message.retryTransaction = object.retryTransaction; + return message; + }; + + /** + * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.TransactionOptions.ReadWrite + * @static + * @param {google.firestore.v1.TransactionOptions.ReadWrite} message ReadWrite + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReadWrite.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if (options.bytes === String) + object.retryTransaction = ""; + else { + object.retryTransaction = []; + if (options.bytes !== Array) + object.retryTransaction = $util.newBuffer(object.retryTransaction); + } + if (message.retryTransaction != null && message.hasOwnProperty("retryTransaction")) + object.retryTransaction = options.bytes === String ? $util.base64.encode(message.retryTransaction, 0, message.retryTransaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.retryTransaction) : message.retryTransaction; + return object; + }; + + /** + * Converts this ReadWrite to JSON. + * @function toJSON + * @memberof google.firestore.v1.TransactionOptions.ReadWrite + * @instance + * @returns {Object.} JSON object + */ + ReadWrite.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReadWrite + * @function getTypeUrl + * @memberof google.firestore.v1.TransactionOptions.ReadWrite + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReadWrite.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.TransactionOptions.ReadWrite"; + }; + + return ReadWrite; + })(); + + TransactionOptions.ReadOnly = (function() { + + /** + * Properties of a ReadOnly. + * @memberof google.firestore.v1.TransactionOptions + * @interface IReadOnly + * @property {google.protobuf.ITimestamp|null} [readTime] ReadOnly readTime + */ + + /** + * Constructs a new ReadOnly. + * @memberof google.firestore.v1.TransactionOptions + * @classdesc Represents a ReadOnly. + * @implements IReadOnly + * @constructor + * @param {google.firestore.v1.TransactionOptions.IReadOnly=} [properties] Properties to set + */ + function ReadOnly(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReadOnly readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.TransactionOptions.ReadOnly + * @instance + */ + ReadOnly.prototype.readTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ReadOnly consistencySelector. + * @member {"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.TransactionOptions.ReadOnly + * @instance + */ + Object.defineProperty(ReadOnly.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.TransactionOptions.ReadOnly + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.TransactionOptions.ReadOnly} ReadOnly + */ + ReadOnly.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.TransactionOptions.ReadOnly) + return object; + var message = new $root.google.firestore.v1.TransactionOptions.ReadOnly(); + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.TransactionOptions.ReadOnly.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.TransactionOptions.ReadOnly + * @static + * @param {google.firestore.v1.TransactionOptions.ReadOnly} message ReadOnly + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReadOnly.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + return object; + }; + + /** + * Converts this ReadOnly to JSON. + * @function toJSON + * @memberof google.firestore.v1.TransactionOptions.ReadOnly + * @instance + * @returns {Object.} JSON object + */ + ReadOnly.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReadOnly + * @function getTypeUrl + * @memberof google.firestore.v1.TransactionOptions.ReadOnly + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReadOnly.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.TransactionOptions.ReadOnly"; + }; + + return ReadOnly; + })(); + + return TransactionOptions; + })(); + + v1.ExplainStats = (function() { + + /** + * Properties of an ExplainStats. + * @memberof google.firestore.v1 + * @interface IExplainStats + * @property {google.protobuf.IAny|null} [data] ExplainStats data + */ + + /** + * Constructs a new ExplainStats. + * @memberof google.firestore.v1 + * @classdesc Represents an ExplainStats. + * @implements IExplainStats + * @constructor + * @param {google.firestore.v1.IExplainStats=} [properties] Properties to set + */ + function ExplainStats(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExplainStats data. + * @member {google.protobuf.IAny|null|undefined} data + * @memberof google.firestore.v1.ExplainStats + * @instance + */ + ExplainStats.prototype.data = null; + + /** + * Creates an ExplainStats message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ExplainStats + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ExplainStats} ExplainStats + */ + ExplainStats.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ExplainStats) + return object; + var message = new $root.google.firestore.v1.ExplainStats(); + if (object.data != null) { + if (typeof object.data !== "object") + throw TypeError(".google.firestore.v1.ExplainStats.data: object expected"); + message.data = $root.google.protobuf.Any.fromObject(object.data); + } + return message; + }; + + /** + * Creates a plain object from an ExplainStats message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ExplainStats + * @static + * @param {google.firestore.v1.ExplainStats} message ExplainStats + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExplainStats.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.data = null; + if (message.data != null && message.hasOwnProperty("data")) + object.data = $root.google.protobuf.Any.toObject(message.data, options); + return object; + }; + + /** + * Converts this ExplainStats to JSON. + * @function toJSON + * @memberof google.firestore.v1.ExplainStats + * @instance + * @returns {Object.} JSON object + */ + ExplainStats.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExplainStats + * @function getTypeUrl + * @memberof google.firestore.v1.ExplainStats + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExplainStats.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ExplainStats"; + }; + + return ExplainStats; + })(); + + v1.Firestore = (function() { + + /** + * Constructs a new Firestore service. + * @memberof google.firestore.v1 + * @classdesc Represents a Firestore + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function Firestore(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (Firestore.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = Firestore; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#getDocument}. + * @memberof google.firestore.v1.Firestore + * @typedef GetDocumentCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.Document} [response] Document + */ + + /** + * Calls GetDocument. + * @function getDocument + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IGetDocumentRequest} request GetDocumentRequest message or plain object + * @param {google.firestore.v1.Firestore.GetDocumentCallback} callback Node-style callback called with the error, if any, and Document + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.getDocument = function getDocument(request, callback) { + return this.rpcCall(getDocument, $root.google.firestore.v1.GetDocumentRequest, $root.google.firestore.v1.Document, request, callback); + }, "name", { value: "GetDocument" }); + + /** + * Calls GetDocument. + * @function getDocument + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IGetDocumentRequest} request GetDocumentRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listDocuments}. + * @memberof google.firestore.v1.Firestore + * @typedef ListDocumentsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.ListDocumentsResponse} [response] ListDocumentsResponse + */ + + /** + * Calls ListDocuments. + * @function listDocuments + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IListDocumentsRequest} request ListDocumentsRequest message or plain object + * @param {google.firestore.v1.Firestore.ListDocumentsCallback} callback Node-style callback called with the error, if any, and ListDocumentsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.listDocuments = function listDocuments(request, callback) { + return this.rpcCall(listDocuments, $root.google.firestore.v1.ListDocumentsRequest, $root.google.firestore.v1.ListDocumentsResponse, request, callback); + }, "name", { value: "ListDocuments" }); + + /** + * Calls ListDocuments. + * @function listDocuments + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IListDocumentsRequest} request ListDocumentsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#updateDocument}. + * @memberof google.firestore.v1.Firestore + * @typedef UpdateDocumentCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.Document} [response] Document + */ + + /** + * Calls UpdateDocument. + * @function updateDocument + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IUpdateDocumentRequest} request UpdateDocumentRequest message or plain object + * @param {google.firestore.v1.Firestore.UpdateDocumentCallback} callback Node-style callback called with the error, if any, and Document + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.updateDocument = function updateDocument(request, callback) { + return this.rpcCall(updateDocument, $root.google.firestore.v1.UpdateDocumentRequest, $root.google.firestore.v1.Document, request, callback); + }, "name", { value: "UpdateDocument" }); + + /** + * Calls UpdateDocument. + * @function updateDocument + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IUpdateDocumentRequest} request UpdateDocumentRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#deleteDocument}. + * @memberof google.firestore.v1.Firestore + * @typedef DeleteDocumentCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteDocument. + * @function deleteDocument + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IDeleteDocumentRequest} request DeleteDocumentRequest message or plain object + * @param {google.firestore.v1.Firestore.DeleteDocumentCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.deleteDocument = function deleteDocument(request, callback) { + return this.rpcCall(deleteDocument, $root.google.firestore.v1.DeleteDocumentRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteDocument" }); + + /** + * Calls DeleteDocument. + * @function deleteDocument + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IDeleteDocumentRequest} request DeleteDocumentRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#batchGetDocuments}. + * @memberof google.firestore.v1.Firestore + * @typedef BatchGetDocumentsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.BatchGetDocumentsResponse} [response] BatchGetDocumentsResponse + */ + + /** + * Calls BatchGetDocuments. + * @function batchGetDocuments + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IBatchGetDocumentsRequest} request BatchGetDocumentsRequest message or plain object + * @param {google.firestore.v1.Firestore.BatchGetDocumentsCallback} callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.batchGetDocuments = function batchGetDocuments(request, callback) { + return this.rpcCall(batchGetDocuments, $root.google.firestore.v1.BatchGetDocumentsRequest, $root.google.firestore.v1.BatchGetDocumentsResponse, request, callback); + }, "name", { value: "BatchGetDocuments" }); + + /** + * Calls BatchGetDocuments. + * @function batchGetDocuments + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IBatchGetDocumentsRequest} request BatchGetDocumentsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#beginTransaction}. + * @memberof google.firestore.v1.Firestore + * @typedef BeginTransactionCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.BeginTransactionResponse} [response] BeginTransactionResponse + */ + + /** + * Calls BeginTransaction. + * @function beginTransaction + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IBeginTransactionRequest} request BeginTransactionRequest message or plain object + * @param {google.firestore.v1.Firestore.BeginTransactionCallback} callback Node-style callback called with the error, if any, and BeginTransactionResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.beginTransaction = function beginTransaction(request, callback) { + return this.rpcCall(beginTransaction, $root.google.firestore.v1.BeginTransactionRequest, $root.google.firestore.v1.BeginTransactionResponse, request, callback); + }, "name", { value: "BeginTransaction" }); + + /** + * Calls BeginTransaction. + * @function beginTransaction + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IBeginTransactionRequest} request BeginTransactionRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#commit}. + * @memberof google.firestore.v1.Firestore + * @typedef CommitCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.CommitResponse} [response] CommitResponse + */ + + /** + * Calls Commit. + * @function commit + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.ICommitRequest} request CommitRequest message or plain object + * @param {google.firestore.v1.Firestore.CommitCallback} callback Node-style callback called with the error, if any, and CommitResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.commit = function commit(request, callback) { + return this.rpcCall(commit, $root.google.firestore.v1.CommitRequest, $root.google.firestore.v1.CommitResponse, request, callback); + }, "name", { value: "Commit" }); + + /** + * Calls Commit. + * @function commit + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.ICommitRequest} request CommitRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#rollback}. + * @memberof google.firestore.v1.Firestore + * @typedef RollbackCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls Rollback. + * @function rollback + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IRollbackRequest} request RollbackRequest message or plain object + * @param {google.firestore.v1.Firestore.RollbackCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.rollback = function rollback(request, callback) { + return this.rpcCall(rollback, $root.google.firestore.v1.RollbackRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "Rollback" }); + + /** + * Calls Rollback. + * @function rollback + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IRollbackRequest} request RollbackRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#runQuery}. + * @memberof google.firestore.v1.Firestore + * @typedef RunQueryCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.RunQueryResponse} [response] RunQueryResponse + */ + + /** + * Calls RunQuery. + * @function runQuery + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IRunQueryRequest} request RunQueryRequest message or plain object + * @param {google.firestore.v1.Firestore.RunQueryCallback} callback Node-style callback called with the error, if any, and RunQueryResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.runQuery = function runQuery(request, callback) { + return this.rpcCall(runQuery, $root.google.firestore.v1.RunQueryRequest, $root.google.firestore.v1.RunQueryResponse, request, callback); + }, "name", { value: "RunQuery" }); + + /** + * Calls RunQuery. + * @function runQuery + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IRunQueryRequest} request RunQueryRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#executePipeline}. + * @memberof google.firestore.v1.Firestore + * @typedef ExecutePipelineCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.ExecutePipelineResponse} [response] ExecutePipelineResponse + */ + + /** + * Calls ExecutePipeline. + * @function executePipeline + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IExecutePipelineRequest} request ExecutePipelineRequest message or plain object + * @param {google.firestore.v1.Firestore.ExecutePipelineCallback} callback Node-style callback called with the error, if any, and ExecutePipelineResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.executePipeline = function executePipeline(request, callback) { + return this.rpcCall(executePipeline, $root.google.firestore.v1.ExecutePipelineRequest, $root.google.firestore.v1.ExecutePipelineResponse, request, callback); + }, "name", { value: "ExecutePipeline" }); + + /** + * Calls ExecutePipeline. + * @function executePipeline + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IExecutePipelineRequest} request ExecutePipelineRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#runAggregationQuery}. + * @memberof google.firestore.v1.Firestore + * @typedef RunAggregationQueryCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.RunAggregationQueryResponse} [response] RunAggregationQueryResponse + */ + + /** + * Calls RunAggregationQuery. + * @function runAggregationQuery + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IRunAggregationQueryRequest} request RunAggregationQueryRequest message or plain object + * @param {google.firestore.v1.Firestore.RunAggregationQueryCallback} callback Node-style callback called with the error, if any, and RunAggregationQueryResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.runAggregationQuery = function runAggregationQuery(request, callback) { + return this.rpcCall(runAggregationQuery, $root.google.firestore.v1.RunAggregationQueryRequest, $root.google.firestore.v1.RunAggregationQueryResponse, request, callback); + }, "name", { value: "RunAggregationQuery" }); + + /** + * Calls RunAggregationQuery. + * @function runAggregationQuery + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IRunAggregationQueryRequest} request RunAggregationQueryRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#partitionQuery}. + * @memberof google.firestore.v1.Firestore + * @typedef PartitionQueryCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.PartitionQueryResponse} [response] PartitionQueryResponse + */ + + /** + * Calls PartitionQuery. + * @function partitionQuery + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IPartitionQueryRequest} request PartitionQueryRequest message or plain object + * @param {google.firestore.v1.Firestore.PartitionQueryCallback} callback Node-style callback called with the error, if any, and PartitionQueryResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.partitionQuery = function partitionQuery(request, callback) { + return this.rpcCall(partitionQuery, $root.google.firestore.v1.PartitionQueryRequest, $root.google.firestore.v1.PartitionQueryResponse, request, callback); + }, "name", { value: "PartitionQuery" }); + + /** + * Calls PartitionQuery. + * @function partitionQuery + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IPartitionQueryRequest} request PartitionQueryRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#write}. + * @memberof google.firestore.v1.Firestore + * @typedef WriteCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.WriteResponse} [response] WriteResponse + */ + + /** + * Calls Write. + * @function write + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IWriteRequest} request WriteRequest message or plain object + * @param {google.firestore.v1.Firestore.WriteCallback} callback Node-style callback called with the error, if any, and WriteResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.write = function write(request, callback) { + return this.rpcCall(write, $root.google.firestore.v1.WriteRequest, $root.google.firestore.v1.WriteResponse, request, callback); + }, "name", { value: "Write" }); + + /** + * Calls Write. + * @function write + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IWriteRequest} request WriteRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listen}. + * @memberof google.firestore.v1.Firestore + * @typedef ListenCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.ListenResponse} [response] ListenResponse + */ + + /** + * Calls Listen. + * @function listen + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IListenRequest} request ListenRequest message or plain object + * @param {google.firestore.v1.Firestore.ListenCallback} callback Node-style callback called with the error, if any, and ListenResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.listen = function listen(request, callback) { + return this.rpcCall(listen, $root.google.firestore.v1.ListenRequest, $root.google.firestore.v1.ListenResponse, request, callback); + }, "name", { value: "Listen" }); + + /** + * Calls Listen. + * @function listen + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IListenRequest} request ListenRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listCollectionIds}. + * @memberof google.firestore.v1.Firestore + * @typedef ListCollectionIdsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.ListCollectionIdsResponse} [response] ListCollectionIdsResponse + */ + + /** + * Calls ListCollectionIds. + * @function listCollectionIds + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IListCollectionIdsRequest} request ListCollectionIdsRequest message or plain object + * @param {google.firestore.v1.Firestore.ListCollectionIdsCallback} callback Node-style callback called with the error, if any, and ListCollectionIdsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.listCollectionIds = function listCollectionIds(request, callback) { + return this.rpcCall(listCollectionIds, $root.google.firestore.v1.ListCollectionIdsRequest, $root.google.firestore.v1.ListCollectionIdsResponse, request, callback); + }, "name", { value: "ListCollectionIds" }); + + /** + * Calls ListCollectionIds. + * @function listCollectionIds + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IListCollectionIdsRequest} request ListCollectionIdsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#batchWrite}. + * @memberof google.firestore.v1.Firestore + * @typedef BatchWriteCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.BatchWriteResponse} [response] BatchWriteResponse + */ + + /** + * Calls BatchWrite. + * @function batchWrite + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IBatchWriteRequest} request BatchWriteRequest message or plain object + * @param {google.firestore.v1.Firestore.BatchWriteCallback} callback Node-style callback called with the error, if any, and BatchWriteResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.batchWrite = function batchWrite(request, callback) { + return this.rpcCall(batchWrite, $root.google.firestore.v1.BatchWriteRequest, $root.google.firestore.v1.BatchWriteResponse, request, callback); + }, "name", { value: "BatchWrite" }); + + /** + * Calls BatchWrite. + * @function batchWrite + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IBatchWriteRequest} request BatchWriteRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#createDocument}. + * @memberof google.firestore.v1.Firestore + * @typedef CreateDocumentCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.Document} [response] Document + */ + + /** + * Calls CreateDocument. + * @function createDocument + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.ICreateDocumentRequest} request CreateDocumentRequest message or plain object + * @param {google.firestore.v1.Firestore.CreateDocumentCallback} callback Node-style callback called with the error, if any, and Document + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.createDocument = function createDocument(request, callback) { + return this.rpcCall(createDocument, $root.google.firestore.v1.CreateDocumentRequest, $root.google.firestore.v1.Document, request, callback); + }, "name", { value: "CreateDocument" }); + + /** + * Calls CreateDocument. + * @function createDocument + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.ICreateDocumentRequest} request CreateDocumentRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return Firestore; + })(); + + v1.GetDocumentRequest = (function() { + + /** + * Properties of a GetDocumentRequest. + * @memberof google.firestore.v1 + * @interface IGetDocumentRequest + * @property {string|null} [name] GetDocumentRequest name + * @property {google.firestore.v1.IDocumentMask|null} [mask] GetDocumentRequest mask + * @property {Uint8Array|null} [transaction] GetDocumentRequest transaction + * @property {google.protobuf.ITimestamp|null} [readTime] GetDocumentRequest readTime + */ + + /** + * Constructs a new GetDocumentRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a GetDocumentRequest. + * @implements IGetDocumentRequest + * @constructor + * @param {google.firestore.v1.IGetDocumentRequest=} [properties] Properties to set + */ + function GetDocumentRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetDocumentRequest name. + * @member {string} name + * @memberof google.firestore.v1.GetDocumentRequest + * @instance + */ + GetDocumentRequest.prototype.name = ""; + + /** + * GetDocumentRequest mask. + * @member {google.firestore.v1.IDocumentMask|null|undefined} mask + * @memberof google.firestore.v1.GetDocumentRequest + * @instance + */ + GetDocumentRequest.prototype.mask = null; + + /** + * GetDocumentRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1.GetDocumentRequest + * @instance + */ + GetDocumentRequest.prototype.transaction = null; + + /** + * GetDocumentRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.GetDocumentRequest + * @instance + */ + GetDocumentRequest.prototype.readTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * GetDocumentRequest consistencySelector. + * @member {"transaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.GetDocumentRequest + * @instance + */ + Object.defineProperty(GetDocumentRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.GetDocumentRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.GetDocumentRequest} GetDocumentRequest + */ + GetDocumentRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.GetDocumentRequest) + return object; + var message = new $root.google.firestore.v1.GetDocumentRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.mask != null) { + if (typeof object.mask !== "object") + throw TypeError(".google.firestore.v1.GetDocumentRequest.mask: object expected"); + message.mask = $root.google.firestore.v1.DocumentMask.fromObject(object.mask); + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.GetDocumentRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.GetDocumentRequest + * @static + * @param {google.firestore.v1.GetDocumentRequest} message GetDocumentRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetDocumentRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.mask = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.mask != null && message.hasOwnProperty("mask")) + object.mask = $root.google.firestore.v1.DocumentMask.toObject(message.mask, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + return object; + }; + + /** + * Converts this GetDocumentRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.GetDocumentRequest + * @instance + * @returns {Object.} JSON object + */ + GetDocumentRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetDocumentRequest + * @function getTypeUrl + * @memberof google.firestore.v1.GetDocumentRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetDocumentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.GetDocumentRequest"; + }; + + return GetDocumentRequest; + })(); + + v1.ListDocumentsRequest = (function() { + + /** + * Properties of a ListDocumentsRequest. + * @memberof google.firestore.v1 + * @interface IListDocumentsRequest + * @property {string|null} [parent] ListDocumentsRequest parent + * @property {string|null} [collectionId] ListDocumentsRequest collectionId + * @property {number|null} [pageSize] ListDocumentsRequest pageSize + * @property {string|null} [pageToken] ListDocumentsRequest pageToken + * @property {string|null} [orderBy] ListDocumentsRequest orderBy + * @property {google.firestore.v1.IDocumentMask|null} [mask] ListDocumentsRequest mask + * @property {Uint8Array|null} [transaction] ListDocumentsRequest transaction + * @property {google.protobuf.ITimestamp|null} [readTime] ListDocumentsRequest readTime + * @property {boolean|null} [showMissing] ListDocumentsRequest showMissing + */ + + /** + * Constructs a new ListDocumentsRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a ListDocumentsRequest. + * @implements IListDocumentsRequest + * @constructor + * @param {google.firestore.v1.IListDocumentsRequest=} [properties] Properties to set + */ + function ListDocumentsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListDocumentsRequest parent. + * @member {string} parent + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.parent = ""; + + /** + * ListDocumentsRequest collectionId. + * @member {string} collectionId + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.collectionId = ""; + + /** + * ListDocumentsRequest pageSize. + * @member {number} pageSize + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.pageSize = 0; + + /** + * ListDocumentsRequest pageToken. + * @member {string} pageToken + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.pageToken = ""; + + /** + * ListDocumentsRequest orderBy. + * @member {string} orderBy + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.orderBy = ""; + + /** + * ListDocumentsRequest mask. + * @member {google.firestore.v1.IDocumentMask|null|undefined} mask + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.mask = null; + + /** + * ListDocumentsRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.transaction = null; + + /** + * ListDocumentsRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.readTime = null; + + /** + * ListDocumentsRequest showMissing. + * @member {boolean} showMissing + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.showMissing = false; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ListDocumentsRequest consistencySelector. + * @member {"transaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + Object.defineProperty(ListDocumentsRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ListDocumentsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ListDocumentsRequest} ListDocumentsRequest + */ + ListDocumentsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ListDocumentsRequest) + return object; + var message = new $root.google.firestore.v1.ListDocumentsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.collectionId != null) + message.collectionId = String(object.collectionId); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.orderBy != null) + message.orderBy = String(object.orderBy); + if (object.mask != null) { + if (typeof object.mask !== "object") + throw TypeError(".google.firestore.v1.ListDocumentsRequest.mask: object expected"); + message.mask = $root.google.firestore.v1.DocumentMask.fromObject(object.mask); + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.ListDocumentsRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.showMissing != null) + message.showMissing = Boolean(object.showMissing); + return message; + }; + + /** + * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ListDocumentsRequest + * @static + * @param {google.firestore.v1.ListDocumentsRequest} message ListDocumentsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListDocumentsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.collectionId = ""; + object.pageSize = 0; + object.pageToken = ""; + object.orderBy = ""; + object.mask = null; + object.showMissing = false; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.collectionId != null && message.hasOwnProperty("collectionId")) + object.collectionId = message.collectionId; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.orderBy != null && message.hasOwnProperty("orderBy")) + object.orderBy = message.orderBy; + if (message.mask != null && message.hasOwnProperty("mask")) + object.mask = $root.google.firestore.v1.DocumentMask.toObject(message.mask, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + if (message.showMissing != null && message.hasOwnProperty("showMissing")) + object.showMissing = message.showMissing; + return object; + }; + + /** + * Converts this ListDocumentsRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + * @returns {Object.} JSON object + */ + ListDocumentsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListDocumentsRequest + * @function getTypeUrl + * @memberof google.firestore.v1.ListDocumentsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListDocumentsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ListDocumentsRequest"; + }; + + return ListDocumentsRequest; + })(); + + v1.ListDocumentsResponse = (function() { + + /** + * Properties of a ListDocumentsResponse. + * @memberof google.firestore.v1 + * @interface IListDocumentsResponse + * @property {Array.|null} [documents] ListDocumentsResponse documents + * @property {string|null} [nextPageToken] ListDocumentsResponse nextPageToken + */ + + /** + * Constructs a new ListDocumentsResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a ListDocumentsResponse. + * @implements IListDocumentsResponse + * @constructor + * @param {google.firestore.v1.IListDocumentsResponse=} [properties] Properties to set + */ + function ListDocumentsResponse(properties) { + this.documents = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListDocumentsResponse documents. + * @member {Array.} documents + * @memberof google.firestore.v1.ListDocumentsResponse + * @instance + */ + ListDocumentsResponse.prototype.documents = $util.emptyArray; + + /** + * ListDocumentsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.firestore.v1.ListDocumentsResponse + * @instance + */ + ListDocumentsResponse.prototype.nextPageToken = ""; + + /** + * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ListDocumentsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ListDocumentsResponse} ListDocumentsResponse + */ + ListDocumentsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ListDocumentsResponse) + return object; + var message = new $root.google.firestore.v1.ListDocumentsResponse(); + if (object.documents) { + if (!Array.isArray(object.documents)) + throw TypeError(".google.firestore.v1.ListDocumentsResponse.documents: array expected"); + message.documents = []; + for (var i = 0; i < object.documents.length; ++i) { + if (typeof object.documents[i] !== "object") + throw TypeError(".google.firestore.v1.ListDocumentsResponse.documents: object expected"); + message.documents[i] = $root.google.firestore.v1.Document.fromObject(object.documents[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ListDocumentsResponse + * @static + * @param {google.firestore.v1.ListDocumentsResponse} message ListDocumentsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListDocumentsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.documents = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.documents && message.documents.length) { + object.documents = []; + for (var j = 0; j < message.documents.length; ++j) + object.documents[j] = $root.google.firestore.v1.Document.toObject(message.documents[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListDocumentsResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.ListDocumentsResponse + * @instance + * @returns {Object.} JSON object + */ + ListDocumentsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListDocumentsResponse + * @function getTypeUrl + * @memberof google.firestore.v1.ListDocumentsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListDocumentsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ListDocumentsResponse"; + }; + + return ListDocumentsResponse; + })(); + + v1.CreateDocumentRequest = (function() { + + /** + * Properties of a CreateDocumentRequest. + * @memberof google.firestore.v1 + * @interface ICreateDocumentRequest + * @property {string|null} [parent] CreateDocumentRequest parent + * @property {string|null} [collectionId] CreateDocumentRequest collectionId + * @property {string|null} [documentId] CreateDocumentRequest documentId + * @property {google.firestore.v1.IDocument|null} [document] CreateDocumentRequest document + * @property {google.firestore.v1.IDocumentMask|null} [mask] CreateDocumentRequest mask + */ + + /** + * Constructs a new CreateDocumentRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a CreateDocumentRequest. + * @implements ICreateDocumentRequest + * @constructor + * @param {google.firestore.v1.ICreateDocumentRequest=} [properties] Properties to set + */ + function CreateDocumentRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateDocumentRequest parent. + * @member {string} parent + * @memberof google.firestore.v1.CreateDocumentRequest + * @instance + */ + CreateDocumentRequest.prototype.parent = ""; + + /** + * CreateDocumentRequest collectionId. + * @member {string} collectionId + * @memberof google.firestore.v1.CreateDocumentRequest + * @instance + */ + CreateDocumentRequest.prototype.collectionId = ""; + + /** + * CreateDocumentRequest documentId. + * @member {string} documentId + * @memberof google.firestore.v1.CreateDocumentRequest + * @instance + */ + CreateDocumentRequest.prototype.documentId = ""; + + /** + * CreateDocumentRequest document. + * @member {google.firestore.v1.IDocument|null|undefined} document + * @memberof google.firestore.v1.CreateDocumentRequest + * @instance + */ + CreateDocumentRequest.prototype.document = null; + + /** + * CreateDocumentRequest mask. + * @member {google.firestore.v1.IDocumentMask|null|undefined} mask + * @memberof google.firestore.v1.CreateDocumentRequest + * @instance + */ + CreateDocumentRequest.prototype.mask = null; + + /** + * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.CreateDocumentRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.CreateDocumentRequest} CreateDocumentRequest + */ + CreateDocumentRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.CreateDocumentRequest) + return object; + var message = new $root.google.firestore.v1.CreateDocumentRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.collectionId != null) + message.collectionId = String(object.collectionId); + if (object.documentId != null) + message.documentId = String(object.documentId); + if (object.document != null) { + if (typeof object.document !== "object") + throw TypeError(".google.firestore.v1.CreateDocumentRequest.document: object expected"); + message.document = $root.google.firestore.v1.Document.fromObject(object.document); + } + if (object.mask != null) { + if (typeof object.mask !== "object") + throw TypeError(".google.firestore.v1.CreateDocumentRequest.mask: object expected"); + message.mask = $root.google.firestore.v1.DocumentMask.fromObject(object.mask); + } + return message; + }; + + /** + * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.CreateDocumentRequest + * @static + * @param {google.firestore.v1.CreateDocumentRequest} message CreateDocumentRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateDocumentRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.collectionId = ""; + object.documentId = ""; + object.document = null; + object.mask = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.collectionId != null && message.hasOwnProperty("collectionId")) + object.collectionId = message.collectionId; + if (message.documentId != null && message.hasOwnProperty("documentId")) + object.documentId = message.documentId; + if (message.document != null && message.hasOwnProperty("document")) + object.document = $root.google.firestore.v1.Document.toObject(message.document, options); + if (message.mask != null && message.hasOwnProperty("mask")) + object.mask = $root.google.firestore.v1.DocumentMask.toObject(message.mask, options); + return object; + }; + + /** + * Converts this CreateDocumentRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.CreateDocumentRequest + * @instance + * @returns {Object.} JSON object + */ + CreateDocumentRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateDocumentRequest + * @function getTypeUrl + * @memberof google.firestore.v1.CreateDocumentRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateDocumentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.CreateDocumentRequest"; + }; + + return CreateDocumentRequest; + })(); + + v1.UpdateDocumentRequest = (function() { + + /** + * Properties of an UpdateDocumentRequest. + * @memberof google.firestore.v1 + * @interface IUpdateDocumentRequest + * @property {google.firestore.v1.IDocument|null} [document] UpdateDocumentRequest document + * @property {google.firestore.v1.IDocumentMask|null} [updateMask] UpdateDocumentRequest updateMask + * @property {google.firestore.v1.IDocumentMask|null} [mask] UpdateDocumentRequest mask + * @property {google.firestore.v1.IPrecondition|null} [currentDocument] UpdateDocumentRequest currentDocument + */ + + /** + * Constructs a new UpdateDocumentRequest. + * @memberof google.firestore.v1 + * @classdesc Represents an UpdateDocumentRequest. + * @implements IUpdateDocumentRequest + * @constructor + * @param {google.firestore.v1.IUpdateDocumentRequest=} [properties] Properties to set + */ + function UpdateDocumentRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateDocumentRequest document. + * @member {google.firestore.v1.IDocument|null|undefined} document + * @memberof google.firestore.v1.UpdateDocumentRequest + * @instance + */ + UpdateDocumentRequest.prototype.document = null; + + /** + * UpdateDocumentRequest updateMask. + * @member {google.firestore.v1.IDocumentMask|null|undefined} updateMask + * @memberof google.firestore.v1.UpdateDocumentRequest + * @instance + */ + UpdateDocumentRequest.prototype.updateMask = null; + + /** + * UpdateDocumentRequest mask. + * @member {google.firestore.v1.IDocumentMask|null|undefined} mask + * @memberof google.firestore.v1.UpdateDocumentRequest + * @instance + */ + UpdateDocumentRequest.prototype.mask = null; + + /** + * UpdateDocumentRequest currentDocument. + * @member {google.firestore.v1.IPrecondition|null|undefined} currentDocument + * @memberof google.firestore.v1.UpdateDocumentRequest + * @instance + */ + UpdateDocumentRequest.prototype.currentDocument = null; + + /** + * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.UpdateDocumentRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.UpdateDocumentRequest} UpdateDocumentRequest + */ + UpdateDocumentRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.UpdateDocumentRequest) + return object; + var message = new $root.google.firestore.v1.UpdateDocumentRequest(); + if (object.document != null) { + if (typeof object.document !== "object") + throw TypeError(".google.firestore.v1.UpdateDocumentRequest.document: object expected"); + message.document = $root.google.firestore.v1.Document.fromObject(object.document); + } + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.firestore.v1.UpdateDocumentRequest.updateMask: object expected"); + message.updateMask = $root.google.firestore.v1.DocumentMask.fromObject(object.updateMask); + } + if (object.mask != null) { + if (typeof object.mask !== "object") + throw TypeError(".google.firestore.v1.UpdateDocumentRequest.mask: object expected"); + message.mask = $root.google.firestore.v1.DocumentMask.fromObject(object.mask); + } + if (object.currentDocument != null) { + if (typeof object.currentDocument !== "object") + throw TypeError(".google.firestore.v1.UpdateDocumentRequest.currentDocument: object expected"); + message.currentDocument = $root.google.firestore.v1.Precondition.fromObject(object.currentDocument); + } + return message; + }; + + /** + * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.UpdateDocumentRequest + * @static + * @param {google.firestore.v1.UpdateDocumentRequest} message UpdateDocumentRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateDocumentRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.document = null; + object.updateMask = null; + object.mask = null; + object.currentDocument = null; + } + if (message.document != null && message.hasOwnProperty("document")) + object.document = $root.google.firestore.v1.Document.toObject(message.document, options); + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.firestore.v1.DocumentMask.toObject(message.updateMask, options); + if (message.mask != null && message.hasOwnProperty("mask")) + object.mask = $root.google.firestore.v1.DocumentMask.toObject(message.mask, options); + if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) + object.currentDocument = $root.google.firestore.v1.Precondition.toObject(message.currentDocument, options); + return object; + }; + + /** + * Converts this UpdateDocumentRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.UpdateDocumentRequest + * @instance + * @returns {Object.} JSON object + */ + UpdateDocumentRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateDocumentRequest + * @function getTypeUrl + * @memberof google.firestore.v1.UpdateDocumentRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateDocumentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.UpdateDocumentRequest"; + }; + + return UpdateDocumentRequest; + })(); + + v1.DeleteDocumentRequest = (function() { + + /** + * Properties of a DeleteDocumentRequest. + * @memberof google.firestore.v1 + * @interface IDeleteDocumentRequest + * @property {string|null} [name] DeleteDocumentRequest name + * @property {google.firestore.v1.IPrecondition|null} [currentDocument] DeleteDocumentRequest currentDocument + */ + + /** + * Constructs a new DeleteDocumentRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a DeleteDocumentRequest. + * @implements IDeleteDocumentRequest + * @constructor + * @param {google.firestore.v1.IDeleteDocumentRequest=} [properties] Properties to set + */ + function DeleteDocumentRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteDocumentRequest name. + * @member {string} name + * @memberof google.firestore.v1.DeleteDocumentRequest + * @instance + */ + DeleteDocumentRequest.prototype.name = ""; + + /** + * DeleteDocumentRequest currentDocument. + * @member {google.firestore.v1.IPrecondition|null|undefined} currentDocument + * @memberof google.firestore.v1.DeleteDocumentRequest + * @instance + */ + DeleteDocumentRequest.prototype.currentDocument = null; + + /** + * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.DeleteDocumentRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.DeleteDocumentRequest} DeleteDocumentRequest + */ + DeleteDocumentRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.DeleteDocumentRequest) + return object; + var message = new $root.google.firestore.v1.DeleteDocumentRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.currentDocument != null) { + if (typeof object.currentDocument !== "object") + throw TypeError(".google.firestore.v1.DeleteDocumentRequest.currentDocument: object expected"); + message.currentDocument = $root.google.firestore.v1.Precondition.fromObject(object.currentDocument); + } + return message; + }; + + /** + * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.DeleteDocumentRequest + * @static + * @param {google.firestore.v1.DeleteDocumentRequest} message DeleteDocumentRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteDocumentRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.currentDocument = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) + object.currentDocument = $root.google.firestore.v1.Precondition.toObject(message.currentDocument, options); + return object; + }; + + /** + * Converts this DeleteDocumentRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.DeleteDocumentRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteDocumentRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteDocumentRequest + * @function getTypeUrl + * @memberof google.firestore.v1.DeleteDocumentRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteDocumentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.DeleteDocumentRequest"; + }; + + return DeleteDocumentRequest; + })(); + + v1.BatchGetDocumentsRequest = (function() { + + /** + * Properties of a BatchGetDocumentsRequest. + * @memberof google.firestore.v1 + * @interface IBatchGetDocumentsRequest + * @property {string|null} [database] BatchGetDocumentsRequest database + * @property {Array.|null} [documents] BatchGetDocumentsRequest documents + * @property {google.firestore.v1.IDocumentMask|null} [mask] BatchGetDocumentsRequest mask + * @property {Uint8Array|null} [transaction] BatchGetDocumentsRequest transaction + * @property {google.firestore.v1.ITransactionOptions|null} [newTransaction] BatchGetDocumentsRequest newTransaction + * @property {google.protobuf.ITimestamp|null} [readTime] BatchGetDocumentsRequest readTime + */ + + /** + * Constructs a new BatchGetDocumentsRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a BatchGetDocumentsRequest. + * @implements IBatchGetDocumentsRequest + * @constructor + * @param {google.firestore.v1.IBatchGetDocumentsRequest=} [properties] Properties to set + */ + function BatchGetDocumentsRequest(properties) { + this.documents = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BatchGetDocumentsRequest database. + * @member {string} database + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.database = ""; + + /** + * BatchGetDocumentsRequest documents. + * @member {Array.} documents + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.documents = $util.emptyArray; + + /** + * BatchGetDocumentsRequest mask. + * @member {google.firestore.v1.IDocumentMask|null|undefined} mask + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.mask = null; + + /** + * BatchGetDocumentsRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.transaction = null; + + /** + * BatchGetDocumentsRequest newTransaction. + * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.newTransaction = null; + + /** + * BatchGetDocumentsRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.readTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * BatchGetDocumentsRequest consistencySelector. + * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @instance + */ + Object.defineProperty(BatchGetDocumentsRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.BatchGetDocumentsRequest} BatchGetDocumentsRequest + */ + BatchGetDocumentsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.BatchGetDocumentsRequest) + return object; + var message = new $root.google.firestore.v1.BatchGetDocumentsRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.documents) { + if (!Array.isArray(object.documents)) + throw TypeError(".google.firestore.v1.BatchGetDocumentsRequest.documents: array expected"); + message.documents = []; + for (var i = 0; i < object.documents.length; ++i) + message.documents[i] = String(object.documents[i]); + } + if (object.mask != null) { + if (typeof object.mask !== "object") + throw TypeError(".google.firestore.v1.BatchGetDocumentsRequest.mask: object expected"); + message.mask = $root.google.firestore.v1.DocumentMask.fromObject(object.mask); + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.newTransaction != null) { + if (typeof object.newTransaction !== "object") + throw TypeError(".google.firestore.v1.BatchGetDocumentsRequest.newTransaction: object expected"); + message.newTransaction = $root.google.firestore.v1.TransactionOptions.fromObject(object.newTransaction); + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.BatchGetDocumentsRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @static + * @param {google.firestore.v1.BatchGetDocumentsRequest} message BatchGetDocumentsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchGetDocumentsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.documents = []; + if (options.defaults) { + object.database = ""; + object.mask = null; + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.documents && message.documents.length) { + object.documents = []; + for (var j = 0; j < message.documents.length; ++j) + object.documents[j] = message.documents[j]; + } + if (message.mask != null && message.hasOwnProperty("mask")) + object.mask = $root.google.firestore.v1.DocumentMask.toObject(message.mask, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; + } + if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { + object.newTransaction = $root.google.firestore.v1.TransactionOptions.toObject(message.newTransaction, options); + if (options.oneofs) + object.consistencySelector = "newTransaction"; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + return object; + }; + + /** + * Converts this BatchGetDocumentsRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @instance + * @returns {Object.} JSON object + */ + BatchGetDocumentsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchGetDocumentsRequest + * @function getTypeUrl + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchGetDocumentsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.BatchGetDocumentsRequest"; + }; + + return BatchGetDocumentsRequest; + })(); + + v1.BatchGetDocumentsResponse = (function() { + + /** + * Properties of a BatchGetDocumentsResponse. + * @memberof google.firestore.v1 + * @interface IBatchGetDocumentsResponse + * @property {google.firestore.v1.IDocument|null} [found] BatchGetDocumentsResponse found + * @property {string|null} [missing] BatchGetDocumentsResponse missing + * @property {Uint8Array|null} [transaction] BatchGetDocumentsResponse transaction + * @property {google.protobuf.ITimestamp|null} [readTime] BatchGetDocumentsResponse readTime + */ + + /** + * Constructs a new BatchGetDocumentsResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a BatchGetDocumentsResponse. + * @implements IBatchGetDocumentsResponse + * @constructor + * @param {google.firestore.v1.IBatchGetDocumentsResponse=} [properties] Properties to set + */ + function BatchGetDocumentsResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BatchGetDocumentsResponse found. + * @member {google.firestore.v1.IDocument|null|undefined} found + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @instance + */ + BatchGetDocumentsResponse.prototype.found = null; + + /** + * BatchGetDocumentsResponse missing. + * @member {string|null|undefined} missing + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @instance + */ + BatchGetDocumentsResponse.prototype.missing = null; + + /** + * BatchGetDocumentsResponse transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @instance + */ + BatchGetDocumentsResponse.prototype.transaction = $util.newBuffer([]); + + /** + * BatchGetDocumentsResponse readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @instance + */ + BatchGetDocumentsResponse.prototype.readTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * BatchGetDocumentsResponse result. + * @member {"found"|"missing"|undefined} result + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @instance + */ + Object.defineProperty(BatchGetDocumentsResponse.prototype, "result", { + get: $util.oneOfGetter($oneOfFields = ["found", "missing"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.BatchGetDocumentsResponse} BatchGetDocumentsResponse + */ + BatchGetDocumentsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.BatchGetDocumentsResponse) + return object; + var message = new $root.google.firestore.v1.BatchGetDocumentsResponse(); + if (object.found != null) { + if (typeof object.found !== "object") + throw TypeError(".google.firestore.v1.BatchGetDocumentsResponse.found: object expected"); + message.found = $root.google.firestore.v1.Document.fromObject(object.found); + } + if (object.missing != null) + message.missing = String(object.missing); + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.BatchGetDocumentsResponse.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @static + * @param {google.firestore.v1.BatchGetDocumentsResponse} message BatchGetDocumentsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchGetDocumentsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + object.readTime = null; + } + if (message.found != null && message.hasOwnProperty("found")) { + object.found = $root.google.firestore.v1.Document.toObject(message.found, options); + if (options.oneofs) + object.result = "found"; + } + if (message.missing != null && message.hasOwnProperty("missing")) { + object.missing = message.missing; + if (options.oneofs) + object.result = "missing"; + } + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + return object; + }; + + /** + * Converts this BatchGetDocumentsResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @instance + * @returns {Object.} JSON object + */ + BatchGetDocumentsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchGetDocumentsResponse + * @function getTypeUrl + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchGetDocumentsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.BatchGetDocumentsResponse"; + }; + + return BatchGetDocumentsResponse; + })(); + + v1.BeginTransactionRequest = (function() { + + /** + * Properties of a BeginTransactionRequest. + * @memberof google.firestore.v1 + * @interface IBeginTransactionRequest + * @property {string|null} [database] BeginTransactionRequest database + * @property {google.firestore.v1.ITransactionOptions|null} [options] BeginTransactionRequest options + */ + + /** + * Constructs a new BeginTransactionRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a BeginTransactionRequest. + * @implements IBeginTransactionRequest + * @constructor + * @param {google.firestore.v1.IBeginTransactionRequest=} [properties] Properties to set + */ + function BeginTransactionRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BeginTransactionRequest database. + * @member {string} database + * @memberof google.firestore.v1.BeginTransactionRequest + * @instance + */ + BeginTransactionRequest.prototype.database = ""; + + /** + * BeginTransactionRequest options. + * @member {google.firestore.v1.ITransactionOptions|null|undefined} options + * @memberof google.firestore.v1.BeginTransactionRequest + * @instance + */ + BeginTransactionRequest.prototype.options = null; + + /** + * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.BeginTransactionRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.BeginTransactionRequest} BeginTransactionRequest + */ + BeginTransactionRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.BeginTransactionRequest) + return object; + var message = new $root.google.firestore.v1.BeginTransactionRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.firestore.v1.BeginTransactionRequest.options: object expected"); + message.options = $root.google.firestore.v1.TransactionOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.BeginTransactionRequest + * @static + * @param {google.firestore.v1.BeginTransactionRequest} message BeginTransactionRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BeginTransactionRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.database = ""; + object.options = null; + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.firestore.v1.TransactionOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this BeginTransactionRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.BeginTransactionRequest + * @instance + * @returns {Object.} JSON object + */ + BeginTransactionRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BeginTransactionRequest + * @function getTypeUrl + * @memberof google.firestore.v1.BeginTransactionRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BeginTransactionRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.BeginTransactionRequest"; + }; + + return BeginTransactionRequest; + })(); + + v1.BeginTransactionResponse = (function() { + + /** + * Properties of a BeginTransactionResponse. + * @memberof google.firestore.v1 + * @interface IBeginTransactionResponse + * @property {Uint8Array|null} [transaction] BeginTransactionResponse transaction + */ + + /** + * Constructs a new BeginTransactionResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a BeginTransactionResponse. + * @implements IBeginTransactionResponse + * @constructor + * @param {google.firestore.v1.IBeginTransactionResponse=} [properties] Properties to set + */ + function BeginTransactionResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BeginTransactionResponse transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1.BeginTransactionResponse + * @instance + */ + BeginTransactionResponse.prototype.transaction = $util.newBuffer([]); + + /** + * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.BeginTransactionResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.BeginTransactionResponse} BeginTransactionResponse + */ + BeginTransactionResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.BeginTransactionResponse) + return object; + var message = new $root.google.firestore.v1.BeginTransactionResponse(); + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + return message; + }; + + /** + * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.BeginTransactionResponse + * @static + * @param {google.firestore.v1.BeginTransactionResponse} message BeginTransactionResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BeginTransactionResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + return object; + }; + + /** + * Converts this BeginTransactionResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.BeginTransactionResponse + * @instance + * @returns {Object.} JSON object + */ + BeginTransactionResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BeginTransactionResponse + * @function getTypeUrl + * @memberof google.firestore.v1.BeginTransactionResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BeginTransactionResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.BeginTransactionResponse"; + }; + + return BeginTransactionResponse; + })(); + + v1.CommitRequest = (function() { + + /** + * Properties of a CommitRequest. + * @memberof google.firestore.v1 + * @interface ICommitRequest + * @property {string|null} [database] CommitRequest database + * @property {Array.|null} [writes] CommitRequest writes + * @property {Uint8Array|null} [transaction] CommitRequest transaction + */ + + /** + * Constructs a new CommitRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a CommitRequest. + * @implements ICommitRequest + * @constructor + * @param {google.firestore.v1.ICommitRequest=} [properties] Properties to set + */ + function CommitRequest(properties) { + this.writes = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CommitRequest database. + * @member {string} database + * @memberof google.firestore.v1.CommitRequest + * @instance + */ + CommitRequest.prototype.database = ""; + + /** + * CommitRequest writes. + * @member {Array.} writes + * @memberof google.firestore.v1.CommitRequest + * @instance + */ + CommitRequest.prototype.writes = $util.emptyArray; + + /** + * CommitRequest transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1.CommitRequest + * @instance + */ + CommitRequest.prototype.transaction = $util.newBuffer([]); + + /** + * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.CommitRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.CommitRequest} CommitRequest + */ + CommitRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.CommitRequest) + return object; + var message = new $root.google.firestore.v1.CommitRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.writes) { + if (!Array.isArray(object.writes)) + throw TypeError(".google.firestore.v1.CommitRequest.writes: array expected"); + message.writes = []; + for (var i = 0; i < object.writes.length; ++i) { + if (typeof object.writes[i] !== "object") + throw TypeError(".google.firestore.v1.CommitRequest.writes: object expected"); + message.writes[i] = $root.google.firestore.v1.Write.fromObject(object.writes[i]); + } + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + return message; + }; + + /** + * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.CommitRequest + * @static + * @param {google.firestore.v1.CommitRequest} message CommitRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CommitRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.writes = []; + if (options.defaults) { + object.database = ""; + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.writes && message.writes.length) { + object.writes = []; + for (var j = 0; j < message.writes.length; ++j) + object.writes[j] = $root.google.firestore.v1.Write.toObject(message.writes[j], options); + } + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + return object; + }; + + /** + * Converts this CommitRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.CommitRequest + * @instance + * @returns {Object.} JSON object + */ + CommitRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CommitRequest + * @function getTypeUrl + * @memberof google.firestore.v1.CommitRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CommitRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.CommitRequest"; + }; + + return CommitRequest; + })(); + + v1.CommitResponse = (function() { + + /** + * Properties of a CommitResponse. + * @memberof google.firestore.v1 + * @interface ICommitResponse + * @property {Array.|null} [writeResults] CommitResponse writeResults + * @property {google.protobuf.ITimestamp|null} [commitTime] CommitResponse commitTime + */ + + /** + * Constructs a new CommitResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a CommitResponse. + * @implements ICommitResponse + * @constructor + * @param {google.firestore.v1.ICommitResponse=} [properties] Properties to set + */ + function CommitResponse(properties) { + this.writeResults = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CommitResponse writeResults. + * @member {Array.} writeResults + * @memberof google.firestore.v1.CommitResponse + * @instance + */ + CommitResponse.prototype.writeResults = $util.emptyArray; + + /** + * CommitResponse commitTime. + * @member {google.protobuf.ITimestamp|null|undefined} commitTime + * @memberof google.firestore.v1.CommitResponse + * @instance + */ + CommitResponse.prototype.commitTime = null; + + /** + * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.CommitResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.CommitResponse} CommitResponse + */ + CommitResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.CommitResponse) + return object; + var message = new $root.google.firestore.v1.CommitResponse(); + if (object.writeResults) { + if (!Array.isArray(object.writeResults)) + throw TypeError(".google.firestore.v1.CommitResponse.writeResults: array expected"); + message.writeResults = []; + for (var i = 0; i < object.writeResults.length; ++i) { + if (typeof object.writeResults[i] !== "object") + throw TypeError(".google.firestore.v1.CommitResponse.writeResults: object expected"); + message.writeResults[i] = $root.google.firestore.v1.WriteResult.fromObject(object.writeResults[i]); + } + } + if (object.commitTime != null) { + if (typeof object.commitTime !== "object") + throw TypeError(".google.firestore.v1.CommitResponse.commitTime: object expected"); + message.commitTime = $root.google.protobuf.Timestamp.fromObject(object.commitTime); + } + return message; + }; + + /** + * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.CommitResponse + * @static + * @param {google.firestore.v1.CommitResponse} message CommitResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CommitResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.writeResults = []; + if (options.defaults) + object.commitTime = null; + if (message.writeResults && message.writeResults.length) { + object.writeResults = []; + for (var j = 0; j < message.writeResults.length; ++j) + object.writeResults[j] = $root.google.firestore.v1.WriteResult.toObject(message.writeResults[j], options); + } + if (message.commitTime != null && message.hasOwnProperty("commitTime")) + object.commitTime = $root.google.protobuf.Timestamp.toObject(message.commitTime, options); + return object; + }; + + /** + * Converts this CommitResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.CommitResponse + * @instance + * @returns {Object.} JSON object + */ + CommitResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CommitResponse + * @function getTypeUrl + * @memberof google.firestore.v1.CommitResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CommitResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.CommitResponse"; + }; + + return CommitResponse; + })(); + + v1.RollbackRequest = (function() { + + /** + * Properties of a RollbackRequest. + * @memberof google.firestore.v1 + * @interface IRollbackRequest + * @property {string|null} [database] RollbackRequest database + * @property {Uint8Array|null} [transaction] RollbackRequest transaction + */ + + /** + * Constructs a new RollbackRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a RollbackRequest. + * @implements IRollbackRequest + * @constructor + * @param {google.firestore.v1.IRollbackRequest=} [properties] Properties to set + */ + function RollbackRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RollbackRequest database. + * @member {string} database + * @memberof google.firestore.v1.RollbackRequest + * @instance + */ + RollbackRequest.prototype.database = ""; + + /** + * RollbackRequest transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1.RollbackRequest + * @instance + */ + RollbackRequest.prototype.transaction = $util.newBuffer([]); + + /** + * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.RollbackRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.RollbackRequest} RollbackRequest + */ + RollbackRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.RollbackRequest) + return object; + var message = new $root.google.firestore.v1.RollbackRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + return message; + }; + + /** + * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.RollbackRequest + * @static + * @param {google.firestore.v1.RollbackRequest} message RollbackRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RollbackRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.database = ""; + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + return object; + }; + + /** + * Converts this RollbackRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.RollbackRequest + * @instance + * @returns {Object.} JSON object + */ + RollbackRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RollbackRequest + * @function getTypeUrl + * @memberof google.firestore.v1.RollbackRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RollbackRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.RollbackRequest"; + }; + + return RollbackRequest; + })(); + + v1.RunQueryRequest = (function() { + + /** + * Properties of a RunQueryRequest. + * @memberof google.firestore.v1 + * @interface IRunQueryRequest + * @property {string|null} [parent] RunQueryRequest parent + * @property {google.firestore.v1.IStructuredQuery|null} [structuredQuery] RunQueryRequest structuredQuery + * @property {Uint8Array|null} [transaction] RunQueryRequest transaction + * @property {google.firestore.v1.ITransactionOptions|null} [newTransaction] RunQueryRequest newTransaction + * @property {google.protobuf.ITimestamp|null} [readTime] RunQueryRequest readTime + * @property {google.firestore.v1.IExplainOptions|null} [explainOptions] RunQueryRequest explainOptions + */ + + /** + * Constructs a new RunQueryRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a RunQueryRequest. + * @implements IRunQueryRequest + * @constructor + * @param {google.firestore.v1.IRunQueryRequest=} [properties] Properties to set + */ + function RunQueryRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RunQueryRequest parent. + * @member {string} parent + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.parent = ""; + + /** + * RunQueryRequest structuredQuery. + * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.structuredQuery = null; + + /** + * RunQueryRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.transaction = null; + + /** + * RunQueryRequest newTransaction. + * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.newTransaction = null; + + /** + * RunQueryRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.readTime = null; + + /** + * RunQueryRequest explainOptions. + * @member {google.firestore.v1.IExplainOptions|null|undefined} explainOptions + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.explainOptions = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * RunQueryRequest queryType. + * @member {"structuredQuery"|undefined} queryType + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + Object.defineProperty(RunQueryRequest.prototype, "queryType", { + get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * RunQueryRequest consistencySelector. + * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + Object.defineProperty(RunQueryRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.RunQueryRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.RunQueryRequest} RunQueryRequest + */ + RunQueryRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.RunQueryRequest) + return object; + var message = new $root.google.firestore.v1.RunQueryRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.structuredQuery != null) { + if (typeof object.structuredQuery !== "object") + throw TypeError(".google.firestore.v1.RunQueryRequest.structuredQuery: object expected"); + message.structuredQuery = $root.google.firestore.v1.StructuredQuery.fromObject(object.structuredQuery); + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.newTransaction != null) { + if (typeof object.newTransaction !== "object") + throw TypeError(".google.firestore.v1.RunQueryRequest.newTransaction: object expected"); + message.newTransaction = $root.google.firestore.v1.TransactionOptions.fromObject(object.newTransaction); + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.RunQueryRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.explainOptions != null) { + if (typeof object.explainOptions !== "object") + throw TypeError(".google.firestore.v1.RunQueryRequest.explainOptions: object expected"); + message.explainOptions = $root.google.firestore.v1.ExplainOptions.fromObject(object.explainOptions); + } + return message; + }; + + /** + * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.RunQueryRequest + * @static + * @param {google.firestore.v1.RunQueryRequest} message RunQueryRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RunQueryRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.explainOptions = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { + object.structuredQuery = $root.google.firestore.v1.StructuredQuery.toObject(message.structuredQuery, options); + if (options.oneofs) + object.queryType = "structuredQuery"; + } + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; + } + if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { + object.newTransaction = $root.google.firestore.v1.TransactionOptions.toObject(message.newTransaction, options); + if (options.oneofs) + object.consistencySelector = "newTransaction"; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + if (message.explainOptions != null && message.hasOwnProperty("explainOptions")) + object.explainOptions = $root.google.firestore.v1.ExplainOptions.toObject(message.explainOptions, options); + return object; + }; + + /** + * Converts this RunQueryRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.RunQueryRequest + * @instance + * @returns {Object.} JSON object + */ + RunQueryRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RunQueryRequest + * @function getTypeUrl + * @memberof google.firestore.v1.RunQueryRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RunQueryRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.RunQueryRequest"; + }; + + return RunQueryRequest; + })(); + + v1.RunQueryResponse = (function() { + + /** + * Properties of a RunQueryResponse. + * @memberof google.firestore.v1 + * @interface IRunQueryResponse + * @property {Uint8Array|null} [transaction] RunQueryResponse transaction + * @property {google.firestore.v1.IDocument|null} [document] RunQueryResponse document + * @property {google.protobuf.ITimestamp|null} [readTime] RunQueryResponse readTime + * @property {number|null} [skippedResults] RunQueryResponse skippedResults + * @property {boolean|null} [done] RunQueryResponse done + * @property {google.firestore.v1.IExplainMetrics|null} [explainMetrics] RunQueryResponse explainMetrics + */ + + /** + * Constructs a new RunQueryResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a RunQueryResponse. + * @implements IRunQueryResponse + * @constructor + * @param {google.firestore.v1.IRunQueryResponse=} [properties] Properties to set + */ + function RunQueryResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RunQueryResponse transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.transaction = $util.newBuffer([]); + + /** + * RunQueryResponse document. + * @member {google.firestore.v1.IDocument|null|undefined} document + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.document = null; + + /** + * RunQueryResponse readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.readTime = null; + + /** + * RunQueryResponse skippedResults. + * @member {number} skippedResults + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.skippedResults = 0; + + /** + * RunQueryResponse done. + * @member {boolean|null|undefined} done + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.done = null; + + /** + * RunQueryResponse explainMetrics. + * @member {google.firestore.v1.IExplainMetrics|null|undefined} explainMetrics + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.explainMetrics = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * RunQueryResponse continuationSelector. + * @member {"done"|undefined} continuationSelector + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + Object.defineProperty(RunQueryResponse.prototype, "continuationSelector", { + get: $util.oneOfGetter($oneOfFields = ["done"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.RunQueryResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.RunQueryResponse} RunQueryResponse + */ + RunQueryResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.RunQueryResponse) + return object; + var message = new $root.google.firestore.v1.RunQueryResponse(); + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.document != null) { + if (typeof object.document !== "object") + throw TypeError(".google.firestore.v1.RunQueryResponse.document: object expected"); + message.document = $root.google.firestore.v1.Document.fromObject(object.document); + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.RunQueryResponse.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.skippedResults != null) + message.skippedResults = object.skippedResults | 0; + if (object.done != null) + message.done = Boolean(object.done); + if (object.explainMetrics != null) { + if (typeof object.explainMetrics !== "object") + throw TypeError(".google.firestore.v1.RunQueryResponse.explainMetrics: object expected"); + message.explainMetrics = $root.google.firestore.v1.ExplainMetrics.fromObject(object.explainMetrics); + } + return message; + }; + + /** + * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.RunQueryResponse + * @static + * @param {google.firestore.v1.RunQueryResponse} message RunQueryResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RunQueryResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.document = null; + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + object.readTime = null; + object.skippedResults = 0; + object.explainMetrics = null; + } + if (message.document != null && message.hasOwnProperty("document")) + object.document = $root.google.firestore.v1.Document.toObject(message.document, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (message.skippedResults != null && message.hasOwnProperty("skippedResults")) + object.skippedResults = message.skippedResults; + if (message.done != null && message.hasOwnProperty("done")) { + object.done = message.done; + if (options.oneofs) + object.continuationSelector = "done"; + } + if (message.explainMetrics != null && message.hasOwnProperty("explainMetrics")) + object.explainMetrics = $root.google.firestore.v1.ExplainMetrics.toObject(message.explainMetrics, options); + return object; + }; + + /** + * Converts this RunQueryResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.RunQueryResponse + * @instance + * @returns {Object.} JSON object + */ + RunQueryResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RunQueryResponse + * @function getTypeUrl + * @memberof google.firestore.v1.RunQueryResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RunQueryResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.RunQueryResponse"; + }; + + return RunQueryResponse; + })(); + + v1.ExecutePipelineRequest = (function() { + + /** + * Properties of an ExecutePipelineRequest. + * @memberof google.firestore.v1 + * @interface IExecutePipelineRequest + * @property {string|null} [database] ExecutePipelineRequest database + * @property {google.firestore.v1.IStructuredPipeline|null} [structuredPipeline] ExecutePipelineRequest structuredPipeline + * @property {Uint8Array|null} [transaction] ExecutePipelineRequest transaction + * @property {google.firestore.v1.ITransactionOptions|null} [newTransaction] ExecutePipelineRequest newTransaction + * @property {google.protobuf.ITimestamp|null} [readTime] ExecutePipelineRequest readTime + */ + + /** + * Constructs a new ExecutePipelineRequest. + * @memberof google.firestore.v1 + * @classdesc Represents an ExecutePipelineRequest. + * @implements IExecutePipelineRequest + * @constructor + * @param {google.firestore.v1.IExecutePipelineRequest=} [properties] Properties to set + */ + function ExecutePipelineRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExecutePipelineRequest database. + * @member {string} database + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + ExecutePipelineRequest.prototype.database = ""; + + /** + * ExecutePipelineRequest structuredPipeline. + * @member {google.firestore.v1.IStructuredPipeline|null|undefined} structuredPipeline + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + ExecutePipelineRequest.prototype.structuredPipeline = null; + + /** + * ExecutePipelineRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + ExecutePipelineRequest.prototype.transaction = null; + + /** + * ExecutePipelineRequest newTransaction. + * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + ExecutePipelineRequest.prototype.newTransaction = null; + + /** + * ExecutePipelineRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + ExecutePipelineRequest.prototype.readTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ExecutePipelineRequest pipelineType. + * @member {"structuredPipeline"|undefined} pipelineType + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + Object.defineProperty(ExecutePipelineRequest.prototype, "pipelineType", { + get: $util.oneOfGetter($oneOfFields = ["structuredPipeline"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * ExecutePipelineRequest consistencySelector. + * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + Object.defineProperty(ExecutePipelineRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates an ExecutePipelineRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ExecutePipelineRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ExecutePipelineRequest} ExecutePipelineRequest + */ + ExecutePipelineRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ExecutePipelineRequest) + return object; + var message = new $root.google.firestore.v1.ExecutePipelineRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.structuredPipeline != null) { + if (typeof object.structuredPipeline !== "object") + throw TypeError(".google.firestore.v1.ExecutePipelineRequest.structuredPipeline: object expected"); + message.structuredPipeline = $root.google.firestore.v1.StructuredPipeline.fromObject(object.structuredPipeline); + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.newTransaction != null) { + if (typeof object.newTransaction !== "object") + throw TypeError(".google.firestore.v1.ExecutePipelineRequest.newTransaction: object expected"); + message.newTransaction = $root.google.firestore.v1.TransactionOptions.fromObject(object.newTransaction); + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.ExecutePipelineRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from an ExecutePipelineRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ExecutePipelineRequest + * @static + * @param {google.firestore.v1.ExecutePipelineRequest} message ExecutePipelineRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExecutePipelineRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.database = ""; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.structuredPipeline != null && message.hasOwnProperty("structuredPipeline")) { + object.structuredPipeline = $root.google.firestore.v1.StructuredPipeline.toObject(message.structuredPipeline, options); + if (options.oneofs) + object.pipelineType = "structuredPipeline"; + } + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; + } + if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { + object.newTransaction = $root.google.firestore.v1.TransactionOptions.toObject(message.newTransaction, options); + if (options.oneofs) + object.consistencySelector = "newTransaction"; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + return object; + }; + + /** + * Converts this ExecutePipelineRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + * @returns {Object.} JSON object + */ + ExecutePipelineRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExecutePipelineRequest + * @function getTypeUrl + * @memberof google.firestore.v1.ExecutePipelineRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExecutePipelineRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ExecutePipelineRequest"; + }; + + return ExecutePipelineRequest; + })(); + + v1.ExecutePipelineResponse = (function() { + + /** + * Properties of an ExecutePipelineResponse. + * @memberof google.firestore.v1 + * @interface IExecutePipelineResponse + * @property {Uint8Array|null} [transaction] ExecutePipelineResponse transaction + * @property {Array.|null} [results] ExecutePipelineResponse results + * @property {google.protobuf.ITimestamp|null} [executionTime] ExecutePipelineResponse executionTime + * @property {google.firestore.v1.IExplainStats|null} [explainStats] ExecutePipelineResponse explainStats + */ + + /** + * Constructs a new ExecutePipelineResponse. + * @memberof google.firestore.v1 + * @classdesc Represents an ExecutePipelineResponse. + * @implements IExecutePipelineResponse + * @constructor + * @param {google.firestore.v1.IExecutePipelineResponse=} [properties] Properties to set + */ + function ExecutePipelineResponse(properties) { + this.results = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExecutePipelineResponse transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1.ExecutePipelineResponse + * @instance + */ + ExecutePipelineResponse.prototype.transaction = $util.newBuffer([]); + + /** + * ExecutePipelineResponse results. + * @member {Array.} results + * @memberof google.firestore.v1.ExecutePipelineResponse + * @instance + */ + ExecutePipelineResponse.prototype.results = $util.emptyArray; + + /** + * ExecutePipelineResponse executionTime. + * @member {google.protobuf.ITimestamp|null|undefined} executionTime + * @memberof google.firestore.v1.ExecutePipelineResponse + * @instance + */ + ExecutePipelineResponse.prototype.executionTime = null; + + /** + * ExecutePipelineResponse explainStats. + * @member {google.firestore.v1.IExplainStats|null|undefined} explainStats + * @memberof google.firestore.v1.ExecutePipelineResponse + * @instance + */ + ExecutePipelineResponse.prototype.explainStats = null; + + /** + * Creates an ExecutePipelineResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ExecutePipelineResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ExecutePipelineResponse} ExecutePipelineResponse + */ + ExecutePipelineResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ExecutePipelineResponse) + return object; + var message = new $root.google.firestore.v1.ExecutePipelineResponse(); + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.results) { + if (!Array.isArray(object.results)) + throw TypeError(".google.firestore.v1.ExecutePipelineResponse.results: array expected"); + message.results = []; + for (var i = 0; i < object.results.length; ++i) { + if (typeof object.results[i] !== "object") + throw TypeError(".google.firestore.v1.ExecutePipelineResponse.results: object expected"); + message.results[i] = $root.google.firestore.v1.Document.fromObject(object.results[i]); + } + } + if (object.executionTime != null) { + if (typeof object.executionTime !== "object") + throw TypeError(".google.firestore.v1.ExecutePipelineResponse.executionTime: object expected"); + message.executionTime = $root.google.protobuf.Timestamp.fromObject(object.executionTime); + } + if (object.explainStats != null) { + if (typeof object.explainStats !== "object") + throw TypeError(".google.firestore.v1.ExecutePipelineResponse.explainStats: object expected"); + message.explainStats = $root.google.firestore.v1.ExplainStats.fromObject(object.explainStats); + } + return message; + }; + + /** + * Creates a plain object from an ExecutePipelineResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ExecutePipelineResponse + * @static + * @param {google.firestore.v1.ExecutePipelineResponse} message ExecutePipelineResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExecutePipelineResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.results = []; + if (options.defaults) { + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + object.executionTime = null; + object.explainStats = null; + } + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (message.results && message.results.length) { + object.results = []; + for (var j = 0; j < message.results.length; ++j) + object.results[j] = $root.google.firestore.v1.Document.toObject(message.results[j], options); + } + if (message.executionTime != null && message.hasOwnProperty("executionTime")) + object.executionTime = $root.google.protobuf.Timestamp.toObject(message.executionTime, options); + if (message.explainStats != null && message.hasOwnProperty("explainStats")) + object.explainStats = $root.google.firestore.v1.ExplainStats.toObject(message.explainStats, options); + return object; + }; + + /** + * Converts this ExecutePipelineResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.ExecutePipelineResponse + * @instance + * @returns {Object.} JSON object + */ + ExecutePipelineResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExecutePipelineResponse + * @function getTypeUrl + * @memberof google.firestore.v1.ExecutePipelineResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExecutePipelineResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ExecutePipelineResponse"; + }; + + return ExecutePipelineResponse; + })(); + + v1.RunAggregationQueryRequest = (function() { + + /** + * Properties of a RunAggregationQueryRequest. + * @memberof google.firestore.v1 + * @interface IRunAggregationQueryRequest + * @property {string|null} [parent] RunAggregationQueryRequest parent + * @property {google.firestore.v1.IStructuredAggregationQuery|null} [structuredAggregationQuery] RunAggregationQueryRequest structuredAggregationQuery + * @property {Uint8Array|null} [transaction] RunAggregationQueryRequest transaction + * @property {google.firestore.v1.ITransactionOptions|null} [newTransaction] RunAggregationQueryRequest newTransaction + * @property {google.protobuf.ITimestamp|null} [readTime] RunAggregationQueryRequest readTime + * @property {google.firestore.v1.IExplainOptions|null} [explainOptions] RunAggregationQueryRequest explainOptions + */ + + /** + * Constructs a new RunAggregationQueryRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a RunAggregationQueryRequest. + * @implements IRunAggregationQueryRequest + * @constructor + * @param {google.firestore.v1.IRunAggregationQueryRequest=} [properties] Properties to set + */ + function RunAggregationQueryRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RunAggregationQueryRequest parent. + * @member {string} parent + * @memberof google.firestore.v1.RunAggregationQueryRequest + * @instance + */ + RunAggregationQueryRequest.prototype.parent = ""; + + /** + * RunAggregationQueryRequest structuredAggregationQuery. + * @member {google.firestore.v1.IStructuredAggregationQuery|null|undefined} structuredAggregationQuery + * @memberof google.firestore.v1.RunAggregationQueryRequest + * @instance + */ + RunAggregationQueryRequest.prototype.structuredAggregationQuery = null; + + /** + * RunAggregationQueryRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1.RunAggregationQueryRequest + * @instance + */ + RunAggregationQueryRequest.prototype.transaction = null; + + /** + * RunAggregationQueryRequest newTransaction. + * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction + * @memberof google.firestore.v1.RunAggregationQueryRequest + * @instance + */ + RunAggregationQueryRequest.prototype.newTransaction = null; + + /** + * RunAggregationQueryRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.RunAggregationQueryRequest + * @instance + */ + RunAggregationQueryRequest.prototype.readTime = null; + + /** + * RunAggregationQueryRequest explainOptions. + * @member {google.firestore.v1.IExplainOptions|null|undefined} explainOptions + * @memberof google.firestore.v1.RunAggregationQueryRequest + * @instance + */ + RunAggregationQueryRequest.prototype.explainOptions = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * RunAggregationQueryRequest queryType. + * @member {"structuredAggregationQuery"|undefined} queryType + * @memberof google.firestore.v1.RunAggregationQueryRequest + * @instance + */ + Object.defineProperty(RunAggregationQueryRequest.prototype, "queryType", { + get: $util.oneOfGetter($oneOfFields = ["structuredAggregationQuery"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * RunAggregationQueryRequest consistencySelector. + * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.RunAggregationQueryRequest + * @instance + */ + Object.defineProperty(RunAggregationQueryRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a RunAggregationQueryRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.RunAggregationQueryRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.RunAggregationQueryRequest} RunAggregationQueryRequest + */ + RunAggregationQueryRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.RunAggregationQueryRequest) + return object; + var message = new $root.google.firestore.v1.RunAggregationQueryRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.structuredAggregationQuery != null) { + if (typeof object.structuredAggregationQuery !== "object") + throw TypeError(".google.firestore.v1.RunAggregationQueryRequest.structuredAggregationQuery: object expected"); + message.structuredAggregationQuery = $root.google.firestore.v1.StructuredAggregationQuery.fromObject(object.structuredAggregationQuery); + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.newTransaction != null) { + if (typeof object.newTransaction !== "object") + throw TypeError(".google.firestore.v1.RunAggregationQueryRequest.newTransaction: object expected"); + message.newTransaction = $root.google.firestore.v1.TransactionOptions.fromObject(object.newTransaction); + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.RunAggregationQueryRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.explainOptions != null) { + if (typeof object.explainOptions !== "object") + throw TypeError(".google.firestore.v1.RunAggregationQueryRequest.explainOptions: object expected"); + message.explainOptions = $root.google.firestore.v1.ExplainOptions.fromObject(object.explainOptions); + } + return message; + }; + + /** + * Creates a plain object from a RunAggregationQueryRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.RunAggregationQueryRequest + * @static + * @param {google.firestore.v1.RunAggregationQueryRequest} message RunAggregationQueryRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RunAggregationQueryRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.explainOptions = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.structuredAggregationQuery != null && message.hasOwnProperty("structuredAggregationQuery")) { + object.structuredAggregationQuery = $root.google.firestore.v1.StructuredAggregationQuery.toObject(message.structuredAggregationQuery, options); + if (options.oneofs) + object.queryType = "structuredAggregationQuery"; + } + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; + } + if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { + object.newTransaction = $root.google.firestore.v1.TransactionOptions.toObject(message.newTransaction, options); + if (options.oneofs) + object.consistencySelector = "newTransaction"; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + if (message.explainOptions != null && message.hasOwnProperty("explainOptions")) + object.explainOptions = $root.google.firestore.v1.ExplainOptions.toObject(message.explainOptions, options); + return object; + }; + + /** + * Converts this RunAggregationQueryRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.RunAggregationQueryRequest + * @instance + * @returns {Object.} JSON object + */ + RunAggregationQueryRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RunAggregationQueryRequest + * @function getTypeUrl + * @memberof google.firestore.v1.RunAggregationQueryRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RunAggregationQueryRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.RunAggregationQueryRequest"; + }; + + return RunAggregationQueryRequest; + })(); + + v1.RunAggregationQueryResponse = (function() { + + /** + * Properties of a RunAggregationQueryResponse. + * @memberof google.firestore.v1 + * @interface IRunAggregationQueryResponse + * @property {google.firestore.v1.IAggregationResult|null} [result] RunAggregationQueryResponse result + * @property {Uint8Array|null} [transaction] RunAggregationQueryResponse transaction + * @property {google.protobuf.ITimestamp|null} [readTime] RunAggregationQueryResponse readTime + * @property {google.firestore.v1.IExplainMetrics|null} [explainMetrics] RunAggregationQueryResponse explainMetrics + */ + + /** + * Constructs a new RunAggregationQueryResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a RunAggregationQueryResponse. + * @implements IRunAggregationQueryResponse + * @constructor + * @param {google.firestore.v1.IRunAggregationQueryResponse=} [properties] Properties to set + */ + function RunAggregationQueryResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RunAggregationQueryResponse result. + * @member {google.firestore.v1.IAggregationResult|null|undefined} result + * @memberof google.firestore.v1.RunAggregationQueryResponse + * @instance + */ + RunAggregationQueryResponse.prototype.result = null; + + /** + * RunAggregationQueryResponse transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1.RunAggregationQueryResponse + * @instance + */ + RunAggregationQueryResponse.prototype.transaction = $util.newBuffer([]); + + /** + * RunAggregationQueryResponse readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.RunAggregationQueryResponse + * @instance + */ + RunAggregationQueryResponse.prototype.readTime = null; + + /** + * RunAggregationQueryResponse explainMetrics. + * @member {google.firestore.v1.IExplainMetrics|null|undefined} explainMetrics + * @memberof google.firestore.v1.RunAggregationQueryResponse + * @instance + */ + RunAggregationQueryResponse.prototype.explainMetrics = null; + + /** + * Creates a RunAggregationQueryResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.RunAggregationQueryResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.RunAggregationQueryResponse} RunAggregationQueryResponse + */ + RunAggregationQueryResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.RunAggregationQueryResponse) + return object; + var message = new $root.google.firestore.v1.RunAggregationQueryResponse(); + if (object.result != null) { + if (typeof object.result !== "object") + throw TypeError(".google.firestore.v1.RunAggregationQueryResponse.result: object expected"); + message.result = $root.google.firestore.v1.AggregationResult.fromObject(object.result); + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.RunAggregationQueryResponse.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.explainMetrics != null) { + if (typeof object.explainMetrics !== "object") + throw TypeError(".google.firestore.v1.RunAggregationQueryResponse.explainMetrics: object expected"); + message.explainMetrics = $root.google.firestore.v1.ExplainMetrics.fromObject(object.explainMetrics); + } + return message; + }; + + /** + * Creates a plain object from a RunAggregationQueryResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.RunAggregationQueryResponse + * @static + * @param {google.firestore.v1.RunAggregationQueryResponse} message RunAggregationQueryResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RunAggregationQueryResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.result = null; + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + object.readTime = null; + object.explainMetrics = null; + } + if (message.result != null && message.hasOwnProperty("result")) + object.result = $root.google.firestore.v1.AggregationResult.toObject(message.result, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (message.explainMetrics != null && message.hasOwnProperty("explainMetrics")) + object.explainMetrics = $root.google.firestore.v1.ExplainMetrics.toObject(message.explainMetrics, options); + return object; + }; + + /** + * Converts this RunAggregationQueryResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.RunAggregationQueryResponse + * @instance + * @returns {Object.} JSON object + */ + RunAggregationQueryResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RunAggregationQueryResponse + * @function getTypeUrl + * @memberof google.firestore.v1.RunAggregationQueryResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RunAggregationQueryResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.RunAggregationQueryResponse"; + }; + + return RunAggregationQueryResponse; + })(); + + v1.PartitionQueryRequest = (function() { + + /** + * Properties of a PartitionQueryRequest. + * @memberof google.firestore.v1 + * @interface IPartitionQueryRequest + * @property {string|null} [parent] PartitionQueryRequest parent + * @property {google.firestore.v1.IStructuredQuery|null} [structuredQuery] PartitionQueryRequest structuredQuery + * @property {number|string|null} [partitionCount] PartitionQueryRequest partitionCount + * @property {string|null} [pageToken] PartitionQueryRequest pageToken + * @property {number|null} [pageSize] PartitionQueryRequest pageSize + * @property {google.protobuf.ITimestamp|null} [readTime] PartitionQueryRequest readTime + */ + + /** + * Constructs a new PartitionQueryRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a PartitionQueryRequest. + * @implements IPartitionQueryRequest + * @constructor + * @param {google.firestore.v1.IPartitionQueryRequest=} [properties] Properties to set + */ + function PartitionQueryRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PartitionQueryRequest parent. + * @member {string} parent + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.parent = ""; + + /** + * PartitionQueryRequest structuredQuery. + * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.structuredQuery = null; + + /** + * PartitionQueryRequest partitionCount. + * @member {number|string} partitionCount + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.partitionCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * PartitionQueryRequest pageToken. + * @member {string} pageToken + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.pageToken = ""; + + /** + * PartitionQueryRequest pageSize. + * @member {number} pageSize + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.pageSize = 0; + + /** + * PartitionQueryRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.readTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * PartitionQueryRequest queryType. + * @member {"structuredQuery"|undefined} queryType + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + */ + Object.defineProperty(PartitionQueryRequest.prototype, "queryType", { + get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * PartitionQueryRequest consistencySelector. + * @member {"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + */ + Object.defineProperty(PartitionQueryRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.PartitionQueryRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.PartitionQueryRequest} PartitionQueryRequest + */ + PartitionQueryRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.PartitionQueryRequest) + return object; + var message = new $root.google.firestore.v1.PartitionQueryRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.structuredQuery != null) { + if (typeof object.structuredQuery !== "object") + throw TypeError(".google.firestore.v1.PartitionQueryRequest.structuredQuery: object expected"); + message.structuredQuery = $root.google.firestore.v1.StructuredQuery.fromObject(object.structuredQuery); + } + if (object.partitionCount != null) + if ($util.Long) + (message.partitionCount = $util.Long.fromValue(object.partitionCount)).unsigned = false; + else if (typeof object.partitionCount === "string") + message.partitionCount = parseInt(object.partitionCount, 10); + else if (typeof object.partitionCount === "number") + message.partitionCount = object.partitionCount; + else if (typeof object.partitionCount === "object") + message.partitionCount = new $util.LongBits(object.partitionCount.low >>> 0, object.partitionCount.high >>> 0).toNumber(); + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.PartitionQueryRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.PartitionQueryRequest + * @static + * @param {google.firestore.v1.PartitionQueryRequest} message PartitionQueryRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartitionQueryRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.partitionCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.partitionCount = options.longs === String ? "0" : 0; + object.pageToken = ""; + object.pageSize = 0; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { + object.structuredQuery = $root.google.firestore.v1.StructuredQuery.toObject(message.structuredQuery, options); + if (options.oneofs) + object.queryType = "structuredQuery"; + } + if (message.partitionCount != null && message.hasOwnProperty("partitionCount")) + if (typeof message.partitionCount === "number") + object.partitionCount = options.longs === String ? String(message.partitionCount) : message.partitionCount; + else + object.partitionCount = options.longs === String ? $util.Long.prototype.toString.call(message.partitionCount) : options.longs === Number ? new $util.LongBits(message.partitionCount.low >>> 0, message.partitionCount.high >>> 0).toNumber() : message.partitionCount; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + return object; + }; + + /** + * Converts this PartitionQueryRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + * @returns {Object.} JSON object + */ + PartitionQueryRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartitionQueryRequest + * @function getTypeUrl + * @memberof google.firestore.v1.PartitionQueryRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartitionQueryRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.PartitionQueryRequest"; + }; + + return PartitionQueryRequest; + })(); + + v1.PartitionQueryResponse = (function() { + + /** + * Properties of a PartitionQueryResponse. + * @memberof google.firestore.v1 + * @interface IPartitionQueryResponse + * @property {Array.|null} [partitions] PartitionQueryResponse partitions + * @property {string|null} [nextPageToken] PartitionQueryResponse nextPageToken + */ + + /** + * Constructs a new PartitionQueryResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a PartitionQueryResponse. + * @implements IPartitionQueryResponse + * @constructor + * @param {google.firestore.v1.IPartitionQueryResponse=} [properties] Properties to set + */ + function PartitionQueryResponse(properties) { + this.partitions = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PartitionQueryResponse partitions. + * @member {Array.} partitions + * @memberof google.firestore.v1.PartitionQueryResponse + * @instance + */ + PartitionQueryResponse.prototype.partitions = $util.emptyArray; + + /** + * PartitionQueryResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.firestore.v1.PartitionQueryResponse + * @instance + */ + PartitionQueryResponse.prototype.nextPageToken = ""; + + /** + * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.PartitionQueryResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.PartitionQueryResponse} PartitionQueryResponse + */ + PartitionQueryResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.PartitionQueryResponse) + return object; + var message = new $root.google.firestore.v1.PartitionQueryResponse(); + if (object.partitions) { + if (!Array.isArray(object.partitions)) + throw TypeError(".google.firestore.v1.PartitionQueryResponse.partitions: array expected"); + message.partitions = []; + for (var i = 0; i < object.partitions.length; ++i) { + if (typeof object.partitions[i] !== "object") + throw TypeError(".google.firestore.v1.PartitionQueryResponse.partitions: object expected"); + message.partitions[i] = $root.google.firestore.v1.Cursor.fromObject(object.partitions[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.PartitionQueryResponse + * @static + * @param {google.firestore.v1.PartitionQueryResponse} message PartitionQueryResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartitionQueryResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.partitions = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.partitions && message.partitions.length) { + object.partitions = []; + for (var j = 0; j < message.partitions.length; ++j) + object.partitions[j] = $root.google.firestore.v1.Cursor.toObject(message.partitions[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this PartitionQueryResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.PartitionQueryResponse + * @instance + * @returns {Object.} JSON object + */ + PartitionQueryResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartitionQueryResponse + * @function getTypeUrl + * @memberof google.firestore.v1.PartitionQueryResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartitionQueryResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.PartitionQueryResponse"; + }; + + return PartitionQueryResponse; + })(); + + v1.WriteRequest = (function() { + + /** + * Properties of a WriteRequest. + * @memberof google.firestore.v1 + * @interface IWriteRequest + * @property {string|null} [database] WriteRequest database + * @property {string|null} [streamId] WriteRequest streamId + * @property {Array.|null} [writes] WriteRequest writes + * @property {Uint8Array|null} [streamToken] WriteRequest streamToken + * @property {Object.|null} [labels] WriteRequest labels + */ + + /** + * Constructs a new WriteRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a WriteRequest. + * @implements IWriteRequest + * @constructor + * @param {google.firestore.v1.IWriteRequest=} [properties] Properties to set + */ + function WriteRequest(properties) { + this.writes = []; + this.labels = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * WriteRequest database. + * @member {string} database + * @memberof google.firestore.v1.WriteRequest + * @instance + */ + WriteRequest.prototype.database = ""; + + /** + * WriteRequest streamId. + * @member {string} streamId + * @memberof google.firestore.v1.WriteRequest + * @instance + */ + WriteRequest.prototype.streamId = ""; + + /** + * WriteRequest writes. + * @member {Array.} writes + * @memberof google.firestore.v1.WriteRequest + * @instance + */ + WriteRequest.prototype.writes = $util.emptyArray; + + /** + * WriteRequest streamToken. + * @member {Uint8Array} streamToken + * @memberof google.firestore.v1.WriteRequest + * @instance + */ + WriteRequest.prototype.streamToken = $util.newBuffer([]); + + /** + * WriteRequest labels. + * @member {Object.} labels + * @memberof google.firestore.v1.WriteRequest + * @instance + */ + WriteRequest.prototype.labels = $util.emptyObject; + + /** + * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.WriteRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.WriteRequest} WriteRequest + */ + WriteRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.WriteRequest) + return object; + var message = new $root.google.firestore.v1.WriteRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.streamId != null) + message.streamId = String(object.streamId); + if (object.writes) { + if (!Array.isArray(object.writes)) + throw TypeError(".google.firestore.v1.WriteRequest.writes: array expected"); + message.writes = []; + for (var i = 0; i < object.writes.length; ++i) { + if (typeof object.writes[i] !== "object") + throw TypeError(".google.firestore.v1.WriteRequest.writes: object expected"); + message.writes[i] = $root.google.firestore.v1.Write.fromObject(object.writes[i]); + } + } + if (object.streamToken != null) + if (typeof object.streamToken === "string") + $util.base64.decode(object.streamToken, message.streamToken = $util.newBuffer($util.base64.length(object.streamToken)), 0); + else if (object.streamToken.length >= 0) + message.streamToken = object.streamToken; + if (object.labels) { + if (typeof object.labels !== "object") + throw TypeError(".google.firestore.v1.WriteRequest.labels: object expected"); + message.labels = {}; + for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) + message.labels[keys[i]] = String(object.labels[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.WriteRequest + * @static + * @param {google.firestore.v1.WriteRequest} message WriteRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WriteRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.writes = []; + if (options.objects || options.defaults) + object.labels = {}; + if (options.defaults) { + object.database = ""; + object.streamId = ""; + if (options.bytes === String) + object.streamToken = ""; + else { + object.streamToken = []; + if (options.bytes !== Array) + object.streamToken = $util.newBuffer(object.streamToken); + } + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.streamId != null && message.hasOwnProperty("streamId")) + object.streamId = message.streamId; + if (message.writes && message.writes.length) { + object.writes = []; + for (var j = 0; j < message.writes.length; ++j) + object.writes[j] = $root.google.firestore.v1.Write.toObject(message.writes[j], options); + } + if (message.streamToken != null && message.hasOwnProperty("streamToken")) + object.streamToken = options.bytes === String ? $util.base64.encode(message.streamToken, 0, message.streamToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.streamToken) : message.streamToken; + var keys2; + if (message.labels && (keys2 = Object.keys(message.labels)).length) { + object.labels = {}; + for (var j = 0; j < keys2.length; ++j) + object.labels[keys2[j]] = message.labels[keys2[j]]; + } + return object; + }; + + /** + * Converts this WriteRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.WriteRequest + * @instance + * @returns {Object.} JSON object + */ + WriteRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for WriteRequest + * @function getTypeUrl + * @memberof google.firestore.v1.WriteRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WriteRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.WriteRequest"; + }; + + return WriteRequest; + })(); + + v1.WriteResponse = (function() { + + /** + * Properties of a WriteResponse. + * @memberof google.firestore.v1 + * @interface IWriteResponse + * @property {string|null} [streamId] WriteResponse streamId + * @property {Uint8Array|null} [streamToken] WriteResponse streamToken + * @property {Array.|null} [writeResults] WriteResponse writeResults + * @property {google.protobuf.ITimestamp|null} [commitTime] WriteResponse commitTime + */ + + /** + * Constructs a new WriteResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a WriteResponse. + * @implements IWriteResponse + * @constructor + * @param {google.firestore.v1.IWriteResponse=} [properties] Properties to set + */ + function WriteResponse(properties) { + this.writeResults = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * WriteResponse streamId. + * @member {string} streamId + * @memberof google.firestore.v1.WriteResponse + * @instance + */ + WriteResponse.prototype.streamId = ""; + + /** + * WriteResponse streamToken. + * @member {Uint8Array} streamToken + * @memberof google.firestore.v1.WriteResponse + * @instance + */ + WriteResponse.prototype.streamToken = $util.newBuffer([]); + + /** + * WriteResponse writeResults. + * @member {Array.} writeResults + * @memberof google.firestore.v1.WriteResponse + * @instance + */ + WriteResponse.prototype.writeResults = $util.emptyArray; + + /** + * WriteResponse commitTime. + * @member {google.protobuf.ITimestamp|null|undefined} commitTime + * @memberof google.firestore.v1.WriteResponse + * @instance + */ + WriteResponse.prototype.commitTime = null; + + /** + * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.WriteResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.WriteResponse} WriteResponse + */ + WriteResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.WriteResponse) + return object; + var message = new $root.google.firestore.v1.WriteResponse(); + if (object.streamId != null) + message.streamId = String(object.streamId); + if (object.streamToken != null) + if (typeof object.streamToken === "string") + $util.base64.decode(object.streamToken, message.streamToken = $util.newBuffer($util.base64.length(object.streamToken)), 0); + else if (object.streamToken.length >= 0) + message.streamToken = object.streamToken; + if (object.writeResults) { + if (!Array.isArray(object.writeResults)) + throw TypeError(".google.firestore.v1.WriteResponse.writeResults: array expected"); + message.writeResults = []; + for (var i = 0; i < object.writeResults.length; ++i) { + if (typeof object.writeResults[i] !== "object") + throw TypeError(".google.firestore.v1.WriteResponse.writeResults: object expected"); + message.writeResults[i] = $root.google.firestore.v1.WriteResult.fromObject(object.writeResults[i]); + } + } + if (object.commitTime != null) { + if (typeof object.commitTime !== "object") + throw TypeError(".google.firestore.v1.WriteResponse.commitTime: object expected"); + message.commitTime = $root.google.protobuf.Timestamp.fromObject(object.commitTime); + } + return message; + }; + + /** + * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.WriteResponse + * @static + * @param {google.firestore.v1.WriteResponse} message WriteResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WriteResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.writeResults = []; + if (options.defaults) { + object.streamId = ""; + if (options.bytes === String) + object.streamToken = ""; + else { + object.streamToken = []; + if (options.bytes !== Array) + object.streamToken = $util.newBuffer(object.streamToken); + } + object.commitTime = null; + } + if (message.streamId != null && message.hasOwnProperty("streamId")) + object.streamId = message.streamId; + if (message.streamToken != null && message.hasOwnProperty("streamToken")) + object.streamToken = options.bytes === String ? $util.base64.encode(message.streamToken, 0, message.streamToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.streamToken) : message.streamToken; + if (message.writeResults && message.writeResults.length) { + object.writeResults = []; + for (var j = 0; j < message.writeResults.length; ++j) + object.writeResults[j] = $root.google.firestore.v1.WriteResult.toObject(message.writeResults[j], options); + } + if (message.commitTime != null && message.hasOwnProperty("commitTime")) + object.commitTime = $root.google.protobuf.Timestamp.toObject(message.commitTime, options); + return object; + }; + + /** + * Converts this WriteResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.WriteResponse + * @instance + * @returns {Object.} JSON object + */ + WriteResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for WriteResponse + * @function getTypeUrl + * @memberof google.firestore.v1.WriteResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WriteResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.WriteResponse"; + }; + + return WriteResponse; + })(); + + v1.ListenRequest = (function() { + + /** + * Properties of a ListenRequest. + * @memberof google.firestore.v1 + * @interface IListenRequest + * @property {string|null} [database] ListenRequest database + * @property {google.firestore.v1.ITarget|null} [addTarget] ListenRequest addTarget + * @property {number|null} [removeTarget] ListenRequest removeTarget + * @property {Object.|null} [labels] ListenRequest labels + */ + + /** + * Constructs a new ListenRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a ListenRequest. + * @implements IListenRequest + * @constructor + * @param {google.firestore.v1.IListenRequest=} [properties] Properties to set + */ + function ListenRequest(properties) { + this.labels = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListenRequest database. + * @member {string} database + * @memberof google.firestore.v1.ListenRequest + * @instance + */ + ListenRequest.prototype.database = ""; + + /** + * ListenRequest addTarget. + * @member {google.firestore.v1.ITarget|null|undefined} addTarget + * @memberof google.firestore.v1.ListenRequest + * @instance + */ + ListenRequest.prototype.addTarget = null; + + /** + * ListenRequest removeTarget. + * @member {number|null|undefined} removeTarget + * @memberof google.firestore.v1.ListenRequest + * @instance + */ + ListenRequest.prototype.removeTarget = null; + + /** + * ListenRequest labels. + * @member {Object.} labels + * @memberof google.firestore.v1.ListenRequest + * @instance + */ + ListenRequest.prototype.labels = $util.emptyObject; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ListenRequest targetChange. + * @member {"addTarget"|"removeTarget"|undefined} targetChange + * @memberof google.firestore.v1.ListenRequest + * @instance + */ + Object.defineProperty(ListenRequest.prototype, "targetChange", { + get: $util.oneOfGetter($oneOfFields = ["addTarget", "removeTarget"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ListenRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ListenRequest} ListenRequest + */ + ListenRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ListenRequest) + return object; + var message = new $root.google.firestore.v1.ListenRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.addTarget != null) { + if (typeof object.addTarget !== "object") + throw TypeError(".google.firestore.v1.ListenRequest.addTarget: object expected"); + message.addTarget = $root.google.firestore.v1.Target.fromObject(object.addTarget); + } + if (object.removeTarget != null) + message.removeTarget = object.removeTarget | 0; + if (object.labels) { + if (typeof object.labels !== "object") + throw TypeError(".google.firestore.v1.ListenRequest.labels: object expected"); + message.labels = {}; + for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) + message.labels[keys[i]] = String(object.labels[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ListenRequest + * @static + * @param {google.firestore.v1.ListenRequest} message ListenRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListenRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.labels = {}; + if (options.defaults) + object.database = ""; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.addTarget != null && message.hasOwnProperty("addTarget")) { + object.addTarget = $root.google.firestore.v1.Target.toObject(message.addTarget, options); + if (options.oneofs) + object.targetChange = "addTarget"; + } + if (message.removeTarget != null && message.hasOwnProperty("removeTarget")) { + object.removeTarget = message.removeTarget; + if (options.oneofs) + object.targetChange = "removeTarget"; + } + var keys2; + if (message.labels && (keys2 = Object.keys(message.labels)).length) { + object.labels = {}; + for (var j = 0; j < keys2.length; ++j) + object.labels[keys2[j]] = message.labels[keys2[j]]; + } + return object; + }; + + /** + * Converts this ListenRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.ListenRequest + * @instance + * @returns {Object.} JSON object + */ + ListenRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListenRequest + * @function getTypeUrl + * @memberof google.firestore.v1.ListenRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListenRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ListenRequest"; + }; + + return ListenRequest; + })(); + + v1.ListenResponse = (function() { + + /** + * Properties of a ListenResponse. + * @memberof google.firestore.v1 + * @interface IListenResponse + * @property {google.firestore.v1.ITargetChange|null} [targetChange] ListenResponse targetChange + * @property {google.firestore.v1.IDocumentChange|null} [documentChange] ListenResponse documentChange + * @property {google.firestore.v1.IDocumentDelete|null} [documentDelete] ListenResponse documentDelete + * @property {google.firestore.v1.IDocumentRemove|null} [documentRemove] ListenResponse documentRemove + * @property {google.firestore.v1.IExistenceFilter|null} [filter] ListenResponse filter + */ + + /** + * Constructs a new ListenResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a ListenResponse. + * @implements IListenResponse + * @constructor + * @param {google.firestore.v1.IListenResponse=} [properties] Properties to set + */ + function ListenResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListenResponse targetChange. + * @member {google.firestore.v1.ITargetChange|null|undefined} targetChange + * @memberof google.firestore.v1.ListenResponse + * @instance + */ + ListenResponse.prototype.targetChange = null; + + /** + * ListenResponse documentChange. + * @member {google.firestore.v1.IDocumentChange|null|undefined} documentChange + * @memberof google.firestore.v1.ListenResponse + * @instance + */ + ListenResponse.prototype.documentChange = null; + + /** + * ListenResponse documentDelete. + * @member {google.firestore.v1.IDocumentDelete|null|undefined} documentDelete + * @memberof google.firestore.v1.ListenResponse + * @instance + */ + ListenResponse.prototype.documentDelete = null; + + /** + * ListenResponse documentRemove. + * @member {google.firestore.v1.IDocumentRemove|null|undefined} documentRemove + * @memberof google.firestore.v1.ListenResponse + * @instance + */ + ListenResponse.prototype.documentRemove = null; + + /** + * ListenResponse filter. + * @member {google.firestore.v1.IExistenceFilter|null|undefined} filter + * @memberof google.firestore.v1.ListenResponse + * @instance + */ + ListenResponse.prototype.filter = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ListenResponse responseType. + * @member {"targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"|undefined} responseType + * @memberof google.firestore.v1.ListenResponse + * @instance + */ + Object.defineProperty(ListenResponse.prototype, "responseType", { + get: $util.oneOfGetter($oneOfFields = ["targetChange", "documentChange", "documentDelete", "documentRemove", "filter"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ListenResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ListenResponse} ListenResponse + */ + ListenResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ListenResponse) + return object; + var message = new $root.google.firestore.v1.ListenResponse(); + if (object.targetChange != null) { + if (typeof object.targetChange !== "object") + throw TypeError(".google.firestore.v1.ListenResponse.targetChange: object expected"); + message.targetChange = $root.google.firestore.v1.TargetChange.fromObject(object.targetChange); + } + if (object.documentChange != null) { + if (typeof object.documentChange !== "object") + throw TypeError(".google.firestore.v1.ListenResponse.documentChange: object expected"); + message.documentChange = $root.google.firestore.v1.DocumentChange.fromObject(object.documentChange); + } + if (object.documentDelete != null) { + if (typeof object.documentDelete !== "object") + throw TypeError(".google.firestore.v1.ListenResponse.documentDelete: object expected"); + message.documentDelete = $root.google.firestore.v1.DocumentDelete.fromObject(object.documentDelete); + } + if (object.documentRemove != null) { + if (typeof object.documentRemove !== "object") + throw TypeError(".google.firestore.v1.ListenResponse.documentRemove: object expected"); + message.documentRemove = $root.google.firestore.v1.DocumentRemove.fromObject(object.documentRemove); + } + if (object.filter != null) { + if (typeof object.filter !== "object") + throw TypeError(".google.firestore.v1.ListenResponse.filter: object expected"); + message.filter = $root.google.firestore.v1.ExistenceFilter.fromObject(object.filter); + } + return message; + }; + + /** + * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ListenResponse + * @static + * @param {google.firestore.v1.ListenResponse} message ListenResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListenResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.targetChange != null && message.hasOwnProperty("targetChange")) { + object.targetChange = $root.google.firestore.v1.TargetChange.toObject(message.targetChange, options); + if (options.oneofs) + object.responseType = "targetChange"; + } + if (message.documentChange != null && message.hasOwnProperty("documentChange")) { + object.documentChange = $root.google.firestore.v1.DocumentChange.toObject(message.documentChange, options); + if (options.oneofs) + object.responseType = "documentChange"; + } + if (message.documentDelete != null && message.hasOwnProperty("documentDelete")) { + object.documentDelete = $root.google.firestore.v1.DocumentDelete.toObject(message.documentDelete, options); + if (options.oneofs) + object.responseType = "documentDelete"; + } + if (message.filter != null && message.hasOwnProperty("filter")) { + object.filter = $root.google.firestore.v1.ExistenceFilter.toObject(message.filter, options); + if (options.oneofs) + object.responseType = "filter"; + } + if (message.documentRemove != null && message.hasOwnProperty("documentRemove")) { + object.documentRemove = $root.google.firestore.v1.DocumentRemove.toObject(message.documentRemove, options); + if (options.oneofs) + object.responseType = "documentRemove"; + } + return object; + }; + + /** + * Converts this ListenResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.ListenResponse + * @instance + * @returns {Object.} JSON object + */ + ListenResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListenResponse + * @function getTypeUrl + * @memberof google.firestore.v1.ListenResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListenResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ListenResponse"; + }; + + return ListenResponse; + })(); + + v1.Target = (function() { + + /** + * Properties of a Target. + * @memberof google.firestore.v1 + * @interface ITarget + * @property {google.firestore.v1.Target.IQueryTarget|null} [query] Target query + * @property {google.firestore.v1.Target.IDocumentsTarget|null} [documents] Target documents + * @property {Uint8Array|null} [resumeToken] Target resumeToken + * @property {google.protobuf.ITimestamp|null} [readTime] Target readTime + * @property {number|null} [targetId] Target targetId + * @property {boolean|null} [once] Target once + * @property {google.protobuf.IInt32Value|null} [expectedCount] Target expectedCount + */ + + /** + * Constructs a new Target. + * @memberof google.firestore.v1 + * @classdesc Represents a Target. + * @implements ITarget + * @constructor + * @param {google.firestore.v1.ITarget=} [properties] Properties to set + */ + function Target(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Target query. + * @member {google.firestore.v1.Target.IQueryTarget|null|undefined} query + * @memberof google.firestore.v1.Target + * @instance + */ + Target.prototype.query = null; + + /** + * Target documents. + * @member {google.firestore.v1.Target.IDocumentsTarget|null|undefined} documents + * @memberof google.firestore.v1.Target + * @instance + */ + Target.prototype.documents = null; + + /** + * Target resumeToken. + * @member {Uint8Array|null|undefined} resumeToken + * @memberof google.firestore.v1.Target + * @instance + */ + Target.prototype.resumeToken = null; + + /** + * Target readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.Target + * @instance + */ + Target.prototype.readTime = null; + + /** + * Target targetId. + * @member {number} targetId + * @memberof google.firestore.v1.Target + * @instance + */ + Target.prototype.targetId = 0; + + /** + * Target once. + * @member {boolean} once + * @memberof google.firestore.v1.Target + * @instance + */ + Target.prototype.once = false; + + /** + * Target expectedCount. + * @member {google.protobuf.IInt32Value|null|undefined} expectedCount + * @memberof google.firestore.v1.Target + * @instance + */ + Target.prototype.expectedCount = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Target targetType. + * @member {"query"|"documents"|undefined} targetType + * @memberof google.firestore.v1.Target + * @instance + */ + Object.defineProperty(Target.prototype, "targetType", { + get: $util.oneOfGetter($oneOfFields = ["query", "documents"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Target resumeType. + * @member {"resumeToken"|"readTime"|undefined} resumeType + * @memberof google.firestore.v1.Target + * @instance + */ + Object.defineProperty(Target.prototype, "resumeType", { + get: $util.oneOfGetter($oneOfFields = ["resumeToken", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a Target message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Target + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Target} Target + */ + Target.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Target) + return object; + var message = new $root.google.firestore.v1.Target(); + if (object.query != null) { + if (typeof object.query !== "object") + throw TypeError(".google.firestore.v1.Target.query: object expected"); + message.query = $root.google.firestore.v1.Target.QueryTarget.fromObject(object.query); + } + if (object.documents != null) { + if (typeof object.documents !== "object") + throw TypeError(".google.firestore.v1.Target.documents: object expected"); + message.documents = $root.google.firestore.v1.Target.DocumentsTarget.fromObject(object.documents); + } + if (object.resumeToken != null) + if (typeof object.resumeToken === "string") + $util.base64.decode(object.resumeToken, message.resumeToken = $util.newBuffer($util.base64.length(object.resumeToken)), 0); + else if (object.resumeToken.length >= 0) + message.resumeToken = object.resumeToken; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.Target.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.targetId != null) + message.targetId = object.targetId | 0; + if (object.once != null) + message.once = Boolean(object.once); + if (object.expectedCount != null) { + if (typeof object.expectedCount !== "object") + throw TypeError(".google.firestore.v1.Target.expectedCount: object expected"); + message.expectedCount = $root.google.protobuf.Int32Value.fromObject(object.expectedCount); + } + return message; + }; + + /** + * Creates a plain object from a Target message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Target + * @static + * @param {google.firestore.v1.Target} message Target + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Target.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.targetId = 0; + object.once = false; + object.expectedCount = null; + } + if (message.query != null && message.hasOwnProperty("query")) { + object.query = $root.google.firestore.v1.Target.QueryTarget.toObject(message.query, options); + if (options.oneofs) + object.targetType = "query"; + } + if (message.documents != null && message.hasOwnProperty("documents")) { + object.documents = $root.google.firestore.v1.Target.DocumentsTarget.toObject(message.documents, options); + if (options.oneofs) + object.targetType = "documents"; + } + if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) { + object.resumeToken = options.bytes === String ? $util.base64.encode(message.resumeToken, 0, message.resumeToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.resumeToken) : message.resumeToken; + if (options.oneofs) + object.resumeType = "resumeToken"; + } + if (message.targetId != null && message.hasOwnProperty("targetId")) + object.targetId = message.targetId; + if (message.once != null && message.hasOwnProperty("once")) + object.once = message.once; + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.resumeType = "readTime"; + } + if (message.expectedCount != null && message.hasOwnProperty("expectedCount")) + object.expectedCount = $root.google.protobuf.Int32Value.toObject(message.expectedCount, options); + return object; + }; + + /** + * Converts this Target to JSON. + * @function toJSON + * @memberof google.firestore.v1.Target + * @instance + * @returns {Object.} JSON object + */ + Target.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Target + * @function getTypeUrl + * @memberof google.firestore.v1.Target + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Target.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Target"; + }; + + Target.DocumentsTarget = (function() { + + /** + * Properties of a DocumentsTarget. + * @memberof google.firestore.v1.Target + * @interface IDocumentsTarget + * @property {Array.|null} [documents] DocumentsTarget documents + */ + + /** + * Constructs a new DocumentsTarget. + * @memberof google.firestore.v1.Target + * @classdesc Represents a DocumentsTarget. + * @implements IDocumentsTarget + * @constructor + * @param {google.firestore.v1.Target.IDocumentsTarget=} [properties] Properties to set + */ + function DocumentsTarget(properties) { + this.documents = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DocumentsTarget documents. + * @member {Array.} documents + * @memberof google.firestore.v1.Target.DocumentsTarget + * @instance + */ + DocumentsTarget.prototype.documents = $util.emptyArray; + + /** + * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Target.DocumentsTarget + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Target.DocumentsTarget} DocumentsTarget + */ + DocumentsTarget.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Target.DocumentsTarget) + return object; + var message = new $root.google.firestore.v1.Target.DocumentsTarget(); + if (object.documents) { + if (!Array.isArray(object.documents)) + throw TypeError(".google.firestore.v1.Target.DocumentsTarget.documents: array expected"); + message.documents = []; + for (var i = 0; i < object.documents.length; ++i) + message.documents[i] = String(object.documents[i]); + } + return message; + }; + + /** + * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Target.DocumentsTarget + * @static + * @param {google.firestore.v1.Target.DocumentsTarget} message DocumentsTarget + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DocumentsTarget.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.documents = []; + if (message.documents && message.documents.length) { + object.documents = []; + for (var j = 0; j < message.documents.length; ++j) + object.documents[j] = message.documents[j]; + } + return object; + }; + + /** + * Converts this DocumentsTarget to JSON. + * @function toJSON + * @memberof google.firestore.v1.Target.DocumentsTarget + * @instance + * @returns {Object.} JSON object + */ + DocumentsTarget.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DocumentsTarget + * @function getTypeUrl + * @memberof google.firestore.v1.Target.DocumentsTarget + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DocumentsTarget.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Target.DocumentsTarget"; + }; + + return DocumentsTarget; + })(); + + Target.QueryTarget = (function() { + + /** + * Properties of a QueryTarget. + * @memberof google.firestore.v1.Target + * @interface IQueryTarget + * @property {string|null} [parent] QueryTarget parent + * @property {google.firestore.v1.IStructuredQuery|null} [structuredQuery] QueryTarget structuredQuery + */ + + /** + * Constructs a new QueryTarget. + * @memberof google.firestore.v1.Target + * @classdesc Represents a QueryTarget. + * @implements IQueryTarget + * @constructor + * @param {google.firestore.v1.Target.IQueryTarget=} [properties] Properties to set + */ + function QueryTarget(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * QueryTarget parent. + * @member {string} parent + * @memberof google.firestore.v1.Target.QueryTarget + * @instance + */ + QueryTarget.prototype.parent = ""; + + /** + * QueryTarget structuredQuery. + * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery + * @memberof google.firestore.v1.Target.QueryTarget + * @instance + */ + QueryTarget.prototype.structuredQuery = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * QueryTarget queryType. + * @member {"structuredQuery"|undefined} queryType + * @memberof google.firestore.v1.Target.QueryTarget + * @instance + */ + Object.defineProperty(QueryTarget.prototype, "queryType", { + get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Target.QueryTarget + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Target.QueryTarget} QueryTarget + */ + QueryTarget.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Target.QueryTarget) + return object; + var message = new $root.google.firestore.v1.Target.QueryTarget(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.structuredQuery != null) { + if (typeof object.structuredQuery !== "object") + throw TypeError(".google.firestore.v1.Target.QueryTarget.structuredQuery: object expected"); + message.structuredQuery = $root.google.firestore.v1.StructuredQuery.fromObject(object.structuredQuery); + } + return message; + }; + + /** + * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Target.QueryTarget + * @static + * @param {google.firestore.v1.Target.QueryTarget} message QueryTarget + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + QueryTarget.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.parent = ""; + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { + object.structuredQuery = $root.google.firestore.v1.StructuredQuery.toObject(message.structuredQuery, options); + if (options.oneofs) + object.queryType = "structuredQuery"; + } + return object; + }; + + /** + * Converts this QueryTarget to JSON. + * @function toJSON + * @memberof google.firestore.v1.Target.QueryTarget + * @instance + * @returns {Object.} JSON object + */ + QueryTarget.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for QueryTarget + * @function getTypeUrl + * @memberof google.firestore.v1.Target.QueryTarget + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + QueryTarget.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Target.QueryTarget"; + }; + + return QueryTarget; + })(); + + return Target; + })(); + + v1.TargetChange = (function() { + + /** + * Properties of a TargetChange. + * @memberof google.firestore.v1 + * @interface ITargetChange + * @property {google.firestore.v1.TargetChange.TargetChangeType|null} [targetChangeType] TargetChange targetChangeType + * @property {Array.|null} [targetIds] TargetChange targetIds + * @property {google.rpc.IStatus|null} [cause] TargetChange cause + * @property {Uint8Array|null} [resumeToken] TargetChange resumeToken + * @property {google.protobuf.ITimestamp|null} [readTime] TargetChange readTime + */ + + /** + * Constructs a new TargetChange. + * @memberof google.firestore.v1 + * @classdesc Represents a TargetChange. + * @implements ITargetChange + * @constructor + * @param {google.firestore.v1.ITargetChange=} [properties] Properties to set + */ + function TargetChange(properties) { + this.targetIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TargetChange targetChangeType. + * @member {google.firestore.v1.TargetChange.TargetChangeType} targetChangeType + * @memberof google.firestore.v1.TargetChange + * @instance + */ + TargetChange.prototype.targetChangeType = 0; + + /** + * TargetChange targetIds. + * @member {Array.} targetIds + * @memberof google.firestore.v1.TargetChange + * @instance + */ + TargetChange.prototype.targetIds = $util.emptyArray; + + /** + * TargetChange cause. + * @member {google.rpc.IStatus|null|undefined} cause + * @memberof google.firestore.v1.TargetChange + * @instance + */ + TargetChange.prototype.cause = null; + + /** + * TargetChange resumeToken. + * @member {Uint8Array} resumeToken + * @memberof google.firestore.v1.TargetChange + * @instance + */ + TargetChange.prototype.resumeToken = $util.newBuffer([]); + + /** + * TargetChange readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.TargetChange + * @instance + */ + TargetChange.prototype.readTime = null; + + /** + * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.TargetChange + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.TargetChange} TargetChange + */ + TargetChange.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.TargetChange) + return object; + var message = new $root.google.firestore.v1.TargetChange(); + switch (object.targetChangeType) { + default: + if (typeof object.targetChangeType === "number") { + message.targetChangeType = object.targetChangeType; + break; + } + break; + case "NO_CHANGE": + case 0: + message.targetChangeType = 0; + break; + case "ADD": + case 1: + message.targetChangeType = 1; + break; + case "REMOVE": + case 2: + message.targetChangeType = 2; + break; + case "CURRENT": + case 3: + message.targetChangeType = 3; + break; + case "RESET": + case 4: + message.targetChangeType = 4; + break; + } + if (object.targetIds) { + if (!Array.isArray(object.targetIds)) + throw TypeError(".google.firestore.v1.TargetChange.targetIds: array expected"); + message.targetIds = []; + for (var i = 0; i < object.targetIds.length; ++i) + message.targetIds[i] = object.targetIds[i] | 0; + } + if (object.cause != null) { + if (typeof object.cause !== "object") + throw TypeError(".google.firestore.v1.TargetChange.cause: object expected"); + message.cause = $root.google.rpc.Status.fromObject(object.cause); + } + if (object.resumeToken != null) + if (typeof object.resumeToken === "string") + $util.base64.decode(object.resumeToken, message.resumeToken = $util.newBuffer($util.base64.length(object.resumeToken)), 0); + else if (object.resumeToken.length >= 0) + message.resumeToken = object.resumeToken; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.TargetChange.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a TargetChange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.TargetChange + * @static + * @param {google.firestore.v1.TargetChange} message TargetChange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TargetChange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.targetIds = []; + if (options.defaults) { + object.targetChangeType = options.enums === String ? "NO_CHANGE" : 0; + object.cause = null; + if (options.bytes === String) + object.resumeToken = ""; + else { + object.resumeToken = []; + if (options.bytes !== Array) + object.resumeToken = $util.newBuffer(object.resumeToken); + } + object.readTime = null; + } + if (message.targetChangeType != null && message.hasOwnProperty("targetChangeType")) + object.targetChangeType = options.enums === String ? $root.google.firestore.v1.TargetChange.TargetChangeType[message.targetChangeType] === undefined ? message.targetChangeType : $root.google.firestore.v1.TargetChange.TargetChangeType[message.targetChangeType] : message.targetChangeType; + if (message.targetIds && message.targetIds.length) { + object.targetIds = []; + for (var j = 0; j < message.targetIds.length; ++j) + object.targetIds[j] = message.targetIds[j]; + } + if (message.cause != null && message.hasOwnProperty("cause")) + object.cause = $root.google.rpc.Status.toObject(message.cause, options); + if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) + object.resumeToken = options.bytes === String ? $util.base64.encode(message.resumeToken, 0, message.resumeToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.resumeToken) : message.resumeToken; + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + return object; + }; + + /** + * Converts this TargetChange to JSON. + * @function toJSON + * @memberof google.firestore.v1.TargetChange + * @instance + * @returns {Object.} JSON object + */ + TargetChange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TargetChange + * @function getTypeUrl + * @memberof google.firestore.v1.TargetChange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TargetChange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.TargetChange"; + }; + + /** + * TargetChangeType enum. + * @name google.firestore.v1.TargetChange.TargetChangeType + * @enum {string} + * @property {string} NO_CHANGE=NO_CHANGE NO_CHANGE value + * @property {string} ADD=ADD ADD value + * @property {string} REMOVE=REMOVE REMOVE value + * @property {string} CURRENT=CURRENT CURRENT value + * @property {string} RESET=RESET RESET value + */ + TargetChange.TargetChangeType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "NO_CHANGE"] = "NO_CHANGE"; + values[valuesById[1] = "ADD"] = "ADD"; + values[valuesById[2] = "REMOVE"] = "REMOVE"; + values[valuesById[3] = "CURRENT"] = "CURRENT"; + values[valuesById[4] = "RESET"] = "RESET"; + return values; + })(); + + return TargetChange; + })(); + + v1.ListCollectionIdsRequest = (function() { + + /** + * Properties of a ListCollectionIdsRequest. + * @memberof google.firestore.v1 + * @interface IListCollectionIdsRequest + * @property {string|null} [parent] ListCollectionIdsRequest parent + * @property {number|null} [pageSize] ListCollectionIdsRequest pageSize + * @property {string|null} [pageToken] ListCollectionIdsRequest pageToken + * @property {google.protobuf.ITimestamp|null} [readTime] ListCollectionIdsRequest readTime + */ + + /** + * Constructs a new ListCollectionIdsRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a ListCollectionIdsRequest. + * @implements IListCollectionIdsRequest + * @constructor + * @param {google.firestore.v1.IListCollectionIdsRequest=} [properties] Properties to set + */ + function ListCollectionIdsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListCollectionIdsRequest parent. + * @member {string} parent + * @memberof google.firestore.v1.ListCollectionIdsRequest + * @instance + */ + ListCollectionIdsRequest.prototype.parent = ""; + + /** + * ListCollectionIdsRequest pageSize. + * @member {number} pageSize + * @memberof google.firestore.v1.ListCollectionIdsRequest + * @instance + */ + ListCollectionIdsRequest.prototype.pageSize = 0; + + /** + * ListCollectionIdsRequest pageToken. + * @member {string} pageToken + * @memberof google.firestore.v1.ListCollectionIdsRequest + * @instance + */ + ListCollectionIdsRequest.prototype.pageToken = ""; + + /** + * ListCollectionIdsRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.ListCollectionIdsRequest + * @instance + */ + ListCollectionIdsRequest.prototype.readTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ListCollectionIdsRequest consistencySelector. + * @member {"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.ListCollectionIdsRequest + * @instance + */ + Object.defineProperty(ListCollectionIdsRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ListCollectionIdsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ListCollectionIdsRequest} ListCollectionIdsRequest + */ + ListCollectionIdsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ListCollectionIdsRequest) + return object; + var message = new $root.google.firestore.v1.ListCollectionIdsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.ListCollectionIdsRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ListCollectionIdsRequest + * @static + * @param {google.firestore.v1.ListCollectionIdsRequest} message ListCollectionIdsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListCollectionIdsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + return object; + }; + + /** + * Converts this ListCollectionIdsRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.ListCollectionIdsRequest + * @instance + * @returns {Object.} JSON object + */ + ListCollectionIdsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListCollectionIdsRequest + * @function getTypeUrl + * @memberof google.firestore.v1.ListCollectionIdsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListCollectionIdsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ListCollectionIdsRequest"; + }; + + return ListCollectionIdsRequest; + })(); + + v1.ListCollectionIdsResponse = (function() { + + /** + * Properties of a ListCollectionIdsResponse. + * @memberof google.firestore.v1 + * @interface IListCollectionIdsResponse + * @property {Array.|null} [collectionIds] ListCollectionIdsResponse collectionIds + * @property {string|null} [nextPageToken] ListCollectionIdsResponse nextPageToken + */ + + /** + * Constructs a new ListCollectionIdsResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a ListCollectionIdsResponse. + * @implements IListCollectionIdsResponse + * @constructor + * @param {google.firestore.v1.IListCollectionIdsResponse=} [properties] Properties to set + */ + function ListCollectionIdsResponse(properties) { + this.collectionIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListCollectionIdsResponse collectionIds. + * @member {Array.} collectionIds + * @memberof google.firestore.v1.ListCollectionIdsResponse + * @instance + */ + ListCollectionIdsResponse.prototype.collectionIds = $util.emptyArray; + + /** + * ListCollectionIdsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.firestore.v1.ListCollectionIdsResponse + * @instance + */ + ListCollectionIdsResponse.prototype.nextPageToken = ""; + + /** + * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ListCollectionIdsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ListCollectionIdsResponse} ListCollectionIdsResponse + */ + ListCollectionIdsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ListCollectionIdsResponse) + return object; + var message = new $root.google.firestore.v1.ListCollectionIdsResponse(); + if (object.collectionIds) { + if (!Array.isArray(object.collectionIds)) + throw TypeError(".google.firestore.v1.ListCollectionIdsResponse.collectionIds: array expected"); + message.collectionIds = []; + for (var i = 0; i < object.collectionIds.length; ++i) + message.collectionIds[i] = String(object.collectionIds[i]); + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ListCollectionIdsResponse + * @static + * @param {google.firestore.v1.ListCollectionIdsResponse} message ListCollectionIdsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListCollectionIdsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.collectionIds = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.collectionIds && message.collectionIds.length) { + object.collectionIds = []; + for (var j = 0; j < message.collectionIds.length; ++j) + object.collectionIds[j] = message.collectionIds[j]; + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListCollectionIdsResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.ListCollectionIdsResponse + * @instance + * @returns {Object.} JSON object + */ + ListCollectionIdsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListCollectionIdsResponse + * @function getTypeUrl + * @memberof google.firestore.v1.ListCollectionIdsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListCollectionIdsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ListCollectionIdsResponse"; + }; + + return ListCollectionIdsResponse; + })(); + + v1.BatchWriteRequest = (function() { + + /** + * Properties of a BatchWriteRequest. + * @memberof google.firestore.v1 + * @interface IBatchWriteRequest + * @property {string|null} [database] BatchWriteRequest database + * @property {Array.|null} [writes] BatchWriteRequest writes + * @property {Object.|null} [labels] BatchWriteRequest labels + */ + + /** + * Constructs a new BatchWriteRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a BatchWriteRequest. + * @implements IBatchWriteRequest + * @constructor + * @param {google.firestore.v1.IBatchWriteRequest=} [properties] Properties to set + */ + function BatchWriteRequest(properties) { + this.writes = []; + this.labels = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BatchWriteRequest database. + * @member {string} database + * @memberof google.firestore.v1.BatchWriteRequest + * @instance + */ + BatchWriteRequest.prototype.database = ""; + + /** + * BatchWriteRequest writes. + * @member {Array.} writes + * @memberof google.firestore.v1.BatchWriteRequest + * @instance + */ + BatchWriteRequest.prototype.writes = $util.emptyArray; + + /** + * BatchWriteRequest labels. + * @member {Object.} labels + * @memberof google.firestore.v1.BatchWriteRequest + * @instance + */ + BatchWriteRequest.prototype.labels = $util.emptyObject; + + /** + * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.BatchWriteRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.BatchWriteRequest} BatchWriteRequest + */ + BatchWriteRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.BatchWriteRequest) + return object; + var message = new $root.google.firestore.v1.BatchWriteRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.writes) { + if (!Array.isArray(object.writes)) + throw TypeError(".google.firestore.v1.BatchWriteRequest.writes: array expected"); + message.writes = []; + for (var i = 0; i < object.writes.length; ++i) { + if (typeof object.writes[i] !== "object") + throw TypeError(".google.firestore.v1.BatchWriteRequest.writes: object expected"); + message.writes[i] = $root.google.firestore.v1.Write.fromObject(object.writes[i]); + } + } + if (object.labels) { + if (typeof object.labels !== "object") + throw TypeError(".google.firestore.v1.BatchWriteRequest.labels: object expected"); + message.labels = {}; + for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) + message.labels[keys[i]] = String(object.labels[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.BatchWriteRequest + * @static + * @param {google.firestore.v1.BatchWriteRequest} message BatchWriteRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchWriteRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.writes = []; + if (options.objects || options.defaults) + object.labels = {}; + if (options.defaults) + object.database = ""; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.writes && message.writes.length) { + object.writes = []; + for (var j = 0; j < message.writes.length; ++j) + object.writes[j] = $root.google.firestore.v1.Write.toObject(message.writes[j], options); + } + var keys2; + if (message.labels && (keys2 = Object.keys(message.labels)).length) { + object.labels = {}; + for (var j = 0; j < keys2.length; ++j) + object.labels[keys2[j]] = message.labels[keys2[j]]; + } + return object; + }; + + /** + * Converts this BatchWriteRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.BatchWriteRequest + * @instance + * @returns {Object.} JSON object + */ + BatchWriteRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchWriteRequest + * @function getTypeUrl + * @memberof google.firestore.v1.BatchWriteRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchWriteRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.BatchWriteRequest"; + }; + + return BatchWriteRequest; + })(); + + v1.BatchWriteResponse = (function() { + + /** + * Properties of a BatchWriteResponse. + * @memberof google.firestore.v1 + * @interface IBatchWriteResponse + * @property {Array.|null} [writeResults] BatchWriteResponse writeResults + * @property {Array.|null} [status] BatchWriteResponse status + */ + + /** + * Constructs a new BatchWriteResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a BatchWriteResponse. + * @implements IBatchWriteResponse + * @constructor + * @param {google.firestore.v1.IBatchWriteResponse=} [properties] Properties to set + */ + function BatchWriteResponse(properties) { + this.writeResults = []; + this.status = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BatchWriteResponse writeResults. + * @member {Array.} writeResults + * @memberof google.firestore.v1.BatchWriteResponse + * @instance + */ + BatchWriteResponse.prototype.writeResults = $util.emptyArray; + + /** + * BatchWriteResponse status. + * @member {Array.} status + * @memberof google.firestore.v1.BatchWriteResponse + * @instance + */ + BatchWriteResponse.prototype.status = $util.emptyArray; + + /** + * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.BatchWriteResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.BatchWriteResponse} BatchWriteResponse + */ + BatchWriteResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.BatchWriteResponse) + return object; + var message = new $root.google.firestore.v1.BatchWriteResponse(); + if (object.writeResults) { + if (!Array.isArray(object.writeResults)) + throw TypeError(".google.firestore.v1.BatchWriteResponse.writeResults: array expected"); + message.writeResults = []; + for (var i = 0; i < object.writeResults.length; ++i) { + if (typeof object.writeResults[i] !== "object") + throw TypeError(".google.firestore.v1.BatchWriteResponse.writeResults: object expected"); + message.writeResults[i] = $root.google.firestore.v1.WriteResult.fromObject(object.writeResults[i]); + } + } + if (object.status) { + if (!Array.isArray(object.status)) + throw TypeError(".google.firestore.v1.BatchWriteResponse.status: array expected"); + message.status = []; + for (var i = 0; i < object.status.length; ++i) { + if (typeof object.status[i] !== "object") + throw TypeError(".google.firestore.v1.BatchWriteResponse.status: object expected"); + message.status[i] = $root.google.rpc.Status.fromObject(object.status[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.BatchWriteResponse + * @static + * @param {google.firestore.v1.BatchWriteResponse} message BatchWriteResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchWriteResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.writeResults = []; + object.status = []; + } + if (message.writeResults && message.writeResults.length) { + object.writeResults = []; + for (var j = 0; j < message.writeResults.length; ++j) + object.writeResults[j] = $root.google.firestore.v1.WriteResult.toObject(message.writeResults[j], options); + } + if (message.status && message.status.length) { + object.status = []; + for (var j = 0; j < message.status.length; ++j) + object.status[j] = $root.google.rpc.Status.toObject(message.status[j], options); + } + return object; + }; + + /** + * Converts this BatchWriteResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.BatchWriteResponse + * @instance + * @returns {Object.} JSON object + */ + BatchWriteResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchWriteResponse + * @function getTypeUrl + * @memberof google.firestore.v1.BatchWriteResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchWriteResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.BatchWriteResponse"; + }; + + return BatchWriteResponse; + })(); + + v1.StructuredPipeline = (function() { + + /** + * Properties of a StructuredPipeline. + * @memberof google.firestore.v1 + * @interface IStructuredPipeline + * @property {google.firestore.v1.IPipeline|null} [pipeline] StructuredPipeline pipeline + * @property {Object.|null} [options] StructuredPipeline options + */ + + /** + * Constructs a new StructuredPipeline. + * @memberof google.firestore.v1 + * @classdesc Represents a StructuredPipeline. + * @implements IStructuredPipeline + * @constructor + * @param {google.firestore.v1.IStructuredPipeline=} [properties] Properties to set + */ + function StructuredPipeline(properties) { + this.options = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * StructuredPipeline pipeline. + * @member {google.firestore.v1.IPipeline|null|undefined} pipeline + * @memberof google.firestore.v1.StructuredPipeline + * @instance + */ + StructuredPipeline.prototype.pipeline = null; + + /** + * StructuredPipeline options. + * @member {Object.} options + * @memberof google.firestore.v1.StructuredPipeline + * @instance + */ + StructuredPipeline.prototype.options = $util.emptyObject; + + /** + * Creates a StructuredPipeline message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredPipeline + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredPipeline} StructuredPipeline + */ + StructuredPipeline.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredPipeline) + return object; + var message = new $root.google.firestore.v1.StructuredPipeline(); + if (object.pipeline != null) { + if (typeof object.pipeline !== "object") + throw TypeError(".google.firestore.v1.StructuredPipeline.pipeline: object expected"); + message.pipeline = $root.google.firestore.v1.Pipeline.fromObject(object.pipeline); + } + if (object.options) { + if (typeof object.options !== "object") + throw TypeError(".google.firestore.v1.StructuredPipeline.options: object expected"); + message.options = {}; + for (var keys = Object.keys(object.options), i = 0; i < keys.length; ++i) { + if (typeof object.options[keys[i]] !== "object") + throw TypeError(".google.firestore.v1.StructuredPipeline.options: object expected"); + message.options[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.options[keys[i]]); + } + } + return message; + }; + + /** + * Creates a plain object from a StructuredPipeline message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredPipeline + * @static + * @param {google.firestore.v1.StructuredPipeline} message StructuredPipeline + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + StructuredPipeline.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.options = {}; + if (options.defaults) + object.pipeline = null; + if (message.pipeline != null && message.hasOwnProperty("pipeline")) + object.pipeline = $root.google.firestore.v1.Pipeline.toObject(message.pipeline, options); + var keys2; + if (message.options && (keys2 = Object.keys(message.options)).length) { + object.options = {}; + for (var j = 0; j < keys2.length; ++j) + object.options[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.options[keys2[j]], options); + } + return object; + }; + + /** + * Converts this StructuredPipeline to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredPipeline + * @instance + * @returns {Object.} JSON object + */ + StructuredPipeline.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for StructuredPipeline + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredPipeline + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + StructuredPipeline.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredPipeline"; + }; + + return StructuredPipeline; + })(); + + v1.StructuredQuery = (function() { + + /** + * Properties of a StructuredQuery. + * @memberof google.firestore.v1 + * @interface IStructuredQuery + * @property {google.firestore.v1.StructuredQuery.IProjection|null} [select] StructuredQuery select + * @property {Array.|null} [from] StructuredQuery from + * @property {google.firestore.v1.StructuredQuery.IFilter|null} [where] StructuredQuery where + * @property {Array.|null} [orderBy] StructuredQuery orderBy + * @property {google.firestore.v1.ICursor|null} [startAt] StructuredQuery startAt + * @property {google.firestore.v1.ICursor|null} [endAt] StructuredQuery endAt + * @property {number|null} [offset] StructuredQuery offset + * @property {google.protobuf.IInt32Value|null} [limit] StructuredQuery limit + * @property {google.firestore.v1.StructuredQuery.IFindNearest|null} [findNearest] StructuredQuery findNearest + */ + + /** + * Constructs a new StructuredQuery. + * @memberof google.firestore.v1 + * @classdesc Represents a StructuredQuery. + * @implements IStructuredQuery + * @constructor + * @param {google.firestore.v1.IStructuredQuery=} [properties] Properties to set + */ + function StructuredQuery(properties) { + this.from = []; + this.orderBy = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * StructuredQuery select. + * @member {google.firestore.v1.StructuredQuery.IProjection|null|undefined} select + * @memberof google.firestore.v1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.select = null; + + /** + * StructuredQuery from. + * @member {Array.} from + * @memberof google.firestore.v1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.from = $util.emptyArray; + + /** + * StructuredQuery where. + * @member {google.firestore.v1.StructuredQuery.IFilter|null|undefined} where + * @memberof google.firestore.v1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.where = null; + + /** + * StructuredQuery orderBy. + * @member {Array.} orderBy + * @memberof google.firestore.v1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.orderBy = $util.emptyArray; + + /** + * StructuredQuery startAt. + * @member {google.firestore.v1.ICursor|null|undefined} startAt + * @memberof google.firestore.v1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.startAt = null; + + /** + * StructuredQuery endAt. + * @member {google.firestore.v1.ICursor|null|undefined} endAt + * @memberof google.firestore.v1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.endAt = null; + + /** + * StructuredQuery offset. + * @member {number} offset + * @memberof google.firestore.v1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.offset = 0; + + /** + * StructuredQuery limit. + * @member {google.protobuf.IInt32Value|null|undefined} limit + * @memberof google.firestore.v1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.limit = null; + + /** + * StructuredQuery findNearest. + * @member {google.firestore.v1.StructuredQuery.IFindNearest|null|undefined} findNearest + * @memberof google.firestore.v1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.findNearest = null; + + /** + * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredQuery + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredQuery} StructuredQuery + */ + StructuredQuery.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery) + return object; + var message = new $root.google.firestore.v1.StructuredQuery(); + if (object.select != null) { + if (typeof object.select !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.select: object expected"); + message.select = $root.google.firestore.v1.StructuredQuery.Projection.fromObject(object.select); + } + if (object.from) { + if (!Array.isArray(object.from)) + throw TypeError(".google.firestore.v1.StructuredQuery.from: array expected"); + message.from = []; + for (var i = 0; i < object.from.length; ++i) { + if (typeof object.from[i] !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.from: object expected"); + message.from[i] = $root.google.firestore.v1.StructuredQuery.CollectionSelector.fromObject(object.from[i]); + } + } + if (object.where != null) { + if (typeof object.where !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.where: object expected"); + message.where = $root.google.firestore.v1.StructuredQuery.Filter.fromObject(object.where); + } + if (object.orderBy) { + if (!Array.isArray(object.orderBy)) + throw TypeError(".google.firestore.v1.StructuredQuery.orderBy: array expected"); + message.orderBy = []; + for (var i = 0; i < object.orderBy.length; ++i) { + if (typeof object.orderBy[i] !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.orderBy: object expected"); + message.orderBy[i] = $root.google.firestore.v1.StructuredQuery.Order.fromObject(object.orderBy[i]); + } + } + if (object.startAt != null) { + if (typeof object.startAt !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.startAt: object expected"); + message.startAt = $root.google.firestore.v1.Cursor.fromObject(object.startAt); + } + if (object.endAt != null) { + if (typeof object.endAt !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.endAt: object expected"); + message.endAt = $root.google.firestore.v1.Cursor.fromObject(object.endAt); + } + if (object.offset != null) + message.offset = object.offset | 0; + if (object.limit != null) { + if (typeof object.limit !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.limit: object expected"); + message.limit = $root.google.protobuf.Int32Value.fromObject(object.limit); + } + if (object.findNearest != null) { + if (typeof object.findNearest !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.findNearest: object expected"); + message.findNearest = $root.google.firestore.v1.StructuredQuery.FindNearest.fromObject(object.findNearest); + } + return message; + }; + + /** + * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredQuery + * @static + * @param {google.firestore.v1.StructuredQuery} message StructuredQuery + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + StructuredQuery.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.from = []; + object.orderBy = []; + } + if (options.defaults) { + object.select = null; + object.where = null; + object.limit = null; + object.offset = 0; + object.startAt = null; + object.endAt = null; + object.findNearest = null; + } + if (message.select != null && message.hasOwnProperty("select")) + object.select = $root.google.firestore.v1.StructuredQuery.Projection.toObject(message.select, options); + if (message.from && message.from.length) { + object.from = []; + for (var j = 0; j < message.from.length; ++j) + object.from[j] = $root.google.firestore.v1.StructuredQuery.CollectionSelector.toObject(message.from[j], options); + } + if (message.where != null && message.hasOwnProperty("where")) + object.where = $root.google.firestore.v1.StructuredQuery.Filter.toObject(message.where, options); + if (message.orderBy && message.orderBy.length) { + object.orderBy = []; + for (var j = 0; j < message.orderBy.length; ++j) + object.orderBy[j] = $root.google.firestore.v1.StructuredQuery.Order.toObject(message.orderBy[j], options); + } + if (message.limit != null && message.hasOwnProperty("limit")) + object.limit = $root.google.protobuf.Int32Value.toObject(message.limit, options); + if (message.offset != null && message.hasOwnProperty("offset")) + object.offset = message.offset; + if (message.startAt != null && message.hasOwnProperty("startAt")) + object.startAt = $root.google.firestore.v1.Cursor.toObject(message.startAt, options); + if (message.endAt != null && message.hasOwnProperty("endAt")) + object.endAt = $root.google.firestore.v1.Cursor.toObject(message.endAt, options); + if (message.findNearest != null && message.hasOwnProperty("findNearest")) + object.findNearest = $root.google.firestore.v1.StructuredQuery.FindNearest.toObject(message.findNearest, options); + return object; + }; + + /** + * Converts this StructuredQuery to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery + * @instance + * @returns {Object.} JSON object + */ + StructuredQuery.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for StructuredQuery + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + StructuredQuery.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery"; + }; + + StructuredQuery.CollectionSelector = (function() { + + /** + * Properties of a CollectionSelector. + * @memberof google.firestore.v1.StructuredQuery + * @interface ICollectionSelector + * @property {string|null} [collectionId] CollectionSelector collectionId + * @property {boolean|null} [allDescendants] CollectionSelector allDescendants + */ + + /** + * Constructs a new CollectionSelector. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents a CollectionSelector. + * @implements ICollectionSelector + * @constructor + * @param {google.firestore.v1.StructuredQuery.ICollectionSelector=} [properties] Properties to set + */ + function CollectionSelector(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CollectionSelector collectionId. + * @member {string} collectionId + * @memberof google.firestore.v1.StructuredQuery.CollectionSelector + * @instance + */ + CollectionSelector.prototype.collectionId = ""; + + /** + * CollectionSelector allDescendants. + * @member {boolean} allDescendants + * @memberof google.firestore.v1.StructuredQuery.CollectionSelector + * @instance + */ + CollectionSelector.prototype.allDescendants = false; + + /** + * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredQuery.CollectionSelector + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredQuery.CollectionSelector} CollectionSelector + */ + CollectionSelector.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.CollectionSelector) + return object; + var message = new $root.google.firestore.v1.StructuredQuery.CollectionSelector(); + if (object.collectionId != null) + message.collectionId = String(object.collectionId); + if (object.allDescendants != null) + message.allDescendants = Boolean(object.allDescendants); + return message; + }; + + /** + * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredQuery.CollectionSelector + * @static + * @param {google.firestore.v1.StructuredQuery.CollectionSelector} message CollectionSelector + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CollectionSelector.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.collectionId = ""; + object.allDescendants = false; + } + if (message.collectionId != null && message.hasOwnProperty("collectionId")) + object.collectionId = message.collectionId; + if (message.allDescendants != null && message.hasOwnProperty("allDescendants")) + object.allDescendants = message.allDescendants; + return object; + }; + + /** + * Converts this CollectionSelector to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery.CollectionSelector + * @instance + * @returns {Object.} JSON object + */ + CollectionSelector.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CollectionSelector + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery.CollectionSelector + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CollectionSelector.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.CollectionSelector"; + }; + + return CollectionSelector; + })(); + + StructuredQuery.Filter = (function() { + + /** + * Properties of a Filter. + * @memberof google.firestore.v1.StructuredQuery + * @interface IFilter + * @property {google.firestore.v1.StructuredQuery.ICompositeFilter|null} [compositeFilter] Filter compositeFilter + * @property {google.firestore.v1.StructuredQuery.IFieldFilter|null} [fieldFilter] Filter fieldFilter + * @property {google.firestore.v1.StructuredQuery.IUnaryFilter|null} [unaryFilter] Filter unaryFilter + */ + + /** + * Constructs a new Filter. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents a Filter. + * @implements IFilter + * @constructor + * @param {google.firestore.v1.StructuredQuery.IFilter=} [properties] Properties to set + */ + function Filter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Filter compositeFilter. + * @member {google.firestore.v1.StructuredQuery.ICompositeFilter|null|undefined} compositeFilter + * @memberof google.firestore.v1.StructuredQuery.Filter + * @instance + */ + Filter.prototype.compositeFilter = null; + + /** + * Filter fieldFilter. + * @member {google.firestore.v1.StructuredQuery.IFieldFilter|null|undefined} fieldFilter + * @memberof google.firestore.v1.StructuredQuery.Filter + * @instance + */ + Filter.prototype.fieldFilter = null; + + /** + * Filter unaryFilter. + * @member {google.firestore.v1.StructuredQuery.IUnaryFilter|null|undefined} unaryFilter + * @memberof google.firestore.v1.StructuredQuery.Filter + * @instance + */ + Filter.prototype.unaryFilter = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Filter filterType. + * @member {"compositeFilter"|"fieldFilter"|"unaryFilter"|undefined} filterType + * @memberof google.firestore.v1.StructuredQuery.Filter + * @instance + */ + Object.defineProperty(Filter.prototype, "filterType", { + get: $util.oneOfGetter($oneOfFields = ["compositeFilter", "fieldFilter", "unaryFilter"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a Filter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredQuery.Filter + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredQuery.Filter} Filter + */ + Filter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.Filter) + return object; + var message = new $root.google.firestore.v1.StructuredQuery.Filter(); + if (object.compositeFilter != null) { + if (typeof object.compositeFilter !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.Filter.compositeFilter: object expected"); + message.compositeFilter = $root.google.firestore.v1.StructuredQuery.CompositeFilter.fromObject(object.compositeFilter); + } + if (object.fieldFilter != null) { + if (typeof object.fieldFilter !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.Filter.fieldFilter: object expected"); + message.fieldFilter = $root.google.firestore.v1.StructuredQuery.FieldFilter.fromObject(object.fieldFilter); + } + if (object.unaryFilter != null) { + if (typeof object.unaryFilter !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.Filter.unaryFilter: object expected"); + message.unaryFilter = $root.google.firestore.v1.StructuredQuery.UnaryFilter.fromObject(object.unaryFilter); + } + return message; + }; + + /** + * Creates a plain object from a Filter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredQuery.Filter + * @static + * @param {google.firestore.v1.StructuredQuery.Filter} message Filter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Filter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.compositeFilter != null && message.hasOwnProperty("compositeFilter")) { + object.compositeFilter = $root.google.firestore.v1.StructuredQuery.CompositeFilter.toObject(message.compositeFilter, options); + if (options.oneofs) + object.filterType = "compositeFilter"; + } + if (message.fieldFilter != null && message.hasOwnProperty("fieldFilter")) { + object.fieldFilter = $root.google.firestore.v1.StructuredQuery.FieldFilter.toObject(message.fieldFilter, options); + if (options.oneofs) + object.filterType = "fieldFilter"; + } + if (message.unaryFilter != null && message.hasOwnProperty("unaryFilter")) { + object.unaryFilter = $root.google.firestore.v1.StructuredQuery.UnaryFilter.toObject(message.unaryFilter, options); + if (options.oneofs) + object.filterType = "unaryFilter"; + } + return object; + }; + + /** + * Converts this Filter to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery.Filter + * @instance + * @returns {Object.} JSON object + */ + Filter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Filter + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery.Filter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Filter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.Filter"; + }; + + return Filter; + })(); + + StructuredQuery.CompositeFilter = (function() { + + /** + * Properties of a CompositeFilter. + * @memberof google.firestore.v1.StructuredQuery + * @interface ICompositeFilter + * @property {google.firestore.v1.StructuredQuery.CompositeFilter.Operator|null} [op] CompositeFilter op + * @property {Array.|null} [filters] CompositeFilter filters + */ + + /** + * Constructs a new CompositeFilter. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents a CompositeFilter. + * @implements ICompositeFilter + * @constructor + * @param {google.firestore.v1.StructuredQuery.ICompositeFilter=} [properties] Properties to set + */ + function CompositeFilter(properties) { + this.filters = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CompositeFilter op. + * @member {google.firestore.v1.StructuredQuery.CompositeFilter.Operator} op + * @memberof google.firestore.v1.StructuredQuery.CompositeFilter + * @instance + */ + CompositeFilter.prototype.op = 0; + + /** + * CompositeFilter filters. + * @member {Array.} filters + * @memberof google.firestore.v1.StructuredQuery.CompositeFilter + * @instance + */ + CompositeFilter.prototype.filters = $util.emptyArray; + + /** + * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredQuery.CompositeFilter + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredQuery.CompositeFilter} CompositeFilter + */ + CompositeFilter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.CompositeFilter) + return object; + var message = new $root.google.firestore.v1.StructuredQuery.CompositeFilter(); + switch (object.op) { + default: + if (typeof object.op === "number") { + message.op = object.op; + break; + } + break; + case "OPERATOR_UNSPECIFIED": + case 0: + message.op = 0; + break; + case "AND": + case 1: + message.op = 1; + break; + case "OR": + case 2: + message.op = 2; + break; + } + if (object.filters) { + if (!Array.isArray(object.filters)) + throw TypeError(".google.firestore.v1.StructuredQuery.CompositeFilter.filters: array expected"); + message.filters = []; + for (var i = 0; i < object.filters.length; ++i) { + if (typeof object.filters[i] !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.CompositeFilter.filters: object expected"); + message.filters[i] = $root.google.firestore.v1.StructuredQuery.Filter.fromObject(object.filters[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredQuery.CompositeFilter + * @static + * @param {google.firestore.v1.StructuredQuery.CompositeFilter} message CompositeFilter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CompositeFilter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.filters = []; + if (options.defaults) + object.op = options.enums === String ? "OPERATOR_UNSPECIFIED" : 0; + if (message.op != null && message.hasOwnProperty("op")) + object.op = options.enums === String ? $root.google.firestore.v1.StructuredQuery.CompositeFilter.Operator[message.op] === undefined ? message.op : $root.google.firestore.v1.StructuredQuery.CompositeFilter.Operator[message.op] : message.op; + if (message.filters && message.filters.length) { + object.filters = []; + for (var j = 0; j < message.filters.length; ++j) + object.filters[j] = $root.google.firestore.v1.StructuredQuery.Filter.toObject(message.filters[j], options); + } + return object; + }; + + /** + * Converts this CompositeFilter to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery.CompositeFilter + * @instance + * @returns {Object.} JSON object + */ + CompositeFilter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CompositeFilter + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery.CompositeFilter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CompositeFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.CompositeFilter"; + }; + + /** + * Operator enum. + * @name google.firestore.v1.StructuredQuery.CompositeFilter.Operator + * @enum {string} + * @property {string} OPERATOR_UNSPECIFIED=OPERATOR_UNSPECIFIED OPERATOR_UNSPECIFIED value + * @property {string} AND=AND AND value + * @property {string} OR=OR OR value + */ + CompositeFilter.Operator = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "OPERATOR_UNSPECIFIED"] = "OPERATOR_UNSPECIFIED"; + values[valuesById[1] = "AND"] = "AND"; + values[valuesById[2] = "OR"] = "OR"; + return values; + })(); + + return CompositeFilter; + })(); + + StructuredQuery.FieldFilter = (function() { + + /** + * Properties of a FieldFilter. + * @memberof google.firestore.v1.StructuredQuery + * @interface IFieldFilter + * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] FieldFilter field + * @property {google.firestore.v1.StructuredQuery.FieldFilter.Operator|null} [op] FieldFilter op + * @property {google.firestore.v1.IValue|null} [value] FieldFilter value + */ + + /** + * Constructs a new FieldFilter. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents a FieldFilter. + * @implements IFieldFilter + * @constructor + * @param {google.firestore.v1.StructuredQuery.IFieldFilter=} [properties] Properties to set + */ + function FieldFilter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldFilter field. + * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field + * @memberof google.firestore.v1.StructuredQuery.FieldFilter + * @instance + */ + FieldFilter.prototype.field = null; + + /** + * FieldFilter op. + * @member {google.firestore.v1.StructuredQuery.FieldFilter.Operator} op + * @memberof google.firestore.v1.StructuredQuery.FieldFilter + * @instance + */ + FieldFilter.prototype.op = 0; + + /** + * FieldFilter value. + * @member {google.firestore.v1.IValue|null|undefined} value + * @memberof google.firestore.v1.StructuredQuery.FieldFilter + * @instance + */ + FieldFilter.prototype.value = null; + + /** + * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredQuery.FieldFilter + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredQuery.FieldFilter} FieldFilter + */ + FieldFilter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.FieldFilter) + return object; + var message = new $root.google.firestore.v1.StructuredQuery.FieldFilter(); + if (object.field != null) { + if (typeof object.field !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.FieldFilter.field: object expected"); + message.field = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.field); + } + switch (object.op) { + default: + if (typeof object.op === "number") { + message.op = object.op; + break; + } + break; + case "OPERATOR_UNSPECIFIED": + case 0: + message.op = 0; + break; + case "LESS_THAN": + case 1: + message.op = 1; + break; + case "LESS_THAN_OR_EQUAL": + case 2: + message.op = 2; + break; + case "GREATER_THAN": + case 3: + message.op = 3; + break; + case "GREATER_THAN_OR_EQUAL": + case 4: + message.op = 4; + break; + case "EQUAL": + case 5: + message.op = 5; + break; + case "NOT_EQUAL": + case 6: + message.op = 6; + break; + case "ARRAY_CONTAINS": + case 7: + message.op = 7; + break; + case "IN": + case 8: + message.op = 8; + break; + case "ARRAY_CONTAINS_ANY": + case 9: + message.op = 9; + break; + case "NOT_IN": + case 10: + message.op = 10; + break; + } + if (object.value != null) { + if (typeof object.value !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.FieldFilter.value: object expected"); + message.value = $root.google.firestore.v1.Value.fromObject(object.value); + } + return message; + }; + + /** + * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredQuery.FieldFilter + * @static + * @param {google.firestore.v1.StructuredQuery.FieldFilter} message FieldFilter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldFilter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.field = null; + object.op = options.enums === String ? "OPERATOR_UNSPECIFIED" : 0; + object.value = null; + } + if (message.field != null && message.hasOwnProperty("field")) + object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); + if (message.op != null && message.hasOwnProperty("op")) + object.op = options.enums === String ? $root.google.firestore.v1.StructuredQuery.FieldFilter.Operator[message.op] === undefined ? message.op : $root.google.firestore.v1.StructuredQuery.FieldFilter.Operator[message.op] : message.op; + if (message.value != null && message.hasOwnProperty("value")) + object.value = $root.google.firestore.v1.Value.toObject(message.value, options); + return object; + }; + + /** + * Converts this FieldFilter to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery.FieldFilter + * @instance + * @returns {Object.} JSON object + */ + FieldFilter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldFilter + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery.FieldFilter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.FieldFilter"; + }; + + /** + * Operator enum. + * @name google.firestore.v1.StructuredQuery.FieldFilter.Operator + * @enum {string} + * @property {string} OPERATOR_UNSPECIFIED=OPERATOR_UNSPECIFIED OPERATOR_UNSPECIFIED value + * @property {string} LESS_THAN=LESS_THAN LESS_THAN value + * @property {string} LESS_THAN_OR_EQUAL=LESS_THAN_OR_EQUAL LESS_THAN_OR_EQUAL value + * @property {string} GREATER_THAN=GREATER_THAN GREATER_THAN value + * @property {string} GREATER_THAN_OR_EQUAL=GREATER_THAN_OR_EQUAL GREATER_THAN_OR_EQUAL value + * @property {string} EQUAL=EQUAL EQUAL value + * @property {string} NOT_EQUAL=NOT_EQUAL NOT_EQUAL value + * @property {string} ARRAY_CONTAINS=ARRAY_CONTAINS ARRAY_CONTAINS value + * @property {string} IN=IN IN value + * @property {string} ARRAY_CONTAINS_ANY=ARRAY_CONTAINS_ANY ARRAY_CONTAINS_ANY value + * @property {string} NOT_IN=NOT_IN NOT_IN value + */ + FieldFilter.Operator = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "OPERATOR_UNSPECIFIED"] = "OPERATOR_UNSPECIFIED"; + values[valuesById[1] = "LESS_THAN"] = "LESS_THAN"; + values[valuesById[2] = "LESS_THAN_OR_EQUAL"] = "LESS_THAN_OR_EQUAL"; + values[valuesById[3] = "GREATER_THAN"] = "GREATER_THAN"; + values[valuesById[4] = "GREATER_THAN_OR_EQUAL"] = "GREATER_THAN_OR_EQUAL"; + values[valuesById[5] = "EQUAL"] = "EQUAL"; + values[valuesById[6] = "NOT_EQUAL"] = "NOT_EQUAL"; + values[valuesById[7] = "ARRAY_CONTAINS"] = "ARRAY_CONTAINS"; + values[valuesById[8] = "IN"] = "IN"; + values[valuesById[9] = "ARRAY_CONTAINS_ANY"] = "ARRAY_CONTAINS_ANY"; + values[valuesById[10] = "NOT_IN"] = "NOT_IN"; + return values; + })(); + + return FieldFilter; + })(); + + StructuredQuery.UnaryFilter = (function() { + + /** + * Properties of an UnaryFilter. + * @memberof google.firestore.v1.StructuredQuery + * @interface IUnaryFilter + * @property {google.firestore.v1.StructuredQuery.UnaryFilter.Operator|null} [op] UnaryFilter op + * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] UnaryFilter field + */ + + /** + * Constructs a new UnaryFilter. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents an UnaryFilter. + * @implements IUnaryFilter + * @constructor + * @param {google.firestore.v1.StructuredQuery.IUnaryFilter=} [properties] Properties to set + */ + function UnaryFilter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UnaryFilter op. + * @member {google.firestore.v1.StructuredQuery.UnaryFilter.Operator} op + * @memberof google.firestore.v1.StructuredQuery.UnaryFilter + * @instance + */ + UnaryFilter.prototype.op = 0; + + /** + * UnaryFilter field. + * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field + * @memberof google.firestore.v1.StructuredQuery.UnaryFilter + * @instance + */ + UnaryFilter.prototype.field = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * UnaryFilter operandType. + * @member {"field"|undefined} operandType + * @memberof google.firestore.v1.StructuredQuery.UnaryFilter + * @instance + */ + Object.defineProperty(UnaryFilter.prototype, "operandType", { + get: $util.oneOfGetter($oneOfFields = ["field"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredQuery.UnaryFilter + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredQuery.UnaryFilter} UnaryFilter + */ + UnaryFilter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.UnaryFilter) + return object; + var message = new $root.google.firestore.v1.StructuredQuery.UnaryFilter(); + switch (object.op) { + default: + if (typeof object.op === "number") { + message.op = object.op; + break; + } + break; + case "OPERATOR_UNSPECIFIED": + case 0: + message.op = 0; + break; + case "IS_NAN": + case 2: + message.op = 2; + break; + case "IS_NULL": + case 3: + message.op = 3; + break; + case "IS_NOT_NAN": + case 4: + message.op = 4; + break; + case "IS_NOT_NULL": + case 5: + message.op = 5; + break; + } + if (object.field != null) { + if (typeof object.field !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.UnaryFilter.field: object expected"); + message.field = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.field); + } + return message; + }; + + /** + * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredQuery.UnaryFilter + * @static + * @param {google.firestore.v1.StructuredQuery.UnaryFilter} message UnaryFilter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UnaryFilter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.op = options.enums === String ? "OPERATOR_UNSPECIFIED" : 0; + if (message.op != null && message.hasOwnProperty("op")) + object.op = options.enums === String ? $root.google.firestore.v1.StructuredQuery.UnaryFilter.Operator[message.op] === undefined ? message.op : $root.google.firestore.v1.StructuredQuery.UnaryFilter.Operator[message.op] : message.op; + if (message.field != null && message.hasOwnProperty("field")) { + object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); + if (options.oneofs) + object.operandType = "field"; + } + return object; + }; + + /** + * Converts this UnaryFilter to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery.UnaryFilter + * @instance + * @returns {Object.} JSON object + */ + UnaryFilter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UnaryFilter + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery.UnaryFilter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UnaryFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.UnaryFilter"; + }; + + /** + * Operator enum. + * @name google.firestore.v1.StructuredQuery.UnaryFilter.Operator + * @enum {string} + * @property {string} OPERATOR_UNSPECIFIED=OPERATOR_UNSPECIFIED OPERATOR_UNSPECIFIED value + * @property {string} IS_NAN=IS_NAN IS_NAN value + * @property {string} IS_NULL=IS_NULL IS_NULL value + * @property {string} IS_NOT_NAN=IS_NOT_NAN IS_NOT_NAN value + * @property {string} IS_NOT_NULL=IS_NOT_NULL IS_NOT_NULL value + */ + UnaryFilter.Operator = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "OPERATOR_UNSPECIFIED"] = "OPERATOR_UNSPECIFIED"; + values[valuesById[2] = "IS_NAN"] = "IS_NAN"; + values[valuesById[3] = "IS_NULL"] = "IS_NULL"; + values[valuesById[4] = "IS_NOT_NAN"] = "IS_NOT_NAN"; + values[valuesById[5] = "IS_NOT_NULL"] = "IS_NOT_NULL"; + return values; + })(); + + return UnaryFilter; + })(); + + StructuredQuery.Order = (function() { + + /** + * Properties of an Order. + * @memberof google.firestore.v1.StructuredQuery + * @interface IOrder + * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] Order field + * @property {google.firestore.v1.StructuredQuery.Direction|null} [direction] Order direction + */ + + /** + * Constructs a new Order. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents an Order. + * @implements IOrder + * @constructor + * @param {google.firestore.v1.StructuredQuery.IOrder=} [properties] Properties to set + */ + function Order(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Order field. + * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field + * @memberof google.firestore.v1.StructuredQuery.Order + * @instance + */ + Order.prototype.field = null; + + /** + * Order direction. + * @member {google.firestore.v1.StructuredQuery.Direction} direction + * @memberof google.firestore.v1.StructuredQuery.Order + * @instance + */ + Order.prototype.direction = 0; + + /** + * Creates an Order message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredQuery.Order + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredQuery.Order} Order + */ + Order.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.Order) + return object; + var message = new $root.google.firestore.v1.StructuredQuery.Order(); + if (object.field != null) { + if (typeof object.field !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.Order.field: object expected"); + message.field = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.field); + } + switch (object.direction) { + default: + if (typeof object.direction === "number") { + message.direction = object.direction; + break; + } + break; + case "DIRECTION_UNSPECIFIED": + case 0: + message.direction = 0; + break; + case "ASCENDING": + case 1: + message.direction = 1; + break; + case "DESCENDING": + case 2: + message.direction = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from an Order message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredQuery.Order + * @static + * @param {google.firestore.v1.StructuredQuery.Order} message Order + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Order.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.field = null; + object.direction = options.enums === String ? "DIRECTION_UNSPECIFIED" : 0; + } + if (message.field != null && message.hasOwnProperty("field")) + object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); + if (message.direction != null && message.hasOwnProperty("direction")) + object.direction = options.enums === String ? $root.google.firestore.v1.StructuredQuery.Direction[message.direction] === undefined ? message.direction : $root.google.firestore.v1.StructuredQuery.Direction[message.direction] : message.direction; + return object; + }; + + /** + * Converts this Order to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery.Order + * @instance + * @returns {Object.} JSON object + */ + Order.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Order + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery.Order + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Order.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.Order"; + }; + + return Order; + })(); + + /** + * Direction enum. + * @name google.firestore.v1.StructuredQuery.Direction + * @enum {string} + * @property {string} DIRECTION_UNSPECIFIED=DIRECTION_UNSPECIFIED DIRECTION_UNSPECIFIED value + * @property {string} ASCENDING=ASCENDING ASCENDING value + * @property {string} DESCENDING=DESCENDING DESCENDING value + */ + StructuredQuery.Direction = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DIRECTION_UNSPECIFIED"] = "DIRECTION_UNSPECIFIED"; + values[valuesById[1] = "ASCENDING"] = "ASCENDING"; + values[valuesById[2] = "DESCENDING"] = "DESCENDING"; + return values; + })(); + + StructuredQuery.FieldReference = (function() { + + /** + * Properties of a FieldReference. + * @memberof google.firestore.v1.StructuredQuery + * @interface IFieldReference + * @property {string|null} [fieldPath] FieldReference fieldPath + */ + + /** + * Constructs a new FieldReference. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents a FieldReference. + * @implements IFieldReference + * @constructor + * @param {google.firestore.v1.StructuredQuery.IFieldReference=} [properties] Properties to set + */ + function FieldReference(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldReference fieldPath. + * @member {string} fieldPath + * @memberof google.firestore.v1.StructuredQuery.FieldReference + * @instance + */ + FieldReference.prototype.fieldPath = ""; + + /** + * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredQuery.FieldReference + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredQuery.FieldReference} FieldReference + */ + FieldReference.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.FieldReference) + return object; + var message = new $root.google.firestore.v1.StructuredQuery.FieldReference(); + if (object.fieldPath != null) + message.fieldPath = String(object.fieldPath); + return message; + }; + + /** + * Creates a plain object from a FieldReference message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredQuery.FieldReference + * @static + * @param {google.firestore.v1.StructuredQuery.FieldReference} message FieldReference + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldReference.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.fieldPath = ""; + if (message.fieldPath != null && message.hasOwnProperty("fieldPath")) + object.fieldPath = message.fieldPath; + return object; + }; + + /** + * Converts this FieldReference to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery.FieldReference + * @instance + * @returns {Object.} JSON object + */ + FieldReference.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldReference + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery.FieldReference + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldReference.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.FieldReference"; + }; + + return FieldReference; + })(); + + StructuredQuery.Projection = (function() { + + /** + * Properties of a Projection. + * @memberof google.firestore.v1.StructuredQuery + * @interface IProjection + * @property {Array.|null} [fields] Projection fields + */ + + /** + * Constructs a new Projection. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents a Projection. + * @implements IProjection + * @constructor + * @param {google.firestore.v1.StructuredQuery.IProjection=} [properties] Properties to set + */ + function Projection(properties) { + this.fields = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Projection fields. + * @member {Array.} fields + * @memberof google.firestore.v1.StructuredQuery.Projection + * @instance + */ + Projection.prototype.fields = $util.emptyArray; + + /** + * Creates a Projection message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredQuery.Projection + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredQuery.Projection} Projection + */ + Projection.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.Projection) + return object; + var message = new $root.google.firestore.v1.StructuredQuery.Projection(); + if (object.fields) { + if (!Array.isArray(object.fields)) + throw TypeError(".google.firestore.v1.StructuredQuery.Projection.fields: array expected"); + message.fields = []; + for (var i = 0; i < object.fields.length; ++i) { + if (typeof object.fields[i] !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.Projection.fields: object expected"); + message.fields[i] = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.fields[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a Projection message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredQuery.Projection + * @static + * @param {google.firestore.v1.StructuredQuery.Projection} message Projection + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Projection.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.fields = []; + if (message.fields && message.fields.length) { + object.fields = []; + for (var j = 0; j < message.fields.length; ++j) + object.fields[j] = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.fields[j], options); + } + return object; + }; + + /** + * Converts this Projection to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery.Projection + * @instance + * @returns {Object.} JSON object + */ + Projection.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Projection + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery.Projection + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Projection.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.Projection"; + }; + + return Projection; + })(); + + StructuredQuery.FindNearest = (function() { + + /** + * Properties of a FindNearest. + * @memberof google.firestore.v1.StructuredQuery + * @interface IFindNearest + * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [vectorField] FindNearest vectorField + * @property {google.firestore.v1.IValue|null} [queryVector] FindNearest queryVector + * @property {google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure|null} [distanceMeasure] FindNearest distanceMeasure + * @property {google.protobuf.IInt32Value|null} [limit] FindNearest limit + * @property {string|null} [distanceResultField] FindNearest distanceResultField + * @property {google.protobuf.IDoubleValue|null} [distanceThreshold] FindNearest distanceThreshold + */ + + /** + * Constructs a new FindNearest. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents a FindNearest. + * @implements IFindNearest + * @constructor + * @param {google.firestore.v1.StructuredQuery.IFindNearest=} [properties] Properties to set + */ + function FindNearest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FindNearest vectorField. + * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} vectorField + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @instance + */ + FindNearest.prototype.vectorField = null; + + /** + * FindNearest queryVector. + * @member {google.firestore.v1.IValue|null|undefined} queryVector + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @instance + */ + FindNearest.prototype.queryVector = null; + + /** + * FindNearest distanceMeasure. + * @member {google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure} distanceMeasure + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @instance + */ + FindNearest.prototype.distanceMeasure = 0; + + /** + * FindNearest limit. + * @member {google.protobuf.IInt32Value|null|undefined} limit + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @instance + */ + FindNearest.prototype.limit = null; + + /** + * FindNearest distanceResultField. + * @member {string} distanceResultField + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @instance + */ + FindNearest.prototype.distanceResultField = ""; + + /** + * FindNearest distanceThreshold. + * @member {google.protobuf.IDoubleValue|null|undefined} distanceThreshold + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @instance + */ + FindNearest.prototype.distanceThreshold = null; + + /** + * Creates a FindNearest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredQuery.FindNearest} FindNearest + */ + FindNearest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.FindNearest) + return object; + var message = new $root.google.firestore.v1.StructuredQuery.FindNearest(); + if (object.vectorField != null) { + if (typeof object.vectorField !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.FindNearest.vectorField: object expected"); + message.vectorField = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.vectorField); + } + if (object.queryVector != null) { + if (typeof object.queryVector !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.FindNearest.queryVector: object expected"); + message.queryVector = $root.google.firestore.v1.Value.fromObject(object.queryVector); + } + switch (object.distanceMeasure) { + default: + if (typeof object.distanceMeasure === "number") { + message.distanceMeasure = object.distanceMeasure; + break; + } + break; + case "DISTANCE_MEASURE_UNSPECIFIED": + case 0: + message.distanceMeasure = 0; + break; + case "EUCLIDEAN": + case 1: + message.distanceMeasure = 1; + break; + case "COSINE": + case 2: + message.distanceMeasure = 2; + break; + case "DOT_PRODUCT": + case 3: + message.distanceMeasure = 3; + break; + } + if (object.limit != null) { + if (typeof object.limit !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.FindNearest.limit: object expected"); + message.limit = $root.google.protobuf.Int32Value.fromObject(object.limit); + } + if (object.distanceResultField != null) + message.distanceResultField = String(object.distanceResultField); + if (object.distanceThreshold != null) { + if (typeof object.distanceThreshold !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.FindNearest.distanceThreshold: object expected"); + message.distanceThreshold = $root.google.protobuf.DoubleValue.fromObject(object.distanceThreshold); + } + return message; + }; + + /** + * Creates a plain object from a FindNearest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @static + * @param {google.firestore.v1.StructuredQuery.FindNearest} message FindNearest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FindNearest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.vectorField = null; + object.queryVector = null; + object.distanceMeasure = options.enums === String ? "DISTANCE_MEASURE_UNSPECIFIED" : 0; + object.limit = null; + object.distanceResultField = ""; + object.distanceThreshold = null; + } + if (message.vectorField != null && message.hasOwnProperty("vectorField")) + object.vectorField = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.vectorField, options); + if (message.queryVector != null && message.hasOwnProperty("queryVector")) + object.queryVector = $root.google.firestore.v1.Value.toObject(message.queryVector, options); + if (message.distanceMeasure != null && message.hasOwnProperty("distanceMeasure")) + object.distanceMeasure = options.enums === String ? $root.google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure[message.distanceMeasure] === undefined ? message.distanceMeasure : $root.google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure[message.distanceMeasure] : message.distanceMeasure; + if (message.limit != null && message.hasOwnProperty("limit")) + object.limit = $root.google.protobuf.Int32Value.toObject(message.limit, options); + if (message.distanceResultField != null && message.hasOwnProperty("distanceResultField")) + object.distanceResultField = message.distanceResultField; + if (message.distanceThreshold != null && message.hasOwnProperty("distanceThreshold")) + object.distanceThreshold = $root.google.protobuf.DoubleValue.toObject(message.distanceThreshold, options); + return object; + }; + + /** + * Converts this FindNearest to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @instance + * @returns {Object.} JSON object + */ + FindNearest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FindNearest + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FindNearest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.FindNearest"; + }; + + /** + * DistanceMeasure enum. + * @name google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure + * @enum {string} + * @property {string} DISTANCE_MEASURE_UNSPECIFIED=DISTANCE_MEASURE_UNSPECIFIED DISTANCE_MEASURE_UNSPECIFIED value + * @property {string} EUCLIDEAN=EUCLIDEAN EUCLIDEAN value + * @property {string} COSINE=COSINE COSINE value + * @property {string} DOT_PRODUCT=DOT_PRODUCT DOT_PRODUCT value + */ + FindNearest.DistanceMeasure = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DISTANCE_MEASURE_UNSPECIFIED"] = "DISTANCE_MEASURE_UNSPECIFIED"; + values[valuesById[1] = "EUCLIDEAN"] = "EUCLIDEAN"; + values[valuesById[2] = "COSINE"] = "COSINE"; + values[valuesById[3] = "DOT_PRODUCT"] = "DOT_PRODUCT"; + return values; + })(); + + return FindNearest; + })(); + + return StructuredQuery; + })(); + + v1.StructuredAggregationQuery = (function() { + + /** + * Properties of a StructuredAggregationQuery. + * @memberof google.firestore.v1 + * @interface IStructuredAggregationQuery + * @property {google.firestore.v1.IStructuredQuery|null} [structuredQuery] StructuredAggregationQuery structuredQuery + * @property {Array.|null} [aggregations] StructuredAggregationQuery aggregations + */ + + /** + * Constructs a new StructuredAggregationQuery. + * @memberof google.firestore.v1 + * @classdesc Represents a StructuredAggregationQuery. + * @implements IStructuredAggregationQuery + * @constructor + * @param {google.firestore.v1.IStructuredAggregationQuery=} [properties] Properties to set + */ + function StructuredAggregationQuery(properties) { + this.aggregations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * StructuredAggregationQuery structuredQuery. + * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery + * @memberof google.firestore.v1.StructuredAggregationQuery + * @instance + */ + StructuredAggregationQuery.prototype.structuredQuery = null; + + /** + * StructuredAggregationQuery aggregations. + * @member {Array.} aggregations + * @memberof google.firestore.v1.StructuredAggregationQuery + * @instance + */ + StructuredAggregationQuery.prototype.aggregations = $util.emptyArray; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * StructuredAggregationQuery queryType. + * @member {"structuredQuery"|undefined} queryType + * @memberof google.firestore.v1.StructuredAggregationQuery + * @instance + */ + Object.defineProperty(StructuredAggregationQuery.prototype, "queryType", { + get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a StructuredAggregationQuery message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredAggregationQuery + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredAggregationQuery} StructuredAggregationQuery + */ + StructuredAggregationQuery.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredAggregationQuery) + return object; + var message = new $root.google.firestore.v1.StructuredAggregationQuery(); + if (object.structuredQuery != null) { + if (typeof object.structuredQuery !== "object") + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.structuredQuery: object expected"); + message.structuredQuery = $root.google.firestore.v1.StructuredQuery.fromObject(object.structuredQuery); + } + if (object.aggregations) { + if (!Array.isArray(object.aggregations)) + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.aggregations: array expected"); + message.aggregations = []; + for (var i = 0; i < object.aggregations.length; ++i) { + if (typeof object.aggregations[i] !== "object") + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.aggregations: object expected"); + message.aggregations[i] = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.fromObject(object.aggregations[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a StructuredAggregationQuery message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredAggregationQuery + * @static + * @param {google.firestore.v1.StructuredAggregationQuery} message StructuredAggregationQuery + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + StructuredAggregationQuery.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.aggregations = []; + if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { + object.structuredQuery = $root.google.firestore.v1.StructuredQuery.toObject(message.structuredQuery, options); + if (options.oneofs) + object.queryType = "structuredQuery"; + } + if (message.aggregations && message.aggregations.length) { + object.aggregations = []; + for (var j = 0; j < message.aggregations.length; ++j) + object.aggregations[j] = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.toObject(message.aggregations[j], options); + } + return object; + }; + + /** + * Converts this StructuredAggregationQuery to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredAggregationQuery + * @instance + * @returns {Object.} JSON object + */ + StructuredAggregationQuery.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for StructuredAggregationQuery + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredAggregationQuery + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + StructuredAggregationQuery.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery"; + }; + + StructuredAggregationQuery.Aggregation = (function() { + + /** + * Properties of an Aggregation. + * @memberof google.firestore.v1.StructuredAggregationQuery + * @interface IAggregation + * @property {google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null} [count] Aggregation count + * @property {google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null} [sum] Aggregation sum + * @property {google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null} [avg] Aggregation avg + * @property {string|null} [alias] Aggregation alias + */ + + /** + * Constructs a new Aggregation. + * @memberof google.firestore.v1.StructuredAggregationQuery + * @classdesc Represents an Aggregation. + * @implements IAggregation + * @constructor + * @param {google.firestore.v1.StructuredAggregationQuery.IAggregation=} [properties] Properties to set + */ + function Aggregation(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Aggregation count. + * @member {google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null|undefined} count + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @instance + */ + Aggregation.prototype.count = null; + + /** + * Aggregation sum. + * @member {google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null|undefined} sum + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @instance + */ + Aggregation.prototype.sum = null; + + /** + * Aggregation avg. + * @member {google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null|undefined} avg + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @instance + */ + Aggregation.prototype.avg = null; + + /** + * Aggregation alias. + * @member {string} alias + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @instance + */ + Aggregation.prototype.alias = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Aggregation operator. + * @member {"count"|"sum"|"avg"|undefined} operator + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @instance + */ + Object.defineProperty(Aggregation.prototype, "operator", { + get: $util.oneOfGetter($oneOfFields = ["count", "sum", "avg"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates an Aggregation message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredAggregationQuery.Aggregation} Aggregation + */ + Aggregation.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredAggregationQuery.Aggregation) + return object; + var message = new $root.google.firestore.v1.StructuredAggregationQuery.Aggregation(); + if (object.count != null) { + if (typeof object.count !== "object") + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.count: object expected"); + message.count = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Count.fromObject(object.count); + } + if (object.sum != null) { + if (typeof object.sum !== "object") + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.sum: object expected"); + message.sum = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum.fromObject(object.sum); + } + if (object.avg != null) { + if (typeof object.avg !== "object") + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.avg: object expected"); + message.avg = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg.fromObject(object.avg); + } + if (object.alias != null) + message.alias = String(object.alias); + return message; + }; + + /** + * Creates a plain object from an Aggregation message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @static + * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation} message Aggregation + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Aggregation.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.alias = ""; + if (message.count != null && message.hasOwnProperty("count")) { + object.count = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Count.toObject(message.count, options); + if (options.oneofs) + object.operator = "count"; + } + if (message.sum != null && message.hasOwnProperty("sum")) { + object.sum = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum.toObject(message.sum, options); + if (options.oneofs) + object.operator = "sum"; + } + if (message.avg != null && message.hasOwnProperty("avg")) { + object.avg = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg.toObject(message.avg, options); + if (options.oneofs) + object.operator = "avg"; + } + if (message.alias != null && message.hasOwnProperty("alias")) + object.alias = message.alias; + return object; + }; + + /** + * Converts this Aggregation to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @instance + * @returns {Object.} JSON object + */ + Aggregation.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Aggregation + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Aggregation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery.Aggregation"; + }; + + Aggregation.Count = (function() { + + /** + * Properties of a Count. + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @interface ICount + * @property {google.protobuf.IInt64Value|null} [upTo] Count upTo + */ + + /** + * Constructs a new Count. + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @classdesc Represents a Count. + * @implements ICount + * @constructor + * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount=} [properties] Properties to set + */ + function Count(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Count upTo. + * @member {google.protobuf.IInt64Value|null|undefined} upTo + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Count + * @instance + */ + Count.prototype.upTo = null; + + /** + * Creates a Count message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Count + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredAggregationQuery.Aggregation.Count} Count + */ + Count.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Count) + return object; + var message = new $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Count(); + if (object.upTo != null) { + if (typeof object.upTo !== "object") + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.Count.upTo: object expected"); + message.upTo = $root.google.protobuf.Int64Value.fromObject(object.upTo); + } + return message; + }; + + /** + * Creates a plain object from a Count message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Count + * @static + * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.Count} message Count + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Count.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.upTo = null; + if (message.upTo != null && message.hasOwnProperty("upTo")) + object.upTo = $root.google.protobuf.Int64Value.toObject(message.upTo, options); + return object; + }; + + /** + * Converts this Count to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Count + * @instance + * @returns {Object.} JSON object + */ + Count.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Count + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Count + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Count.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery.Aggregation.Count"; + }; + + return Count; + })(); + + Aggregation.Sum = (function() { + + /** + * Properties of a Sum. + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @interface ISum + * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] Sum field + */ + + /** + * Constructs a new Sum. + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @classdesc Represents a Sum. + * @implements ISum + * @constructor + * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum=} [properties] Properties to set + */ + function Sum(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Sum field. + * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum + * @instance + */ + Sum.prototype.field = null; + + /** + * Creates a Sum message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum} Sum + */ + Sum.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum) + return object; + var message = new $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum(); + if (object.field != null) { + if (typeof object.field !== "object") + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum.field: object expected"); + message.field = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.field); + } + return message; + }; + + /** + * Creates a plain object from a Sum message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum + * @static + * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum} message Sum + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Sum.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.field = null; + if (message.field != null && message.hasOwnProperty("field")) + object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); + return object; + }; + + /** + * Converts this Sum to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum + * @instance + * @returns {Object.} JSON object + */ + Sum.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Sum + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Sum.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum"; + }; + + return Sum; + })(); + + Aggregation.Avg = (function() { + + /** + * Properties of an Avg. + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @interface IAvg + * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] Avg field + */ + + /** + * Constructs a new Avg. + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @classdesc Represents an Avg. + * @implements IAvg + * @constructor + * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg=} [properties] Properties to set + */ + function Avg(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Avg field. + * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg + * @instance + */ + Avg.prototype.field = null; + + /** + * Creates an Avg message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg} Avg + */ + Avg.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg) + return object; + var message = new $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg(); + if (object.field != null) { + if (typeof object.field !== "object") + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg.field: object expected"); + message.field = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.field); + } + return message; + }; + + /** + * Creates a plain object from an Avg message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg + * @static + * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg} message Avg + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Avg.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.field = null; + if (message.field != null && message.hasOwnProperty("field")) + object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); + return object; + }; + + /** + * Converts this Avg to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg + * @instance + * @returns {Object.} JSON object + */ + Avg.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Avg + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Avg.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg"; + }; + + return Avg; + })(); + + return Aggregation; + })(); + + return StructuredAggregationQuery; + })(); + + v1.Cursor = (function() { + + /** + * Properties of a Cursor. + * @memberof google.firestore.v1 + * @interface ICursor + * @property {Array.|null} [values] Cursor values + * @property {boolean|null} [before] Cursor before + */ + + /** + * Constructs a new Cursor. + * @memberof google.firestore.v1 + * @classdesc Represents a Cursor. + * @implements ICursor + * @constructor + * @param {google.firestore.v1.ICursor=} [properties] Properties to set + */ + function Cursor(properties) { + this.values = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Cursor values. + * @member {Array.} values + * @memberof google.firestore.v1.Cursor + * @instance + */ + Cursor.prototype.values = $util.emptyArray; + + /** + * Cursor before. + * @member {boolean} before + * @memberof google.firestore.v1.Cursor + * @instance + */ + Cursor.prototype.before = false; + + /** + * Creates a Cursor message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Cursor + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Cursor} Cursor + */ + Cursor.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Cursor) + return object; + var message = new $root.google.firestore.v1.Cursor(); + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".google.firestore.v1.Cursor.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".google.firestore.v1.Cursor.values: object expected"); + message.values[i] = $root.google.firestore.v1.Value.fromObject(object.values[i]); + } + } + if (object.before != null) + message.before = Boolean(object.before); + return message; + }; + + /** + * Creates a plain object from a Cursor message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Cursor + * @static + * @param {google.firestore.v1.Cursor} message Cursor + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Cursor.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.values = []; + if (options.defaults) + object.before = false; + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.google.firestore.v1.Value.toObject(message.values[j], options); + } + if (message.before != null && message.hasOwnProperty("before")) + object.before = message.before; + return object; + }; + + /** + * Converts this Cursor to JSON. + * @function toJSON + * @memberof google.firestore.v1.Cursor + * @instance + * @returns {Object.} JSON object + */ + Cursor.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Cursor + * @function getTypeUrl + * @memberof google.firestore.v1.Cursor + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Cursor.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Cursor"; + }; + + return Cursor; + })(); + + v1.ExplainOptions = (function() { + + /** + * Properties of an ExplainOptions. + * @memberof google.firestore.v1 + * @interface IExplainOptions + * @property {boolean|null} [analyze] ExplainOptions analyze + */ + + /** + * Constructs a new ExplainOptions. + * @memberof google.firestore.v1 + * @classdesc Represents an ExplainOptions. + * @implements IExplainOptions + * @constructor + * @param {google.firestore.v1.IExplainOptions=} [properties] Properties to set + */ + function ExplainOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExplainOptions analyze. + * @member {boolean} analyze + * @memberof google.firestore.v1.ExplainOptions + * @instance + */ + ExplainOptions.prototype.analyze = false; + + /** + * Creates an ExplainOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ExplainOptions + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ExplainOptions} ExplainOptions + */ + ExplainOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ExplainOptions) + return object; + var message = new $root.google.firestore.v1.ExplainOptions(); + if (object.analyze != null) + message.analyze = Boolean(object.analyze); + return message; + }; + + /** + * Creates a plain object from an ExplainOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ExplainOptions + * @static + * @param {google.firestore.v1.ExplainOptions} message ExplainOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExplainOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.analyze = false; + if (message.analyze != null && message.hasOwnProperty("analyze")) + object.analyze = message.analyze; + return object; + }; + + /** + * Converts this ExplainOptions to JSON. + * @function toJSON + * @memberof google.firestore.v1.ExplainOptions + * @instance + * @returns {Object.} JSON object + */ + ExplainOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExplainOptions + * @function getTypeUrl + * @memberof google.firestore.v1.ExplainOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExplainOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ExplainOptions"; + }; + + return ExplainOptions; + })(); + + v1.ExplainMetrics = (function() { + + /** + * Properties of an ExplainMetrics. + * @memberof google.firestore.v1 + * @interface IExplainMetrics + * @property {google.firestore.v1.IPlanSummary|null} [planSummary] ExplainMetrics planSummary + * @property {google.firestore.v1.IExecutionStats|null} [executionStats] ExplainMetrics executionStats + */ + + /** + * Constructs a new ExplainMetrics. + * @memberof google.firestore.v1 + * @classdesc Represents an ExplainMetrics. + * @implements IExplainMetrics + * @constructor + * @param {google.firestore.v1.IExplainMetrics=} [properties] Properties to set + */ + function ExplainMetrics(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExplainMetrics planSummary. + * @member {google.firestore.v1.IPlanSummary|null|undefined} planSummary + * @memberof google.firestore.v1.ExplainMetrics + * @instance + */ + ExplainMetrics.prototype.planSummary = null; + + /** + * ExplainMetrics executionStats. + * @member {google.firestore.v1.IExecutionStats|null|undefined} executionStats + * @memberof google.firestore.v1.ExplainMetrics + * @instance + */ + ExplainMetrics.prototype.executionStats = null; + + /** + * Creates an ExplainMetrics message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ExplainMetrics + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ExplainMetrics} ExplainMetrics + */ + ExplainMetrics.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ExplainMetrics) + return object; + var message = new $root.google.firestore.v1.ExplainMetrics(); + if (object.planSummary != null) { + if (typeof object.planSummary !== "object") + throw TypeError(".google.firestore.v1.ExplainMetrics.planSummary: object expected"); + message.planSummary = $root.google.firestore.v1.PlanSummary.fromObject(object.planSummary); + } + if (object.executionStats != null) { + if (typeof object.executionStats !== "object") + throw TypeError(".google.firestore.v1.ExplainMetrics.executionStats: object expected"); + message.executionStats = $root.google.firestore.v1.ExecutionStats.fromObject(object.executionStats); + } + return message; + }; + + /** + * Creates a plain object from an ExplainMetrics message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ExplainMetrics + * @static + * @param {google.firestore.v1.ExplainMetrics} message ExplainMetrics + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExplainMetrics.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.planSummary = null; + object.executionStats = null; + } + if (message.planSummary != null && message.hasOwnProperty("planSummary")) + object.planSummary = $root.google.firestore.v1.PlanSummary.toObject(message.planSummary, options); + if (message.executionStats != null && message.hasOwnProperty("executionStats")) + object.executionStats = $root.google.firestore.v1.ExecutionStats.toObject(message.executionStats, options); + return object; + }; + + /** + * Converts this ExplainMetrics to JSON. + * @function toJSON + * @memberof google.firestore.v1.ExplainMetrics + * @instance + * @returns {Object.} JSON object + */ + ExplainMetrics.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExplainMetrics + * @function getTypeUrl + * @memberof google.firestore.v1.ExplainMetrics + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExplainMetrics.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ExplainMetrics"; + }; + + return ExplainMetrics; + })(); + + v1.PlanSummary = (function() { + + /** + * Properties of a PlanSummary. + * @memberof google.firestore.v1 + * @interface IPlanSummary + * @property {Array.|null} [indexesUsed] PlanSummary indexesUsed + */ + + /** + * Constructs a new PlanSummary. + * @memberof google.firestore.v1 + * @classdesc Represents a PlanSummary. + * @implements IPlanSummary + * @constructor + * @param {google.firestore.v1.IPlanSummary=} [properties] Properties to set + */ + function PlanSummary(properties) { + this.indexesUsed = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PlanSummary indexesUsed. + * @member {Array.} indexesUsed + * @memberof google.firestore.v1.PlanSummary + * @instance + */ + PlanSummary.prototype.indexesUsed = $util.emptyArray; + + /** + * Creates a PlanSummary message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.PlanSummary + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.PlanSummary} PlanSummary + */ + PlanSummary.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.PlanSummary) + return object; + var message = new $root.google.firestore.v1.PlanSummary(); + if (object.indexesUsed) { + if (!Array.isArray(object.indexesUsed)) + throw TypeError(".google.firestore.v1.PlanSummary.indexesUsed: array expected"); + message.indexesUsed = []; + for (var i = 0; i < object.indexesUsed.length; ++i) { + if (typeof object.indexesUsed[i] !== "object") + throw TypeError(".google.firestore.v1.PlanSummary.indexesUsed: object expected"); + message.indexesUsed[i] = $root.google.protobuf.Struct.fromObject(object.indexesUsed[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a PlanSummary message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.PlanSummary + * @static + * @param {google.firestore.v1.PlanSummary} message PlanSummary + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PlanSummary.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.indexesUsed = []; + if (message.indexesUsed && message.indexesUsed.length) { + object.indexesUsed = []; + for (var j = 0; j < message.indexesUsed.length; ++j) + object.indexesUsed[j] = $root.google.protobuf.Struct.toObject(message.indexesUsed[j], options); + } + return object; + }; + + /** + * Converts this PlanSummary to JSON. + * @function toJSON + * @memberof google.firestore.v1.PlanSummary + * @instance + * @returns {Object.} JSON object + */ + PlanSummary.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PlanSummary + * @function getTypeUrl + * @memberof google.firestore.v1.PlanSummary + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PlanSummary.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.PlanSummary"; + }; + + return PlanSummary; + })(); + + v1.ExecutionStats = (function() { + + /** + * Properties of an ExecutionStats. + * @memberof google.firestore.v1 + * @interface IExecutionStats + * @property {number|string|null} [resultsReturned] ExecutionStats resultsReturned + * @property {google.protobuf.IDuration|null} [executionDuration] ExecutionStats executionDuration + * @property {number|string|null} [readOperations] ExecutionStats readOperations + * @property {google.protobuf.IStruct|null} [debugStats] ExecutionStats debugStats + */ + + /** + * Constructs a new ExecutionStats. + * @memberof google.firestore.v1 + * @classdesc Represents an ExecutionStats. + * @implements IExecutionStats + * @constructor + * @param {google.firestore.v1.IExecutionStats=} [properties] Properties to set + */ + function ExecutionStats(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExecutionStats resultsReturned. + * @member {number|string} resultsReturned + * @memberof google.firestore.v1.ExecutionStats + * @instance + */ + ExecutionStats.prototype.resultsReturned = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * ExecutionStats executionDuration. + * @member {google.protobuf.IDuration|null|undefined} executionDuration + * @memberof google.firestore.v1.ExecutionStats + * @instance + */ + ExecutionStats.prototype.executionDuration = null; + + /** + * ExecutionStats readOperations. + * @member {number|string} readOperations + * @memberof google.firestore.v1.ExecutionStats + * @instance + */ + ExecutionStats.prototype.readOperations = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * ExecutionStats debugStats. + * @member {google.protobuf.IStruct|null|undefined} debugStats + * @memberof google.firestore.v1.ExecutionStats + * @instance + */ + ExecutionStats.prototype.debugStats = null; + + /** + * Creates an ExecutionStats message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ExecutionStats + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ExecutionStats} ExecutionStats + */ + ExecutionStats.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ExecutionStats) + return object; + var message = new $root.google.firestore.v1.ExecutionStats(); + if (object.resultsReturned != null) + if ($util.Long) + (message.resultsReturned = $util.Long.fromValue(object.resultsReturned)).unsigned = false; + else if (typeof object.resultsReturned === "string") + message.resultsReturned = parseInt(object.resultsReturned, 10); + else if (typeof object.resultsReturned === "number") + message.resultsReturned = object.resultsReturned; + else if (typeof object.resultsReturned === "object") + message.resultsReturned = new $util.LongBits(object.resultsReturned.low >>> 0, object.resultsReturned.high >>> 0).toNumber(); + if (object.executionDuration != null) { + if (typeof object.executionDuration !== "object") + throw TypeError(".google.firestore.v1.ExecutionStats.executionDuration: object expected"); + message.executionDuration = $root.google.protobuf.Duration.fromObject(object.executionDuration); + } + if (object.readOperations != null) + if ($util.Long) + (message.readOperations = $util.Long.fromValue(object.readOperations)).unsigned = false; + else if (typeof object.readOperations === "string") + message.readOperations = parseInt(object.readOperations, 10); + else if (typeof object.readOperations === "number") + message.readOperations = object.readOperations; + else if (typeof object.readOperations === "object") + message.readOperations = new $util.LongBits(object.readOperations.low >>> 0, object.readOperations.high >>> 0).toNumber(); + if (object.debugStats != null) { + if (typeof object.debugStats !== "object") + throw TypeError(".google.firestore.v1.ExecutionStats.debugStats: object expected"); + message.debugStats = $root.google.protobuf.Struct.fromObject(object.debugStats); + } + return message; + }; + + /** + * Creates a plain object from an ExecutionStats message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ExecutionStats + * @static + * @param {google.firestore.v1.ExecutionStats} message ExecutionStats + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExecutionStats.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.resultsReturned = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.resultsReturned = options.longs === String ? "0" : 0; + object.executionDuration = null; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.readOperations = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.readOperations = options.longs === String ? "0" : 0; + object.debugStats = null; + } + if (message.resultsReturned != null && message.hasOwnProperty("resultsReturned")) + if (typeof message.resultsReturned === "number") + object.resultsReturned = options.longs === String ? String(message.resultsReturned) : message.resultsReturned; + else + object.resultsReturned = options.longs === String ? $util.Long.prototype.toString.call(message.resultsReturned) : options.longs === Number ? new $util.LongBits(message.resultsReturned.low >>> 0, message.resultsReturned.high >>> 0).toNumber() : message.resultsReturned; + if (message.executionDuration != null && message.hasOwnProperty("executionDuration")) + object.executionDuration = $root.google.protobuf.Duration.toObject(message.executionDuration, options); + if (message.readOperations != null && message.hasOwnProperty("readOperations")) + if (typeof message.readOperations === "number") + object.readOperations = options.longs === String ? String(message.readOperations) : message.readOperations; + else + object.readOperations = options.longs === String ? $util.Long.prototype.toString.call(message.readOperations) : options.longs === Number ? new $util.LongBits(message.readOperations.low >>> 0, message.readOperations.high >>> 0).toNumber() : message.readOperations; + if (message.debugStats != null && message.hasOwnProperty("debugStats")) + object.debugStats = $root.google.protobuf.Struct.toObject(message.debugStats, options); + return object; + }; + + /** + * Converts this ExecutionStats to JSON. + * @function toJSON + * @memberof google.firestore.v1.ExecutionStats + * @instance + * @returns {Object.} JSON object + */ + ExecutionStats.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExecutionStats + * @function getTypeUrl + * @memberof google.firestore.v1.ExecutionStats + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExecutionStats.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ExecutionStats"; + }; + + return ExecutionStats; + })(); + + v1.Write = (function() { + + /** + * Properties of a Write. + * @memberof google.firestore.v1 + * @interface IWrite + * @property {google.firestore.v1.IDocument|null} [update] Write update + * @property {string|null} ["delete"] Write delete + * @property {google.firestore.v1.IDocumentTransform|null} [transform] Write transform + * @property {google.firestore.v1.IDocumentMask|null} [updateMask] Write updateMask + * @property {Array.|null} [updateTransforms] Write updateTransforms + * @property {google.firestore.v1.IPrecondition|null} [currentDocument] Write currentDocument + */ + + /** + * Constructs a new Write. + * @memberof google.firestore.v1 + * @classdesc Represents a Write. + * @implements IWrite + * @constructor + * @param {google.firestore.v1.IWrite=} [properties] Properties to set + */ + function Write(properties) { + this.updateTransforms = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Write update. + * @member {google.firestore.v1.IDocument|null|undefined} update + * @memberof google.firestore.v1.Write + * @instance + */ + Write.prototype.update = null; + + /** + * Write delete. + * @member {string|null|undefined} delete + * @memberof google.firestore.v1.Write + * @instance + */ + Write.prototype["delete"] = null; + + /** + * Write transform. + * @member {google.firestore.v1.IDocumentTransform|null|undefined} transform + * @memberof google.firestore.v1.Write + * @instance + */ + Write.prototype.transform = null; + + /** + * Write updateMask. + * @member {google.firestore.v1.IDocumentMask|null|undefined} updateMask + * @memberof google.firestore.v1.Write + * @instance + */ + Write.prototype.updateMask = null; + + /** + * Write updateTransforms. + * @member {Array.} updateTransforms + * @memberof google.firestore.v1.Write + * @instance + */ + Write.prototype.updateTransforms = $util.emptyArray; + + /** + * Write currentDocument. + * @member {google.firestore.v1.IPrecondition|null|undefined} currentDocument + * @memberof google.firestore.v1.Write + * @instance + */ + Write.prototype.currentDocument = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Write operation. + * @member {"update"|"delete"|"transform"|undefined} operation + * @memberof google.firestore.v1.Write + * @instance + */ + Object.defineProperty(Write.prototype, "operation", { + get: $util.oneOfGetter($oneOfFields = ["update", "delete", "transform"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a Write message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Write + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Write} Write + */ + Write.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Write) + return object; + var message = new $root.google.firestore.v1.Write(); + if (object.update != null) { + if (typeof object.update !== "object") + throw TypeError(".google.firestore.v1.Write.update: object expected"); + message.update = $root.google.firestore.v1.Document.fromObject(object.update); + } + if (object["delete"] != null) + message["delete"] = String(object["delete"]); + if (object.transform != null) { + if (typeof object.transform !== "object") + throw TypeError(".google.firestore.v1.Write.transform: object expected"); + message.transform = $root.google.firestore.v1.DocumentTransform.fromObject(object.transform); + } + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.firestore.v1.Write.updateMask: object expected"); + message.updateMask = $root.google.firestore.v1.DocumentMask.fromObject(object.updateMask); + } + if (object.updateTransforms) { + if (!Array.isArray(object.updateTransforms)) + throw TypeError(".google.firestore.v1.Write.updateTransforms: array expected"); + message.updateTransforms = []; + for (var i = 0; i < object.updateTransforms.length; ++i) { + if (typeof object.updateTransforms[i] !== "object") + throw TypeError(".google.firestore.v1.Write.updateTransforms: object expected"); + message.updateTransforms[i] = $root.google.firestore.v1.DocumentTransform.FieldTransform.fromObject(object.updateTransforms[i]); + } + } + if (object.currentDocument != null) { + if (typeof object.currentDocument !== "object") + throw TypeError(".google.firestore.v1.Write.currentDocument: object expected"); + message.currentDocument = $root.google.firestore.v1.Precondition.fromObject(object.currentDocument); + } + return message; + }; + + /** + * Creates a plain object from a Write message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Write + * @static + * @param {google.firestore.v1.Write} message Write + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Write.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.updateTransforms = []; + if (options.defaults) { + object.updateMask = null; + object.currentDocument = null; + } + if (message.update != null && message.hasOwnProperty("update")) { + object.update = $root.google.firestore.v1.Document.toObject(message.update, options); + if (options.oneofs) + object.operation = "update"; + } + if (message["delete"] != null && message.hasOwnProperty("delete")) { + object["delete"] = message["delete"]; + if (options.oneofs) + object.operation = "delete"; + } + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.firestore.v1.DocumentMask.toObject(message.updateMask, options); + if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) + object.currentDocument = $root.google.firestore.v1.Precondition.toObject(message.currentDocument, options); + if (message.transform != null && message.hasOwnProperty("transform")) { + object.transform = $root.google.firestore.v1.DocumentTransform.toObject(message.transform, options); + if (options.oneofs) + object.operation = "transform"; + } + if (message.updateTransforms && message.updateTransforms.length) { + object.updateTransforms = []; + for (var j = 0; j < message.updateTransforms.length; ++j) + object.updateTransforms[j] = $root.google.firestore.v1.DocumentTransform.FieldTransform.toObject(message.updateTransforms[j], options); + } + return object; + }; + + /** + * Converts this Write to JSON. + * @function toJSON + * @memberof google.firestore.v1.Write + * @instance + * @returns {Object.} JSON object + */ + Write.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Write + * @function getTypeUrl + * @memberof google.firestore.v1.Write + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Write.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Write"; + }; + + return Write; + })(); + + v1.DocumentTransform = (function() { + + /** + * Properties of a DocumentTransform. + * @memberof google.firestore.v1 + * @interface IDocumentTransform + * @property {string|null} [document] DocumentTransform document + * @property {Array.|null} [fieldTransforms] DocumentTransform fieldTransforms + */ + + /** + * Constructs a new DocumentTransform. + * @memberof google.firestore.v1 + * @classdesc Represents a DocumentTransform. + * @implements IDocumentTransform + * @constructor + * @param {google.firestore.v1.IDocumentTransform=} [properties] Properties to set + */ + function DocumentTransform(properties) { + this.fieldTransforms = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DocumentTransform document. + * @member {string} document + * @memberof google.firestore.v1.DocumentTransform + * @instance + */ + DocumentTransform.prototype.document = ""; + + /** + * DocumentTransform fieldTransforms. + * @member {Array.} fieldTransforms + * @memberof google.firestore.v1.DocumentTransform + * @instance + */ + DocumentTransform.prototype.fieldTransforms = $util.emptyArray; + + /** + * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.DocumentTransform + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.DocumentTransform} DocumentTransform + */ + DocumentTransform.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.DocumentTransform) + return object; + var message = new $root.google.firestore.v1.DocumentTransform(); + if (object.document != null) + message.document = String(object.document); + if (object.fieldTransforms) { + if (!Array.isArray(object.fieldTransforms)) + throw TypeError(".google.firestore.v1.DocumentTransform.fieldTransforms: array expected"); + message.fieldTransforms = []; + for (var i = 0; i < object.fieldTransforms.length; ++i) { + if (typeof object.fieldTransforms[i] !== "object") + throw TypeError(".google.firestore.v1.DocumentTransform.fieldTransforms: object expected"); + message.fieldTransforms[i] = $root.google.firestore.v1.DocumentTransform.FieldTransform.fromObject(object.fieldTransforms[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.DocumentTransform + * @static + * @param {google.firestore.v1.DocumentTransform} message DocumentTransform + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DocumentTransform.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.fieldTransforms = []; + if (options.defaults) + object.document = ""; + if (message.document != null && message.hasOwnProperty("document")) + object.document = message.document; + if (message.fieldTransforms && message.fieldTransforms.length) { + object.fieldTransforms = []; + for (var j = 0; j < message.fieldTransforms.length; ++j) + object.fieldTransforms[j] = $root.google.firestore.v1.DocumentTransform.FieldTransform.toObject(message.fieldTransforms[j], options); + } + return object; + }; + + /** + * Converts this DocumentTransform to JSON. + * @function toJSON + * @memberof google.firestore.v1.DocumentTransform + * @instance + * @returns {Object.} JSON object + */ + DocumentTransform.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DocumentTransform + * @function getTypeUrl + * @memberof google.firestore.v1.DocumentTransform + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DocumentTransform.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.DocumentTransform"; + }; + + DocumentTransform.FieldTransform = (function() { + + /** + * Properties of a FieldTransform. + * @memberof google.firestore.v1.DocumentTransform + * @interface IFieldTransform + * @property {string|null} [fieldPath] FieldTransform fieldPath + * @property {google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null} [setToServerValue] FieldTransform setToServerValue + * @property {google.firestore.v1.IValue|null} [increment] FieldTransform increment + * @property {google.firestore.v1.IValue|null} [maximum] FieldTransform maximum + * @property {google.firestore.v1.IValue|null} [minimum] FieldTransform minimum + * @property {google.firestore.v1.IArrayValue|null} [appendMissingElements] FieldTransform appendMissingElements + * @property {google.firestore.v1.IArrayValue|null} [removeAllFromArray] FieldTransform removeAllFromArray + */ + + /** + * Constructs a new FieldTransform. + * @memberof google.firestore.v1.DocumentTransform + * @classdesc Represents a FieldTransform. + * @implements IFieldTransform + * @constructor + * @param {google.firestore.v1.DocumentTransform.IFieldTransform=} [properties] Properties to set + */ + function FieldTransform(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldTransform fieldPath. + * @member {string} fieldPath + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.fieldPath = ""; + + /** + * FieldTransform setToServerValue. + * @member {google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null|undefined} setToServerValue + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.setToServerValue = null; + + /** + * FieldTransform increment. + * @member {google.firestore.v1.IValue|null|undefined} increment + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.increment = null; + + /** + * FieldTransform maximum. + * @member {google.firestore.v1.IValue|null|undefined} maximum + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.maximum = null; + + /** + * FieldTransform minimum. + * @member {google.firestore.v1.IValue|null|undefined} minimum + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.minimum = null; + + /** + * FieldTransform appendMissingElements. + * @member {google.firestore.v1.IArrayValue|null|undefined} appendMissingElements + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.appendMissingElements = null; + + /** + * FieldTransform removeAllFromArray. + * @member {google.firestore.v1.IArrayValue|null|undefined} removeAllFromArray + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.removeAllFromArray = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * FieldTransform transformType. + * @member {"setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"|undefined} transformType + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + */ + Object.defineProperty(FieldTransform.prototype, "transformType", { + get: $util.oneOfGetter($oneOfFields = ["setToServerValue", "increment", "maximum", "minimum", "appendMissingElements", "removeAllFromArray"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.DocumentTransform.FieldTransform} FieldTransform + */ + FieldTransform.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.DocumentTransform.FieldTransform) + return object; + var message = new $root.google.firestore.v1.DocumentTransform.FieldTransform(); + if (object.fieldPath != null) + message.fieldPath = String(object.fieldPath); + switch (object.setToServerValue) { + default: + if (typeof object.setToServerValue === "number") { + message.setToServerValue = object.setToServerValue; + break; + } + break; + case "SERVER_VALUE_UNSPECIFIED": + case 0: + message.setToServerValue = 0; + break; + case "REQUEST_TIME": + case 1: + message.setToServerValue = 1; + break; + } + if (object.increment != null) { + if (typeof object.increment !== "object") + throw TypeError(".google.firestore.v1.DocumentTransform.FieldTransform.increment: object expected"); + message.increment = $root.google.firestore.v1.Value.fromObject(object.increment); + } + if (object.maximum != null) { + if (typeof object.maximum !== "object") + throw TypeError(".google.firestore.v1.DocumentTransform.FieldTransform.maximum: object expected"); + message.maximum = $root.google.firestore.v1.Value.fromObject(object.maximum); + } + if (object.minimum != null) { + if (typeof object.minimum !== "object") + throw TypeError(".google.firestore.v1.DocumentTransform.FieldTransform.minimum: object expected"); + message.minimum = $root.google.firestore.v1.Value.fromObject(object.minimum); + } + if (object.appendMissingElements != null) { + if (typeof object.appendMissingElements !== "object") + throw TypeError(".google.firestore.v1.DocumentTransform.FieldTransform.appendMissingElements: object expected"); + message.appendMissingElements = $root.google.firestore.v1.ArrayValue.fromObject(object.appendMissingElements); + } + if (object.removeAllFromArray != null) { + if (typeof object.removeAllFromArray !== "object") + throw TypeError(".google.firestore.v1.DocumentTransform.FieldTransform.removeAllFromArray: object expected"); + message.removeAllFromArray = $root.google.firestore.v1.ArrayValue.fromObject(object.removeAllFromArray); + } + return message; + }; + + /** + * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @static + * @param {google.firestore.v1.DocumentTransform.FieldTransform} message FieldTransform + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldTransform.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.fieldPath = ""; + if (message.fieldPath != null && message.hasOwnProperty("fieldPath")) + object.fieldPath = message.fieldPath; + if (message.setToServerValue != null && message.hasOwnProperty("setToServerValue")) { + object.setToServerValue = options.enums === String ? $root.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue[message.setToServerValue] === undefined ? message.setToServerValue : $root.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue[message.setToServerValue] : message.setToServerValue; + if (options.oneofs) + object.transformType = "setToServerValue"; + } + if (message.increment != null && message.hasOwnProperty("increment")) { + object.increment = $root.google.firestore.v1.Value.toObject(message.increment, options); + if (options.oneofs) + object.transformType = "increment"; + } + if (message.maximum != null && message.hasOwnProperty("maximum")) { + object.maximum = $root.google.firestore.v1.Value.toObject(message.maximum, options); + if (options.oneofs) + object.transformType = "maximum"; + } + if (message.minimum != null && message.hasOwnProperty("minimum")) { + object.minimum = $root.google.firestore.v1.Value.toObject(message.minimum, options); + if (options.oneofs) + object.transformType = "minimum"; + } + if (message.appendMissingElements != null && message.hasOwnProperty("appendMissingElements")) { + object.appendMissingElements = $root.google.firestore.v1.ArrayValue.toObject(message.appendMissingElements, options); + if (options.oneofs) + object.transformType = "appendMissingElements"; + } + if (message.removeAllFromArray != null && message.hasOwnProperty("removeAllFromArray")) { + object.removeAllFromArray = $root.google.firestore.v1.ArrayValue.toObject(message.removeAllFromArray, options); + if (options.oneofs) + object.transformType = "removeAllFromArray"; + } + return object; + }; + + /** + * Converts this FieldTransform to JSON. + * @function toJSON + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + * @returns {Object.} JSON object + */ + FieldTransform.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldTransform + * @function getTypeUrl + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldTransform.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.DocumentTransform.FieldTransform"; + }; + + /** + * ServerValue enum. + * @name google.firestore.v1.DocumentTransform.FieldTransform.ServerValue + * @enum {string} + * @property {string} SERVER_VALUE_UNSPECIFIED=SERVER_VALUE_UNSPECIFIED SERVER_VALUE_UNSPECIFIED value + * @property {string} REQUEST_TIME=REQUEST_TIME REQUEST_TIME value + */ + FieldTransform.ServerValue = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "SERVER_VALUE_UNSPECIFIED"] = "SERVER_VALUE_UNSPECIFIED"; + values[valuesById[1] = "REQUEST_TIME"] = "REQUEST_TIME"; + return values; + })(); + + return FieldTransform; + })(); + + return DocumentTransform; + })(); + + v1.WriteResult = (function() { + + /** + * Properties of a WriteResult. + * @memberof google.firestore.v1 + * @interface IWriteResult + * @property {google.protobuf.ITimestamp|null} [updateTime] WriteResult updateTime + * @property {Array.|null} [transformResults] WriteResult transformResults + */ + + /** + * Constructs a new WriteResult. + * @memberof google.firestore.v1 + * @classdesc Represents a WriteResult. + * @implements IWriteResult + * @constructor + * @param {google.firestore.v1.IWriteResult=} [properties] Properties to set + */ + function WriteResult(properties) { + this.transformResults = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * WriteResult updateTime. + * @member {google.protobuf.ITimestamp|null|undefined} updateTime + * @memberof google.firestore.v1.WriteResult + * @instance + */ + WriteResult.prototype.updateTime = null; + + /** + * WriteResult transformResults. + * @member {Array.} transformResults + * @memberof google.firestore.v1.WriteResult + * @instance + */ + WriteResult.prototype.transformResults = $util.emptyArray; + + /** + * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.WriteResult + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.WriteResult} WriteResult + */ + WriteResult.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.WriteResult) + return object; + var message = new $root.google.firestore.v1.WriteResult(); + if (object.updateTime != null) { + if (typeof object.updateTime !== "object") + throw TypeError(".google.firestore.v1.WriteResult.updateTime: object expected"); + message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + } + if (object.transformResults) { + if (!Array.isArray(object.transformResults)) + throw TypeError(".google.firestore.v1.WriteResult.transformResults: array expected"); + message.transformResults = []; + for (var i = 0; i < object.transformResults.length; ++i) { + if (typeof object.transformResults[i] !== "object") + throw TypeError(".google.firestore.v1.WriteResult.transformResults: object expected"); + message.transformResults[i] = $root.google.firestore.v1.Value.fromObject(object.transformResults[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a WriteResult message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.WriteResult + * @static + * @param {google.firestore.v1.WriteResult} message WriteResult + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WriteResult.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.transformResults = []; + if (options.defaults) + object.updateTime = null; + if (message.updateTime != null && message.hasOwnProperty("updateTime")) + object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + if (message.transformResults && message.transformResults.length) { + object.transformResults = []; + for (var j = 0; j < message.transformResults.length; ++j) + object.transformResults[j] = $root.google.firestore.v1.Value.toObject(message.transformResults[j], options); + } + return object; + }; + + /** + * Converts this WriteResult to JSON. + * @function toJSON + * @memberof google.firestore.v1.WriteResult + * @instance + * @returns {Object.} JSON object + */ + WriteResult.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for WriteResult + * @function getTypeUrl + * @memberof google.firestore.v1.WriteResult + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WriteResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.WriteResult"; + }; + + return WriteResult; + })(); + + v1.DocumentChange = (function() { + + /** + * Properties of a DocumentChange. + * @memberof google.firestore.v1 + * @interface IDocumentChange + * @property {google.firestore.v1.IDocument|null} [document] DocumentChange document + * @property {Array.|null} [targetIds] DocumentChange targetIds + * @property {Array.|null} [removedTargetIds] DocumentChange removedTargetIds + */ + + /** + * Constructs a new DocumentChange. + * @memberof google.firestore.v1 + * @classdesc Represents a DocumentChange. + * @implements IDocumentChange + * @constructor + * @param {google.firestore.v1.IDocumentChange=} [properties] Properties to set + */ + function DocumentChange(properties) { + this.targetIds = []; + this.removedTargetIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DocumentChange document. + * @member {google.firestore.v1.IDocument|null|undefined} document + * @memberof google.firestore.v1.DocumentChange + * @instance + */ + DocumentChange.prototype.document = null; + + /** + * DocumentChange targetIds. + * @member {Array.} targetIds + * @memberof google.firestore.v1.DocumentChange + * @instance + */ + DocumentChange.prototype.targetIds = $util.emptyArray; + + /** + * DocumentChange removedTargetIds. + * @member {Array.} removedTargetIds + * @memberof google.firestore.v1.DocumentChange + * @instance + */ + DocumentChange.prototype.removedTargetIds = $util.emptyArray; + + /** + * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.DocumentChange + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.DocumentChange} DocumentChange + */ + DocumentChange.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.DocumentChange) + return object; + var message = new $root.google.firestore.v1.DocumentChange(); + if (object.document != null) { + if (typeof object.document !== "object") + throw TypeError(".google.firestore.v1.DocumentChange.document: object expected"); + message.document = $root.google.firestore.v1.Document.fromObject(object.document); + } + if (object.targetIds) { + if (!Array.isArray(object.targetIds)) + throw TypeError(".google.firestore.v1.DocumentChange.targetIds: array expected"); + message.targetIds = []; + for (var i = 0; i < object.targetIds.length; ++i) + message.targetIds[i] = object.targetIds[i] | 0; + } + if (object.removedTargetIds) { + if (!Array.isArray(object.removedTargetIds)) + throw TypeError(".google.firestore.v1.DocumentChange.removedTargetIds: array expected"); + message.removedTargetIds = []; + for (var i = 0; i < object.removedTargetIds.length; ++i) + message.removedTargetIds[i] = object.removedTargetIds[i] | 0; + } + return message; + }; + + /** + * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.DocumentChange + * @static + * @param {google.firestore.v1.DocumentChange} message DocumentChange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DocumentChange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.targetIds = []; + object.removedTargetIds = []; + } + if (options.defaults) + object.document = null; + if (message.document != null && message.hasOwnProperty("document")) + object.document = $root.google.firestore.v1.Document.toObject(message.document, options); + if (message.targetIds && message.targetIds.length) { + object.targetIds = []; + for (var j = 0; j < message.targetIds.length; ++j) + object.targetIds[j] = message.targetIds[j]; + } + if (message.removedTargetIds && message.removedTargetIds.length) { + object.removedTargetIds = []; + for (var j = 0; j < message.removedTargetIds.length; ++j) + object.removedTargetIds[j] = message.removedTargetIds[j]; + } + return object; + }; + + /** + * Converts this DocumentChange to JSON. + * @function toJSON + * @memberof google.firestore.v1.DocumentChange + * @instance + * @returns {Object.} JSON object + */ + DocumentChange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DocumentChange + * @function getTypeUrl + * @memberof google.firestore.v1.DocumentChange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DocumentChange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.DocumentChange"; + }; + + return DocumentChange; + })(); + + v1.DocumentDelete = (function() { + + /** + * Properties of a DocumentDelete. + * @memberof google.firestore.v1 + * @interface IDocumentDelete + * @property {string|null} [document] DocumentDelete document + * @property {Array.|null} [removedTargetIds] DocumentDelete removedTargetIds + * @property {google.protobuf.ITimestamp|null} [readTime] DocumentDelete readTime + */ + + /** + * Constructs a new DocumentDelete. + * @memberof google.firestore.v1 + * @classdesc Represents a DocumentDelete. + * @implements IDocumentDelete + * @constructor + * @param {google.firestore.v1.IDocumentDelete=} [properties] Properties to set + */ + function DocumentDelete(properties) { + this.removedTargetIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DocumentDelete document. + * @member {string} document + * @memberof google.firestore.v1.DocumentDelete + * @instance + */ + DocumentDelete.prototype.document = ""; + + /** + * DocumentDelete removedTargetIds. + * @member {Array.} removedTargetIds + * @memberof google.firestore.v1.DocumentDelete + * @instance + */ + DocumentDelete.prototype.removedTargetIds = $util.emptyArray; + + /** + * DocumentDelete readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.DocumentDelete + * @instance + */ + DocumentDelete.prototype.readTime = null; + + /** + * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.DocumentDelete + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.DocumentDelete} DocumentDelete + */ + DocumentDelete.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.DocumentDelete) + return object; + var message = new $root.google.firestore.v1.DocumentDelete(); + if (object.document != null) + message.document = String(object.document); + if (object.removedTargetIds) { + if (!Array.isArray(object.removedTargetIds)) + throw TypeError(".google.firestore.v1.DocumentDelete.removedTargetIds: array expected"); + message.removedTargetIds = []; + for (var i = 0; i < object.removedTargetIds.length; ++i) + message.removedTargetIds[i] = object.removedTargetIds[i] | 0; + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.DocumentDelete.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.DocumentDelete + * @static + * @param {google.firestore.v1.DocumentDelete} message DocumentDelete + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DocumentDelete.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.removedTargetIds = []; + if (options.defaults) { + object.document = ""; + object.readTime = null; + } + if (message.document != null && message.hasOwnProperty("document")) + object.document = message.document; + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (message.removedTargetIds && message.removedTargetIds.length) { + object.removedTargetIds = []; + for (var j = 0; j < message.removedTargetIds.length; ++j) + object.removedTargetIds[j] = message.removedTargetIds[j]; + } + return object; + }; + + /** + * Converts this DocumentDelete to JSON. + * @function toJSON + * @memberof google.firestore.v1.DocumentDelete + * @instance + * @returns {Object.} JSON object + */ + DocumentDelete.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DocumentDelete + * @function getTypeUrl + * @memberof google.firestore.v1.DocumentDelete + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DocumentDelete.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.DocumentDelete"; + }; + + return DocumentDelete; + })(); + + v1.DocumentRemove = (function() { + + /** + * Properties of a DocumentRemove. + * @memberof google.firestore.v1 + * @interface IDocumentRemove + * @property {string|null} [document] DocumentRemove document + * @property {Array.|null} [removedTargetIds] DocumentRemove removedTargetIds + * @property {google.protobuf.ITimestamp|null} [readTime] DocumentRemove readTime + */ + + /** + * Constructs a new DocumentRemove. + * @memberof google.firestore.v1 + * @classdesc Represents a DocumentRemove. + * @implements IDocumentRemove + * @constructor + * @param {google.firestore.v1.IDocumentRemove=} [properties] Properties to set + */ + function DocumentRemove(properties) { + this.removedTargetIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DocumentRemove document. + * @member {string} document + * @memberof google.firestore.v1.DocumentRemove + * @instance + */ + DocumentRemove.prototype.document = ""; + + /** + * DocumentRemove removedTargetIds. + * @member {Array.} removedTargetIds + * @memberof google.firestore.v1.DocumentRemove + * @instance + */ + DocumentRemove.prototype.removedTargetIds = $util.emptyArray; + + /** + * DocumentRemove readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.DocumentRemove + * @instance + */ + DocumentRemove.prototype.readTime = null; + + /** + * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.DocumentRemove + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.DocumentRemove} DocumentRemove + */ + DocumentRemove.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.DocumentRemove) + return object; + var message = new $root.google.firestore.v1.DocumentRemove(); + if (object.document != null) + message.document = String(object.document); + if (object.removedTargetIds) { + if (!Array.isArray(object.removedTargetIds)) + throw TypeError(".google.firestore.v1.DocumentRemove.removedTargetIds: array expected"); + message.removedTargetIds = []; + for (var i = 0; i < object.removedTargetIds.length; ++i) + message.removedTargetIds[i] = object.removedTargetIds[i] | 0; + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.DocumentRemove.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.DocumentRemove + * @static + * @param {google.firestore.v1.DocumentRemove} message DocumentRemove + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DocumentRemove.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.removedTargetIds = []; + if (options.defaults) { + object.document = ""; + object.readTime = null; + } + if (message.document != null && message.hasOwnProperty("document")) + object.document = message.document; + if (message.removedTargetIds && message.removedTargetIds.length) { + object.removedTargetIds = []; + for (var j = 0; j < message.removedTargetIds.length; ++j) + object.removedTargetIds[j] = message.removedTargetIds[j]; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + return object; + }; + + /** + * Converts this DocumentRemove to JSON. + * @function toJSON + * @memberof google.firestore.v1.DocumentRemove + * @instance + * @returns {Object.} JSON object + */ + DocumentRemove.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DocumentRemove + * @function getTypeUrl + * @memberof google.firestore.v1.DocumentRemove + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DocumentRemove.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.DocumentRemove"; + }; + + return DocumentRemove; + })(); + + v1.ExistenceFilter = (function() { + + /** + * Properties of an ExistenceFilter. + * @memberof google.firestore.v1 + * @interface IExistenceFilter + * @property {number|null} [targetId] ExistenceFilter targetId + * @property {number|null} [count] ExistenceFilter count + * @property {google.firestore.v1.IBloomFilter|null} [unchangedNames] ExistenceFilter unchangedNames + */ + + /** + * Constructs a new ExistenceFilter. + * @memberof google.firestore.v1 + * @classdesc Represents an ExistenceFilter. + * @implements IExistenceFilter + * @constructor + * @param {google.firestore.v1.IExistenceFilter=} [properties] Properties to set + */ + function ExistenceFilter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExistenceFilter targetId. + * @member {number} targetId + * @memberof google.firestore.v1.ExistenceFilter + * @instance + */ + ExistenceFilter.prototype.targetId = 0; + + /** + * ExistenceFilter count. + * @member {number} count + * @memberof google.firestore.v1.ExistenceFilter + * @instance + */ + ExistenceFilter.prototype.count = 0; + + /** + * ExistenceFilter unchangedNames. + * @member {google.firestore.v1.IBloomFilter|null|undefined} unchangedNames + * @memberof google.firestore.v1.ExistenceFilter + * @instance + */ + ExistenceFilter.prototype.unchangedNames = null; + + /** + * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ExistenceFilter + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ExistenceFilter} ExistenceFilter + */ + ExistenceFilter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ExistenceFilter) + return object; + var message = new $root.google.firestore.v1.ExistenceFilter(); + if (object.targetId != null) + message.targetId = object.targetId | 0; + if (object.count != null) + message.count = object.count | 0; + if (object.unchangedNames != null) { + if (typeof object.unchangedNames !== "object") + throw TypeError(".google.firestore.v1.ExistenceFilter.unchangedNames: object expected"); + message.unchangedNames = $root.google.firestore.v1.BloomFilter.fromObject(object.unchangedNames); + } + return message; + }; + + /** + * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ExistenceFilter + * @static + * @param {google.firestore.v1.ExistenceFilter} message ExistenceFilter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExistenceFilter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.targetId = 0; + object.count = 0; + object.unchangedNames = null; + } + if (message.targetId != null && message.hasOwnProperty("targetId")) + object.targetId = message.targetId; + if (message.count != null && message.hasOwnProperty("count")) + object.count = message.count; + if (message.unchangedNames != null && message.hasOwnProperty("unchangedNames")) + object.unchangedNames = $root.google.firestore.v1.BloomFilter.toObject(message.unchangedNames, options); + return object; + }; + + /** + * Converts this ExistenceFilter to JSON. + * @function toJSON + * @memberof google.firestore.v1.ExistenceFilter + * @instance + * @returns {Object.} JSON object + */ + ExistenceFilter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExistenceFilter + * @function getTypeUrl + * @memberof google.firestore.v1.ExistenceFilter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExistenceFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ExistenceFilter"; + }; + + return ExistenceFilter; + })(); + + return v1; + })(); + + return firestore; + })(); + + google.api = (function() { + + /** + * Namespace api. + * @memberof google + * @namespace + */ + var api = {}; + + /** + * FieldBehavior enum. + * @name google.api.FieldBehavior + * @enum {string} + * @property {string} FIELD_BEHAVIOR_UNSPECIFIED=FIELD_BEHAVIOR_UNSPECIFIED FIELD_BEHAVIOR_UNSPECIFIED value + * @property {string} OPTIONAL=OPTIONAL OPTIONAL value + * @property {string} REQUIRED=REQUIRED REQUIRED value + * @property {string} OUTPUT_ONLY=OUTPUT_ONLY OUTPUT_ONLY value + * @property {string} INPUT_ONLY=INPUT_ONLY INPUT_ONLY value + * @property {string} IMMUTABLE=IMMUTABLE IMMUTABLE value + * @property {string} UNORDERED_LIST=UNORDERED_LIST UNORDERED_LIST value + * @property {string} NON_EMPTY_DEFAULT=NON_EMPTY_DEFAULT NON_EMPTY_DEFAULT value + * @property {string} IDENTIFIER=IDENTIFIER IDENTIFIER value + */ + api.FieldBehavior = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "FIELD_BEHAVIOR_UNSPECIFIED"] = "FIELD_BEHAVIOR_UNSPECIFIED"; + values[valuesById[1] = "OPTIONAL"] = "OPTIONAL"; + values[valuesById[2] = "REQUIRED"] = "REQUIRED"; + values[valuesById[3] = "OUTPUT_ONLY"] = "OUTPUT_ONLY"; + values[valuesById[4] = "INPUT_ONLY"] = "INPUT_ONLY"; + values[valuesById[5] = "IMMUTABLE"] = "IMMUTABLE"; + values[valuesById[6] = "UNORDERED_LIST"] = "UNORDERED_LIST"; + values[valuesById[7] = "NON_EMPTY_DEFAULT"] = "NON_EMPTY_DEFAULT"; + values[valuesById[8] = "IDENTIFIER"] = "IDENTIFIER"; + return values; + })(); + + api.Http = (function() { + + /** + * Properties of a Http. + * @memberof google.api + * @interface IHttp + * @property {Array.|null} [rules] Http rules + * @property {boolean|null} [fullyDecodeReservedExpansion] Http fullyDecodeReservedExpansion + */ + + /** + * Constructs a new Http. + * @memberof google.api + * @classdesc Represents a Http. + * @implements IHttp + * @constructor + * @param {google.api.IHttp=} [properties] Properties to set + */ + function Http(properties) { + this.rules = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Http rules. + * @member {Array.} rules + * @memberof google.api.Http + * @instance + */ + Http.prototype.rules = $util.emptyArray; + + /** + * Http fullyDecodeReservedExpansion. + * @member {boolean} fullyDecodeReservedExpansion + * @memberof google.api.Http + * @instance + */ + Http.prototype.fullyDecodeReservedExpansion = false; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.Http + * @static + * @param {Object.} object Plain object + * @returns {google.api.Http} Http + */ + Http.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.Http) + return object; + var message = new $root.google.api.Http(); + if (object.rules) { + if (!Array.isArray(object.rules)) + throw TypeError(".google.api.Http.rules: array expected"); + message.rules = []; + for (var i = 0; i < object.rules.length; ++i) { + if (typeof object.rules[i] !== "object") + throw TypeError(".google.api.Http.rules: object expected"); + message.rules[i] = $root.google.api.HttpRule.fromObject(object.rules[i]); + } + } + if (object.fullyDecodeReservedExpansion != null) + message.fullyDecodeReservedExpansion = Boolean(object.fullyDecodeReservedExpansion); + return message; + }; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.Http + * @static + * @param {google.api.Http} message Http + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Http.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.rules = []; + if (options.defaults) + object.fullyDecodeReservedExpansion = false; + if (message.rules && message.rules.length) { + object.rules = []; + for (var j = 0; j < message.rules.length; ++j) + object.rules[j] = $root.google.api.HttpRule.toObject(message.rules[j], options); + } + if (message.fullyDecodeReservedExpansion != null && message.hasOwnProperty("fullyDecodeReservedExpansion")) + object.fullyDecodeReservedExpansion = message.fullyDecodeReservedExpansion; + return object; + }; + + /** + * Converts this Http to JSON. + * @function toJSON + * @memberof google.api.Http + * @instance + * @returns {Object.} JSON object + */ + Http.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Http + * @function getTypeUrl + * @memberof google.api.Http + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Http.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.Http"; + }; + + return Http; + })(); + + api.HttpRule = (function() { + + /** + * Properties of a HttpRule. + * @memberof google.api + * @interface IHttpRule + * @property {string|null} [selector] HttpRule selector + * @property {string|null} [get] HttpRule get + * @property {string|null} [put] HttpRule put + * @property {string|null} [post] HttpRule post + * @property {string|null} ["delete"] HttpRule delete + * @property {string|null} [patch] HttpRule patch + * @property {google.api.ICustomHttpPattern|null} [custom] HttpRule custom + * @property {string|null} [body] HttpRule body + * @property {string|null} [responseBody] HttpRule responseBody + * @property {Array.|null} [additionalBindings] HttpRule additionalBindings + */ + + /** + * Constructs a new HttpRule. + * @memberof google.api + * @classdesc Represents a HttpRule. + * @implements IHttpRule + * @constructor + * @param {google.api.IHttpRule=} [properties] Properties to set + */ + function HttpRule(properties) { + this.additionalBindings = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * HttpRule selector. + * @member {string} selector + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.selector = ""; + + /** + * HttpRule get. + * @member {string|null|undefined} get + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.get = null; + + /** + * HttpRule put. + * @member {string|null|undefined} put + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.put = null; + + /** + * HttpRule post. + * @member {string|null|undefined} post + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.post = null; + + /** + * HttpRule delete. + * @member {string|null|undefined} delete + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype["delete"] = null; + + /** + * HttpRule patch. + * @member {string|null|undefined} patch + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.patch = null; + + /** + * HttpRule custom. + * @member {google.api.ICustomHttpPattern|null|undefined} custom + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.custom = null; + + /** + * HttpRule body. + * @member {string} body + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.body = ""; + + /** + * HttpRule responseBody. + * @member {string} responseBody + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.responseBody = ""; + + /** + * HttpRule additionalBindings. + * @member {Array.} additionalBindings + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.additionalBindings = $util.emptyArray; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * HttpRule pattern. + * @member {"get"|"put"|"post"|"delete"|"patch"|"custom"|undefined} pattern + * @memberof google.api.HttpRule + * @instance + */ + Object.defineProperty(HttpRule.prototype, "pattern", { + get: $util.oneOfGetter($oneOfFields = ["get", "put", "post", "delete", "patch", "custom"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.HttpRule + * @static + * @param {Object.} object Plain object + * @returns {google.api.HttpRule} HttpRule + */ + HttpRule.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.HttpRule) + return object; + var message = new $root.google.api.HttpRule(); + if (object.selector != null) + message.selector = String(object.selector); + if (object.get != null) + message.get = String(object.get); + if (object.put != null) + message.put = String(object.put); + if (object.post != null) + message.post = String(object.post); + if (object["delete"] != null) + message["delete"] = String(object["delete"]); + if (object.patch != null) + message.patch = String(object.patch); + if (object.custom != null) { + if (typeof object.custom !== "object") + throw TypeError(".google.api.HttpRule.custom: object expected"); + message.custom = $root.google.api.CustomHttpPattern.fromObject(object.custom); + } + if (object.body != null) + message.body = String(object.body); + if (object.responseBody != null) + message.responseBody = String(object.responseBody); + if (object.additionalBindings) { + if (!Array.isArray(object.additionalBindings)) + throw TypeError(".google.api.HttpRule.additionalBindings: array expected"); + message.additionalBindings = []; + for (var i = 0; i < object.additionalBindings.length; ++i) { + if (typeof object.additionalBindings[i] !== "object") + throw TypeError(".google.api.HttpRule.additionalBindings: object expected"); + message.additionalBindings[i] = $root.google.api.HttpRule.fromObject(object.additionalBindings[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.HttpRule + * @static + * @param {google.api.HttpRule} message HttpRule + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + HttpRule.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.additionalBindings = []; + if (options.defaults) { + object.selector = ""; + object.body = ""; + object.responseBody = ""; + } + if (message.selector != null && message.hasOwnProperty("selector")) + object.selector = message.selector; + if (message.get != null && message.hasOwnProperty("get")) { + object.get = message.get; + if (options.oneofs) + object.pattern = "get"; + } + if (message.put != null && message.hasOwnProperty("put")) { + object.put = message.put; + if (options.oneofs) + object.pattern = "put"; + } + if (message.post != null && message.hasOwnProperty("post")) { + object.post = message.post; + if (options.oneofs) + object.pattern = "post"; + } + if (message["delete"] != null && message.hasOwnProperty("delete")) { + object["delete"] = message["delete"]; + if (options.oneofs) + object.pattern = "delete"; + } + if (message.patch != null && message.hasOwnProperty("patch")) { + object.patch = message.patch; + if (options.oneofs) + object.pattern = "patch"; + } + if (message.body != null && message.hasOwnProperty("body")) + object.body = message.body; + if (message.custom != null && message.hasOwnProperty("custom")) { + object.custom = $root.google.api.CustomHttpPattern.toObject(message.custom, options); + if (options.oneofs) + object.pattern = "custom"; + } + if (message.additionalBindings && message.additionalBindings.length) { + object.additionalBindings = []; + for (var j = 0; j < message.additionalBindings.length; ++j) + object.additionalBindings[j] = $root.google.api.HttpRule.toObject(message.additionalBindings[j], options); + } + if (message.responseBody != null && message.hasOwnProperty("responseBody")) + object.responseBody = message.responseBody; + return object; + }; + + /** + * Converts this HttpRule to JSON. + * @function toJSON + * @memberof google.api.HttpRule + * @instance + * @returns {Object.} JSON object + */ + HttpRule.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for HttpRule + * @function getTypeUrl + * @memberof google.api.HttpRule + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + HttpRule.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.HttpRule"; + }; + + return HttpRule; + })(); + + api.CustomHttpPattern = (function() { + + /** + * Properties of a CustomHttpPattern. + * @memberof google.api + * @interface ICustomHttpPattern + * @property {string|null} [kind] CustomHttpPattern kind + * @property {string|null} [path] CustomHttpPattern path + */ + + /** + * Constructs a new CustomHttpPattern. + * @memberof google.api + * @classdesc Represents a CustomHttpPattern. + * @implements ICustomHttpPattern + * @constructor + * @param {google.api.ICustomHttpPattern=} [properties] Properties to set + */ + function CustomHttpPattern(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CustomHttpPattern kind. + * @member {string} kind + * @memberof google.api.CustomHttpPattern + * @instance + */ + CustomHttpPattern.prototype.kind = ""; + + /** + * CustomHttpPattern path. + * @member {string} path + * @memberof google.api.CustomHttpPattern + * @instance + */ + CustomHttpPattern.prototype.path = ""; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.CustomHttpPattern + * @static + * @param {Object.} object Plain object + * @returns {google.api.CustomHttpPattern} CustomHttpPattern + */ + CustomHttpPattern.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.CustomHttpPattern) + return object; + var message = new $root.google.api.CustomHttpPattern(); + if (object.kind != null) + message.kind = String(object.kind); + if (object.path != null) + message.path = String(object.path); + return message; + }; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.CustomHttpPattern + * @static + * @param {google.api.CustomHttpPattern} message CustomHttpPattern + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CustomHttpPattern.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.kind = ""; + object.path = ""; + } + if (message.kind != null && message.hasOwnProperty("kind")) + object.kind = message.kind; + if (message.path != null && message.hasOwnProperty("path")) + object.path = message.path; + return object; + }; + + /** + * Converts this CustomHttpPattern to JSON. + * @function toJSON + * @memberof google.api.CustomHttpPattern + * @instance + * @returns {Object.} JSON object + */ + CustomHttpPattern.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CustomHttpPattern + * @function getTypeUrl + * @memberof google.api.CustomHttpPattern + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CustomHttpPattern.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.CustomHttpPattern"; + }; + + return CustomHttpPattern; + })(); + + api.CommonLanguageSettings = (function() { + + /** + * Properties of a CommonLanguageSettings. + * @memberof google.api + * @interface ICommonLanguageSettings + * @property {string|null} [referenceDocsUri] CommonLanguageSettings referenceDocsUri + * @property {Array.|null} [destinations] CommonLanguageSettings destinations + * @property {google.api.ISelectiveGapicGeneration|null} [selectiveGapicGeneration] CommonLanguageSettings selectiveGapicGeneration + */ + + /** + * Constructs a new CommonLanguageSettings. + * @memberof google.api + * @classdesc Represents a CommonLanguageSettings. + * @implements ICommonLanguageSettings + * @constructor + * @param {google.api.ICommonLanguageSettings=} [properties] Properties to set + */ + function CommonLanguageSettings(properties) { + this.destinations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CommonLanguageSettings referenceDocsUri. + * @member {string} referenceDocsUri + * @memberof google.api.CommonLanguageSettings + * @instance + */ + CommonLanguageSettings.prototype.referenceDocsUri = ""; + + /** + * CommonLanguageSettings destinations. + * @member {Array.} destinations + * @memberof google.api.CommonLanguageSettings + * @instance + */ + CommonLanguageSettings.prototype.destinations = $util.emptyArray; + + /** + * CommonLanguageSettings selectiveGapicGeneration. + * @member {google.api.ISelectiveGapicGeneration|null|undefined} selectiveGapicGeneration + * @memberof google.api.CommonLanguageSettings + * @instance + */ + CommonLanguageSettings.prototype.selectiveGapicGeneration = null; + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.CommonLanguageSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.CommonLanguageSettings} CommonLanguageSettings + */ + CommonLanguageSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.CommonLanguageSettings) + return object; + var message = new $root.google.api.CommonLanguageSettings(); + if (object.referenceDocsUri != null) + message.referenceDocsUri = String(object.referenceDocsUri); + if (object.destinations) { + if (!Array.isArray(object.destinations)) + throw TypeError(".google.api.CommonLanguageSettings.destinations: array expected"); + message.destinations = []; + for (var i = 0; i < object.destinations.length; ++i) + switch (object.destinations[i]) { + default: + if (typeof object.destinations[i] === "number") { + message.destinations[i] = object.destinations[i]; + break; + } + case "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED": + case 0: + message.destinations[i] = 0; + break; + case "GITHUB": + case 10: + message.destinations[i] = 10; + break; + case "PACKAGE_MANAGER": + case 20: + message.destinations[i] = 20; + break; + } + } + if (object.selectiveGapicGeneration != null) { + if (typeof object.selectiveGapicGeneration !== "object") + throw TypeError(".google.api.CommonLanguageSettings.selectiveGapicGeneration: object expected"); + message.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.fromObject(object.selectiveGapicGeneration); + } + return message; + }; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.CommonLanguageSettings + * @static + * @param {google.api.CommonLanguageSettings} message CommonLanguageSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CommonLanguageSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.destinations = []; + if (options.defaults) { + object.referenceDocsUri = ""; + object.selectiveGapicGeneration = null; + } + if (message.referenceDocsUri != null && message.hasOwnProperty("referenceDocsUri")) + object.referenceDocsUri = message.referenceDocsUri; + if (message.destinations && message.destinations.length) { + object.destinations = []; + for (var j = 0; j < message.destinations.length; ++j) + object.destinations[j] = options.enums === String ? $root.google.api.ClientLibraryDestination[message.destinations[j]] === undefined ? message.destinations[j] : $root.google.api.ClientLibraryDestination[message.destinations[j]] : message.destinations[j]; + } + if (message.selectiveGapicGeneration != null && message.hasOwnProperty("selectiveGapicGeneration")) + object.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.toObject(message.selectiveGapicGeneration, options); + return object; + }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @function toJSON + * @memberof google.api.CommonLanguageSettings + * @instance + * @returns {Object.} JSON object + */ + CommonLanguageSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CommonLanguageSettings + * @function getTypeUrl + * @memberof google.api.CommonLanguageSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CommonLanguageSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.CommonLanguageSettings"; + }; + + return CommonLanguageSettings; + })(); + + api.ClientLibrarySettings = (function() { + + /** + * Properties of a ClientLibrarySettings. + * @memberof google.api + * @interface IClientLibrarySettings + * @property {string|null} [version] ClientLibrarySettings version + * @property {google.api.LaunchStage|null} [launchStage] ClientLibrarySettings launchStage + * @property {boolean|null} [restNumericEnums] ClientLibrarySettings restNumericEnums + * @property {google.api.IJavaSettings|null} [javaSettings] ClientLibrarySettings javaSettings + * @property {google.api.ICppSettings|null} [cppSettings] ClientLibrarySettings cppSettings + * @property {google.api.IPhpSettings|null} [phpSettings] ClientLibrarySettings phpSettings + * @property {google.api.IPythonSettings|null} [pythonSettings] ClientLibrarySettings pythonSettings + * @property {google.api.INodeSettings|null} [nodeSettings] ClientLibrarySettings nodeSettings + * @property {google.api.IDotnetSettings|null} [dotnetSettings] ClientLibrarySettings dotnetSettings + * @property {google.api.IRubySettings|null} [rubySettings] ClientLibrarySettings rubySettings + * @property {google.api.IGoSettings|null} [goSettings] ClientLibrarySettings goSettings + */ + + /** + * Constructs a new ClientLibrarySettings. + * @memberof google.api + * @classdesc Represents a ClientLibrarySettings. + * @implements IClientLibrarySettings + * @constructor + * @param {google.api.IClientLibrarySettings=} [properties] Properties to set + */ + function ClientLibrarySettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ClientLibrarySettings version. + * @member {string} version + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.version = ""; + + /** + * ClientLibrarySettings launchStage. + * @member {google.api.LaunchStage} launchStage + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.launchStage = 0; + + /** + * ClientLibrarySettings restNumericEnums. + * @member {boolean} restNumericEnums + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.restNumericEnums = false; + + /** + * ClientLibrarySettings javaSettings. + * @member {google.api.IJavaSettings|null|undefined} javaSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.javaSettings = null; + + /** + * ClientLibrarySettings cppSettings. + * @member {google.api.ICppSettings|null|undefined} cppSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.cppSettings = null; + + /** + * ClientLibrarySettings phpSettings. + * @member {google.api.IPhpSettings|null|undefined} phpSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.phpSettings = null; + + /** + * ClientLibrarySettings pythonSettings. + * @member {google.api.IPythonSettings|null|undefined} pythonSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.pythonSettings = null; + + /** + * ClientLibrarySettings nodeSettings. + * @member {google.api.INodeSettings|null|undefined} nodeSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.nodeSettings = null; + + /** + * ClientLibrarySettings dotnetSettings. + * @member {google.api.IDotnetSettings|null|undefined} dotnetSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.dotnetSettings = null; + + /** + * ClientLibrarySettings rubySettings. + * @member {google.api.IRubySettings|null|undefined} rubySettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.rubySettings = null; + + /** + * ClientLibrarySettings goSettings. + * @member {google.api.IGoSettings|null|undefined} goSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.goSettings = null; + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ClientLibrarySettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.ClientLibrarySettings} ClientLibrarySettings + */ + ClientLibrarySettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ClientLibrarySettings) + return object; + var message = new $root.google.api.ClientLibrarySettings(); + if (object.version != null) + message.version = String(object.version); + switch (object.launchStage) { + default: + if (typeof object.launchStage === "number") { + message.launchStage = object.launchStage; + break; + } + break; + case "LAUNCH_STAGE_UNSPECIFIED": + case 0: + message.launchStage = 0; + break; + case "UNIMPLEMENTED": + case 6: + message.launchStage = 6; + break; + case "PRELAUNCH": + case 7: + message.launchStage = 7; + break; + case "EARLY_ACCESS": + case 1: + message.launchStage = 1; + break; + case "ALPHA": + case 2: + message.launchStage = 2; + break; + case "BETA": + case 3: + message.launchStage = 3; + break; + case "GA": + case 4: + message.launchStage = 4; + break; + case "DEPRECATED": + case 5: + message.launchStage = 5; + break; + } + if (object.restNumericEnums != null) + message.restNumericEnums = Boolean(object.restNumericEnums); + if (object.javaSettings != null) { + if (typeof object.javaSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.javaSettings: object expected"); + message.javaSettings = $root.google.api.JavaSettings.fromObject(object.javaSettings); + } + if (object.cppSettings != null) { + if (typeof object.cppSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.cppSettings: object expected"); + message.cppSettings = $root.google.api.CppSettings.fromObject(object.cppSettings); + } + if (object.phpSettings != null) { + if (typeof object.phpSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.phpSettings: object expected"); + message.phpSettings = $root.google.api.PhpSettings.fromObject(object.phpSettings); + } + if (object.pythonSettings != null) { + if (typeof object.pythonSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.pythonSettings: object expected"); + message.pythonSettings = $root.google.api.PythonSettings.fromObject(object.pythonSettings); + } + if (object.nodeSettings != null) { + if (typeof object.nodeSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.nodeSettings: object expected"); + message.nodeSettings = $root.google.api.NodeSettings.fromObject(object.nodeSettings); + } + if (object.dotnetSettings != null) { + if (typeof object.dotnetSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.dotnetSettings: object expected"); + message.dotnetSettings = $root.google.api.DotnetSettings.fromObject(object.dotnetSettings); + } + if (object.rubySettings != null) { + if (typeof object.rubySettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.rubySettings: object expected"); + message.rubySettings = $root.google.api.RubySettings.fromObject(object.rubySettings); + } + if (object.goSettings != null) { + if (typeof object.goSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.goSettings: object expected"); + message.goSettings = $root.google.api.GoSettings.fromObject(object.goSettings); + } + return message; + }; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ClientLibrarySettings + * @static + * @param {google.api.ClientLibrarySettings} message ClientLibrarySettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ClientLibrarySettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.version = ""; + object.launchStage = options.enums === String ? "LAUNCH_STAGE_UNSPECIFIED" : 0; + object.restNumericEnums = false; + object.javaSettings = null; + object.cppSettings = null; + object.phpSettings = null; + object.pythonSettings = null; + object.nodeSettings = null; + object.dotnetSettings = null; + object.rubySettings = null; + object.goSettings = null; + } + if (message.version != null && message.hasOwnProperty("version")) + object.version = message.version; + if (message.launchStage != null && message.hasOwnProperty("launchStage")) + object.launchStage = options.enums === String ? $root.google.api.LaunchStage[message.launchStage] === undefined ? message.launchStage : $root.google.api.LaunchStage[message.launchStage] : message.launchStage; + if (message.restNumericEnums != null && message.hasOwnProperty("restNumericEnums")) + object.restNumericEnums = message.restNumericEnums; + if (message.javaSettings != null && message.hasOwnProperty("javaSettings")) + object.javaSettings = $root.google.api.JavaSettings.toObject(message.javaSettings, options); + if (message.cppSettings != null && message.hasOwnProperty("cppSettings")) + object.cppSettings = $root.google.api.CppSettings.toObject(message.cppSettings, options); + if (message.phpSettings != null && message.hasOwnProperty("phpSettings")) + object.phpSettings = $root.google.api.PhpSettings.toObject(message.phpSettings, options); + if (message.pythonSettings != null && message.hasOwnProperty("pythonSettings")) + object.pythonSettings = $root.google.api.PythonSettings.toObject(message.pythonSettings, options); + if (message.nodeSettings != null && message.hasOwnProperty("nodeSettings")) + object.nodeSettings = $root.google.api.NodeSettings.toObject(message.nodeSettings, options); + if (message.dotnetSettings != null && message.hasOwnProperty("dotnetSettings")) + object.dotnetSettings = $root.google.api.DotnetSettings.toObject(message.dotnetSettings, options); + if (message.rubySettings != null && message.hasOwnProperty("rubySettings")) + object.rubySettings = $root.google.api.RubySettings.toObject(message.rubySettings, options); + if (message.goSettings != null && message.hasOwnProperty("goSettings")) + object.goSettings = $root.google.api.GoSettings.toObject(message.goSettings, options); + return object; + }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @function toJSON + * @memberof google.api.ClientLibrarySettings + * @instance + * @returns {Object.} JSON object + */ + ClientLibrarySettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ClientLibrarySettings + * @function getTypeUrl + * @memberof google.api.ClientLibrarySettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ClientLibrarySettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ClientLibrarySettings"; + }; + + return ClientLibrarySettings; + })(); + + api.Publishing = (function() { + + /** + * Properties of a Publishing. + * @memberof google.api + * @interface IPublishing + * @property {Array.|null} [methodSettings] Publishing methodSettings + * @property {string|null} [newIssueUri] Publishing newIssueUri + * @property {string|null} [documentationUri] Publishing documentationUri + * @property {string|null} [apiShortName] Publishing apiShortName + * @property {string|null} [githubLabel] Publishing githubLabel + * @property {Array.|null} [codeownerGithubTeams] Publishing codeownerGithubTeams + * @property {string|null} [docTagPrefix] Publishing docTagPrefix + * @property {google.api.ClientLibraryOrganization|null} [organization] Publishing organization + * @property {Array.|null} [librarySettings] Publishing librarySettings + * @property {string|null} [protoReferenceDocumentationUri] Publishing protoReferenceDocumentationUri + * @property {string|null} [restReferenceDocumentationUri] Publishing restReferenceDocumentationUri + */ + + /** + * Constructs a new Publishing. + * @memberof google.api + * @classdesc Represents a Publishing. + * @implements IPublishing + * @constructor + * @param {google.api.IPublishing=} [properties] Properties to set + */ + function Publishing(properties) { + this.methodSettings = []; + this.codeownerGithubTeams = []; + this.librarySettings = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Publishing methodSettings. + * @member {Array.} methodSettings + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.methodSettings = $util.emptyArray; + + /** + * Publishing newIssueUri. + * @member {string} newIssueUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.newIssueUri = ""; + + /** + * Publishing documentationUri. + * @member {string} documentationUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.documentationUri = ""; + + /** + * Publishing apiShortName. + * @member {string} apiShortName + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.apiShortName = ""; + + /** + * Publishing githubLabel. + * @member {string} githubLabel + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.githubLabel = ""; + + /** + * Publishing codeownerGithubTeams. + * @member {Array.} codeownerGithubTeams + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.codeownerGithubTeams = $util.emptyArray; + + /** + * Publishing docTagPrefix. + * @member {string} docTagPrefix + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.docTagPrefix = ""; + + /** + * Publishing organization. + * @member {google.api.ClientLibraryOrganization} organization + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.organization = 0; + + /** + * Publishing librarySettings. + * @member {Array.} librarySettings + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.librarySettings = $util.emptyArray; + + /** + * Publishing protoReferenceDocumentationUri. + * @member {string} protoReferenceDocumentationUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.protoReferenceDocumentationUri = ""; + + /** + * Publishing restReferenceDocumentationUri. + * @member {string} restReferenceDocumentationUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.restReferenceDocumentationUri = ""; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.Publishing + * @static + * @param {Object.} object Plain object + * @returns {google.api.Publishing} Publishing + */ + Publishing.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.Publishing) + return object; + var message = new $root.google.api.Publishing(); + if (object.methodSettings) { + if (!Array.isArray(object.methodSettings)) + throw TypeError(".google.api.Publishing.methodSettings: array expected"); + message.methodSettings = []; + for (var i = 0; i < object.methodSettings.length; ++i) { + if (typeof object.methodSettings[i] !== "object") + throw TypeError(".google.api.Publishing.methodSettings: object expected"); + message.methodSettings[i] = $root.google.api.MethodSettings.fromObject(object.methodSettings[i]); + } + } + if (object.newIssueUri != null) + message.newIssueUri = String(object.newIssueUri); + if (object.documentationUri != null) + message.documentationUri = String(object.documentationUri); + if (object.apiShortName != null) + message.apiShortName = String(object.apiShortName); + if (object.githubLabel != null) + message.githubLabel = String(object.githubLabel); + if (object.codeownerGithubTeams) { + if (!Array.isArray(object.codeownerGithubTeams)) + throw TypeError(".google.api.Publishing.codeownerGithubTeams: array expected"); + message.codeownerGithubTeams = []; + for (var i = 0; i < object.codeownerGithubTeams.length; ++i) + message.codeownerGithubTeams[i] = String(object.codeownerGithubTeams[i]); + } + if (object.docTagPrefix != null) + message.docTagPrefix = String(object.docTagPrefix); + switch (object.organization) { + default: + if (typeof object.organization === "number") { + message.organization = object.organization; + break; + } + break; + case "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED": + case 0: + message.organization = 0; + break; + case "CLOUD": + case 1: + message.organization = 1; + break; + case "ADS": + case 2: + message.organization = 2; + break; + case "PHOTOS": + case 3: + message.organization = 3; + break; + case "STREET_VIEW": + case 4: + message.organization = 4; + break; + case "SHOPPING": + case 5: + message.organization = 5; + break; + case "GEO": + case 6: + message.organization = 6; + break; + case "GENERATIVE_AI": + case 7: + message.organization = 7; + break; + } + if (object.librarySettings) { + if (!Array.isArray(object.librarySettings)) + throw TypeError(".google.api.Publishing.librarySettings: array expected"); + message.librarySettings = []; + for (var i = 0; i < object.librarySettings.length; ++i) { + if (typeof object.librarySettings[i] !== "object") + throw TypeError(".google.api.Publishing.librarySettings: object expected"); + message.librarySettings[i] = $root.google.api.ClientLibrarySettings.fromObject(object.librarySettings[i]); + } + } + if (object.protoReferenceDocumentationUri != null) + message.protoReferenceDocumentationUri = String(object.protoReferenceDocumentationUri); + if (object.restReferenceDocumentationUri != null) + message.restReferenceDocumentationUri = String(object.restReferenceDocumentationUri); + return message; + }; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.Publishing + * @static + * @param {google.api.Publishing} message Publishing + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Publishing.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.methodSettings = []; + object.codeownerGithubTeams = []; + object.librarySettings = []; + } + if (options.defaults) { + object.newIssueUri = ""; + object.documentationUri = ""; + object.apiShortName = ""; + object.githubLabel = ""; + object.docTagPrefix = ""; + object.organization = options.enums === String ? "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED" : 0; + object.protoReferenceDocumentationUri = ""; + object.restReferenceDocumentationUri = ""; + } + if (message.methodSettings && message.methodSettings.length) { + object.methodSettings = []; + for (var j = 0; j < message.methodSettings.length; ++j) + object.methodSettings[j] = $root.google.api.MethodSettings.toObject(message.methodSettings[j], options); + } + if (message.newIssueUri != null && message.hasOwnProperty("newIssueUri")) + object.newIssueUri = message.newIssueUri; + if (message.documentationUri != null && message.hasOwnProperty("documentationUri")) + object.documentationUri = message.documentationUri; + if (message.apiShortName != null && message.hasOwnProperty("apiShortName")) + object.apiShortName = message.apiShortName; + if (message.githubLabel != null && message.hasOwnProperty("githubLabel")) + object.githubLabel = message.githubLabel; + if (message.codeownerGithubTeams && message.codeownerGithubTeams.length) { + object.codeownerGithubTeams = []; + for (var j = 0; j < message.codeownerGithubTeams.length; ++j) + object.codeownerGithubTeams[j] = message.codeownerGithubTeams[j]; + } + if (message.docTagPrefix != null && message.hasOwnProperty("docTagPrefix")) + object.docTagPrefix = message.docTagPrefix; + if (message.organization != null && message.hasOwnProperty("organization")) + object.organization = options.enums === String ? $root.google.api.ClientLibraryOrganization[message.organization] === undefined ? message.organization : $root.google.api.ClientLibraryOrganization[message.organization] : message.organization; + if (message.librarySettings && message.librarySettings.length) { + object.librarySettings = []; + for (var j = 0; j < message.librarySettings.length; ++j) + object.librarySettings[j] = $root.google.api.ClientLibrarySettings.toObject(message.librarySettings[j], options); + } + if (message.protoReferenceDocumentationUri != null && message.hasOwnProperty("protoReferenceDocumentationUri")) + object.protoReferenceDocumentationUri = message.protoReferenceDocumentationUri; + if (message.restReferenceDocumentationUri != null && message.hasOwnProperty("restReferenceDocumentationUri")) + object.restReferenceDocumentationUri = message.restReferenceDocumentationUri; + return object; + }; + + /** + * Converts this Publishing to JSON. + * @function toJSON + * @memberof google.api.Publishing + * @instance + * @returns {Object.} JSON object + */ + Publishing.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Publishing + * @function getTypeUrl + * @memberof google.api.Publishing + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Publishing.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.Publishing"; + }; + + return Publishing; + })(); + + api.JavaSettings = (function() { + + /** + * Properties of a JavaSettings. + * @memberof google.api + * @interface IJavaSettings + * @property {string|null} [libraryPackage] JavaSettings libraryPackage + * @property {Object.|null} [serviceClassNames] JavaSettings serviceClassNames + * @property {google.api.ICommonLanguageSettings|null} [common] JavaSettings common + */ + + /** + * Constructs a new JavaSettings. + * @memberof google.api + * @classdesc Represents a JavaSettings. + * @implements IJavaSettings + * @constructor + * @param {google.api.IJavaSettings=} [properties] Properties to set + */ + function JavaSettings(properties) { + this.serviceClassNames = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * JavaSettings libraryPackage. + * @member {string} libraryPackage + * @memberof google.api.JavaSettings + * @instance + */ + JavaSettings.prototype.libraryPackage = ""; + + /** + * JavaSettings serviceClassNames. + * @member {Object.} serviceClassNames + * @memberof google.api.JavaSettings + * @instance + */ + JavaSettings.prototype.serviceClassNames = $util.emptyObject; + + /** + * JavaSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.JavaSettings + * @instance + */ + JavaSettings.prototype.common = null; + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.JavaSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.JavaSettings} JavaSettings + */ + JavaSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.JavaSettings) + return object; + var message = new $root.google.api.JavaSettings(); + if (object.libraryPackage != null) + message.libraryPackage = String(object.libraryPackage); + if (object.serviceClassNames) { + if (typeof object.serviceClassNames !== "object") + throw TypeError(".google.api.JavaSettings.serviceClassNames: object expected"); + message.serviceClassNames = {}; + for (var keys = Object.keys(object.serviceClassNames), i = 0; i < keys.length; ++i) + message.serviceClassNames[keys[i]] = String(object.serviceClassNames[keys[i]]); + } + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.JavaSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.JavaSettings + * @static + * @param {google.api.JavaSettings} message JavaSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + JavaSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.serviceClassNames = {}; + if (options.defaults) { + object.libraryPackage = ""; + object.common = null; + } + if (message.libraryPackage != null && message.hasOwnProperty("libraryPackage")) + object.libraryPackage = message.libraryPackage; + var keys2; + if (message.serviceClassNames && (keys2 = Object.keys(message.serviceClassNames)).length) { + object.serviceClassNames = {}; + for (var j = 0; j < keys2.length; ++j) + object.serviceClassNames[keys2[j]] = message.serviceClassNames[keys2[j]]; + } + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this JavaSettings to JSON. + * @function toJSON + * @memberof google.api.JavaSettings + * @instance + * @returns {Object.} JSON object + */ + JavaSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for JavaSettings + * @function getTypeUrl + * @memberof google.api.JavaSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + JavaSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.JavaSettings"; + }; + + return JavaSettings; + })(); + + api.CppSettings = (function() { + + /** + * Properties of a CppSettings. + * @memberof google.api + * @interface ICppSettings + * @property {google.api.ICommonLanguageSettings|null} [common] CppSettings common + */ + + /** + * Constructs a new CppSettings. + * @memberof google.api + * @classdesc Represents a CppSettings. + * @implements ICppSettings + * @constructor + * @param {google.api.ICppSettings=} [properties] Properties to set + */ + function CppSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CppSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.CppSettings + * @instance + */ + CppSettings.prototype.common = null; + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.CppSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.CppSettings} CppSettings + */ + CppSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.CppSettings) + return object; + var message = new $root.google.api.CppSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.CppSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.CppSettings + * @static + * @param {google.api.CppSettings} message CppSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CppSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this CppSettings to JSON. + * @function toJSON + * @memberof google.api.CppSettings + * @instance + * @returns {Object.} JSON object + */ + CppSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CppSettings + * @function getTypeUrl + * @memberof google.api.CppSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CppSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.CppSettings"; + }; + + return CppSettings; + })(); + + api.PhpSettings = (function() { + + /** + * Properties of a PhpSettings. + * @memberof google.api + * @interface IPhpSettings + * @property {google.api.ICommonLanguageSettings|null} [common] PhpSettings common + */ + + /** + * Constructs a new PhpSettings. + * @memberof google.api + * @classdesc Represents a PhpSettings. + * @implements IPhpSettings + * @constructor + * @param {google.api.IPhpSettings=} [properties] Properties to set + */ + function PhpSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PhpSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.PhpSettings + * @instance + */ + PhpSettings.prototype.common = null; + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.PhpSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.PhpSettings} PhpSettings + */ + PhpSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.PhpSettings) + return object; + var message = new $root.google.api.PhpSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.PhpSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.PhpSettings + * @static + * @param {google.api.PhpSettings} message PhpSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PhpSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this PhpSettings to JSON. + * @function toJSON + * @memberof google.api.PhpSettings + * @instance + * @returns {Object.} JSON object + */ + PhpSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PhpSettings + * @function getTypeUrl + * @memberof google.api.PhpSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PhpSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.PhpSettings"; + }; + + return PhpSettings; + })(); + + api.PythonSettings = (function() { + + /** + * Properties of a PythonSettings. + * @memberof google.api + * @interface IPythonSettings + * @property {google.api.ICommonLanguageSettings|null} [common] PythonSettings common + * @property {google.api.PythonSettings.IExperimentalFeatures|null} [experimentalFeatures] PythonSettings experimentalFeatures + */ + + /** + * Constructs a new PythonSettings. + * @memberof google.api + * @classdesc Represents a PythonSettings. + * @implements IPythonSettings + * @constructor + * @param {google.api.IPythonSettings=} [properties] Properties to set + */ + function PythonSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PythonSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.PythonSettings + * @instance + */ + PythonSettings.prototype.common = null; + + /** + * PythonSettings experimentalFeatures. + * @member {google.api.PythonSettings.IExperimentalFeatures|null|undefined} experimentalFeatures + * @memberof google.api.PythonSettings + * @instance + */ + PythonSettings.prototype.experimentalFeatures = null; + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.PythonSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.PythonSettings} PythonSettings + */ + PythonSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.PythonSettings) + return object; + var message = new $root.google.api.PythonSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.PythonSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + if (object.experimentalFeatures != null) { + if (typeof object.experimentalFeatures !== "object") + throw TypeError(".google.api.PythonSettings.experimentalFeatures: object expected"); + message.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.fromObject(object.experimentalFeatures); + } + return message; + }; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.PythonSettings + * @static + * @param {google.api.PythonSettings} message PythonSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PythonSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.common = null; + object.experimentalFeatures = null; + } + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + if (message.experimentalFeatures != null && message.hasOwnProperty("experimentalFeatures")) + object.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.toObject(message.experimentalFeatures, options); + return object; + }; + + /** + * Converts this PythonSettings to JSON. + * @function toJSON + * @memberof google.api.PythonSettings + * @instance + * @returns {Object.} JSON object + */ + PythonSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PythonSettings + * @function getTypeUrl + * @memberof google.api.PythonSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PythonSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.PythonSettings"; + }; + + PythonSettings.ExperimentalFeatures = (function() { + + /** + * Properties of an ExperimentalFeatures. + * @memberof google.api.PythonSettings + * @interface IExperimentalFeatures + * @property {boolean|null} [restAsyncIoEnabled] ExperimentalFeatures restAsyncIoEnabled + * @property {boolean|null} [protobufPythonicTypesEnabled] ExperimentalFeatures protobufPythonicTypesEnabled + * @property {boolean|null} [unversionedPackageDisabled] ExperimentalFeatures unversionedPackageDisabled + */ + + /** + * Constructs a new ExperimentalFeatures. + * @memberof google.api.PythonSettings + * @classdesc Represents an ExperimentalFeatures. + * @implements IExperimentalFeatures + * @constructor + * @param {google.api.PythonSettings.IExperimentalFeatures=} [properties] Properties to set + */ + function ExperimentalFeatures(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExperimentalFeatures restAsyncIoEnabled. + * @member {boolean} restAsyncIoEnabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.restAsyncIoEnabled = false; + + /** + * ExperimentalFeatures protobufPythonicTypesEnabled. + * @member {boolean} protobufPythonicTypesEnabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.protobufPythonicTypesEnabled = false; + + /** + * ExperimentalFeatures unversionedPackageDisabled. + * @member {boolean} unversionedPackageDisabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.unversionedPackageDisabled = false; + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {Object.} object Plain object + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + */ + ExperimentalFeatures.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.PythonSettings.ExperimentalFeatures) + return object; + var message = new $root.google.api.PythonSettings.ExperimentalFeatures(); + if (object.restAsyncIoEnabled != null) + message.restAsyncIoEnabled = Boolean(object.restAsyncIoEnabled); + if (object.protobufPythonicTypesEnabled != null) + message.protobufPythonicTypesEnabled = Boolean(object.protobufPythonicTypesEnabled); + if (object.unversionedPackageDisabled != null) + message.unversionedPackageDisabled = Boolean(object.unversionedPackageDisabled); + return message; + }; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.ExperimentalFeatures} message ExperimentalFeatures + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExperimentalFeatures.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.restAsyncIoEnabled = false; + object.protobufPythonicTypesEnabled = false; + object.unversionedPackageDisabled = false; + } + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + object.restAsyncIoEnabled = message.restAsyncIoEnabled; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + object.protobufPythonicTypesEnabled = message.protobufPythonicTypesEnabled; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + object.unversionedPackageDisabled = message.unversionedPackageDisabled; + return object; + }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @function toJSON + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + * @returns {Object.} JSON object + */ + ExperimentalFeatures.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExperimentalFeatures + * @function getTypeUrl + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExperimentalFeatures.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.PythonSettings.ExperimentalFeatures"; + }; + + return ExperimentalFeatures; + })(); + + return PythonSettings; + })(); + + api.NodeSettings = (function() { + + /** + * Properties of a NodeSettings. + * @memberof google.api + * @interface INodeSettings + * @property {google.api.ICommonLanguageSettings|null} [common] NodeSettings common + */ + + /** + * Constructs a new NodeSettings. + * @memberof google.api + * @classdesc Represents a NodeSettings. + * @implements INodeSettings + * @constructor + * @param {google.api.INodeSettings=} [properties] Properties to set + */ + function NodeSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * NodeSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.NodeSettings + * @instance + */ + NodeSettings.prototype.common = null; + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.NodeSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.NodeSettings} NodeSettings + */ + NodeSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.NodeSettings) + return object; + var message = new $root.google.api.NodeSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.NodeSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.NodeSettings + * @static + * @param {google.api.NodeSettings} message NodeSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + NodeSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this NodeSettings to JSON. + * @function toJSON + * @memberof google.api.NodeSettings + * @instance + * @returns {Object.} JSON object + */ + NodeSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for NodeSettings + * @function getTypeUrl + * @memberof google.api.NodeSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + NodeSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.NodeSettings"; + }; + + return NodeSettings; + })(); + + api.DotnetSettings = (function() { + + /** + * Properties of a DotnetSettings. + * @memberof google.api + * @interface IDotnetSettings + * @property {google.api.ICommonLanguageSettings|null} [common] DotnetSettings common + * @property {Object.|null} [renamedServices] DotnetSettings renamedServices + * @property {Object.|null} [renamedResources] DotnetSettings renamedResources + * @property {Array.|null} [ignoredResources] DotnetSettings ignoredResources + * @property {Array.|null} [forcedNamespaceAliases] DotnetSettings forcedNamespaceAliases + * @property {Array.|null} [handwrittenSignatures] DotnetSettings handwrittenSignatures + */ + + /** + * Constructs a new DotnetSettings. + * @memberof google.api + * @classdesc Represents a DotnetSettings. + * @implements IDotnetSettings + * @constructor + * @param {google.api.IDotnetSettings=} [properties] Properties to set + */ + function DotnetSettings(properties) { + this.renamedServices = {}; + this.renamedResources = {}; + this.ignoredResources = []; + this.forcedNamespaceAliases = []; + this.handwrittenSignatures = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DotnetSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.common = null; + + /** + * DotnetSettings renamedServices. + * @member {Object.} renamedServices + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.renamedServices = $util.emptyObject; + + /** + * DotnetSettings renamedResources. + * @member {Object.} renamedResources + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.renamedResources = $util.emptyObject; + + /** + * DotnetSettings ignoredResources. + * @member {Array.} ignoredResources + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.ignoredResources = $util.emptyArray; + + /** + * DotnetSettings forcedNamespaceAliases. + * @member {Array.} forcedNamespaceAliases + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.forcedNamespaceAliases = $util.emptyArray; + + /** + * DotnetSettings handwrittenSignatures. + * @member {Array.} handwrittenSignatures + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.handwrittenSignatures = $util.emptyArray; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.DotnetSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.DotnetSettings} DotnetSettings + */ + DotnetSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.DotnetSettings) + return object; + var message = new $root.google.api.DotnetSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.DotnetSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + if (object.renamedServices) { + if (typeof object.renamedServices !== "object") + throw TypeError(".google.api.DotnetSettings.renamedServices: object expected"); + message.renamedServices = {}; + for (var keys = Object.keys(object.renamedServices), i = 0; i < keys.length; ++i) + message.renamedServices[keys[i]] = String(object.renamedServices[keys[i]]); + } + if (object.renamedResources) { + if (typeof object.renamedResources !== "object") + throw TypeError(".google.api.DotnetSettings.renamedResources: object expected"); + message.renamedResources = {}; + for (var keys = Object.keys(object.renamedResources), i = 0; i < keys.length; ++i) + message.renamedResources[keys[i]] = String(object.renamedResources[keys[i]]); + } + if (object.ignoredResources) { + if (!Array.isArray(object.ignoredResources)) + throw TypeError(".google.api.DotnetSettings.ignoredResources: array expected"); + message.ignoredResources = []; + for (var i = 0; i < object.ignoredResources.length; ++i) + message.ignoredResources[i] = String(object.ignoredResources[i]); + } + if (object.forcedNamespaceAliases) { + if (!Array.isArray(object.forcedNamespaceAliases)) + throw TypeError(".google.api.DotnetSettings.forcedNamespaceAliases: array expected"); + message.forcedNamespaceAliases = []; + for (var i = 0; i < object.forcedNamespaceAliases.length; ++i) + message.forcedNamespaceAliases[i] = String(object.forcedNamespaceAliases[i]); + } + if (object.handwrittenSignatures) { + if (!Array.isArray(object.handwrittenSignatures)) + throw TypeError(".google.api.DotnetSettings.handwrittenSignatures: array expected"); + message.handwrittenSignatures = []; + for (var i = 0; i < object.handwrittenSignatures.length; ++i) + message.handwrittenSignatures[i] = String(object.handwrittenSignatures[i]); + } + return message; + }; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.DotnetSettings + * @static + * @param {google.api.DotnetSettings} message DotnetSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DotnetSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.ignoredResources = []; + object.forcedNamespaceAliases = []; + object.handwrittenSignatures = []; + } + if (options.objects || options.defaults) { + object.renamedServices = {}; + object.renamedResources = {}; + } + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + var keys2; + if (message.renamedServices && (keys2 = Object.keys(message.renamedServices)).length) { + object.renamedServices = {}; + for (var j = 0; j < keys2.length; ++j) + object.renamedServices[keys2[j]] = message.renamedServices[keys2[j]]; + } + if (message.renamedResources && (keys2 = Object.keys(message.renamedResources)).length) { + object.renamedResources = {}; + for (var j = 0; j < keys2.length; ++j) + object.renamedResources[keys2[j]] = message.renamedResources[keys2[j]]; + } + if (message.ignoredResources && message.ignoredResources.length) { + object.ignoredResources = []; + for (var j = 0; j < message.ignoredResources.length; ++j) + object.ignoredResources[j] = message.ignoredResources[j]; + } + if (message.forcedNamespaceAliases && message.forcedNamespaceAliases.length) { + object.forcedNamespaceAliases = []; + for (var j = 0; j < message.forcedNamespaceAliases.length; ++j) + object.forcedNamespaceAliases[j] = message.forcedNamespaceAliases[j]; + } + if (message.handwrittenSignatures && message.handwrittenSignatures.length) { + object.handwrittenSignatures = []; + for (var j = 0; j < message.handwrittenSignatures.length; ++j) + object.handwrittenSignatures[j] = message.handwrittenSignatures[j]; + } + return object; + }; + + /** + * Converts this DotnetSettings to JSON. + * @function toJSON + * @memberof google.api.DotnetSettings + * @instance + * @returns {Object.} JSON object + */ + DotnetSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DotnetSettings + * @function getTypeUrl + * @memberof google.api.DotnetSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DotnetSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.DotnetSettings"; + }; + + return DotnetSettings; + })(); + + api.RubySettings = (function() { + + /** + * Properties of a RubySettings. + * @memberof google.api + * @interface IRubySettings + * @property {google.api.ICommonLanguageSettings|null} [common] RubySettings common + */ + + /** + * Constructs a new RubySettings. + * @memberof google.api + * @classdesc Represents a RubySettings. + * @implements IRubySettings + * @constructor + * @param {google.api.IRubySettings=} [properties] Properties to set + */ + function RubySettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RubySettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.RubySettings + * @instance + */ + RubySettings.prototype.common = null; + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.RubySettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.RubySettings} RubySettings + */ + RubySettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RubySettings) + return object; + var message = new $root.google.api.RubySettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.RubySettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.RubySettings + * @static + * @param {google.api.RubySettings} message RubySettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RubySettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this RubySettings to JSON. + * @function toJSON + * @memberof google.api.RubySettings + * @instance + * @returns {Object.} JSON object + */ + RubySettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RubySettings + * @function getTypeUrl + * @memberof google.api.RubySettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RubySettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.RubySettings"; + }; + + return RubySettings; + })(); + + api.GoSettings = (function() { + + /** + * Properties of a GoSettings. + * @memberof google.api + * @interface IGoSettings + * @property {google.api.ICommonLanguageSettings|null} [common] GoSettings common + * @property {Object.|null} [renamedServices] GoSettings renamedServices + */ + + /** + * Constructs a new GoSettings. + * @memberof google.api + * @classdesc Represents a GoSettings. + * @implements IGoSettings + * @constructor + * @param {google.api.IGoSettings=} [properties] Properties to set + */ + function GoSettings(properties) { + this.renamedServices = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GoSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.GoSettings + * @instance + */ + GoSettings.prototype.common = null; + + /** + * GoSettings renamedServices. + * @member {Object.} renamedServices + * @memberof google.api.GoSettings + * @instance + */ + GoSettings.prototype.renamedServices = $util.emptyObject; + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.GoSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.GoSettings} GoSettings + */ + GoSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.GoSettings) + return object; + var message = new $root.google.api.GoSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.GoSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + if (object.renamedServices) { + if (typeof object.renamedServices !== "object") + throw TypeError(".google.api.GoSettings.renamedServices: object expected"); + message.renamedServices = {}; + for (var keys = Object.keys(object.renamedServices), i = 0; i < keys.length; ++i) + message.renamedServices[keys[i]] = String(object.renamedServices[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.GoSettings + * @static + * @param {google.api.GoSettings} message GoSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GoSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.renamedServices = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + var keys2; + if (message.renamedServices && (keys2 = Object.keys(message.renamedServices)).length) { + object.renamedServices = {}; + for (var j = 0; j < keys2.length; ++j) + object.renamedServices[keys2[j]] = message.renamedServices[keys2[j]]; + } + return object; + }; + + /** + * Converts this GoSettings to JSON. + * @function toJSON + * @memberof google.api.GoSettings + * @instance + * @returns {Object.} JSON object + */ + GoSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GoSettings + * @function getTypeUrl + * @memberof google.api.GoSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GoSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.GoSettings"; + }; + + return GoSettings; + })(); + + api.MethodSettings = (function() { + + /** + * Properties of a MethodSettings. + * @memberof google.api + * @interface IMethodSettings + * @property {string|null} [selector] MethodSettings selector + * @property {google.api.MethodSettings.ILongRunning|null} [longRunning] MethodSettings longRunning + * @property {Array.|null} [autoPopulatedFields] MethodSettings autoPopulatedFields + */ + + /** + * Constructs a new MethodSettings. + * @memberof google.api + * @classdesc Represents a MethodSettings. + * @implements IMethodSettings + * @constructor + * @param {google.api.IMethodSettings=} [properties] Properties to set + */ + function MethodSettings(properties) { + this.autoPopulatedFields = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MethodSettings selector. + * @member {string} selector + * @memberof google.api.MethodSettings + * @instance + */ + MethodSettings.prototype.selector = ""; + + /** + * MethodSettings longRunning. + * @member {google.api.MethodSettings.ILongRunning|null|undefined} longRunning + * @memberof google.api.MethodSettings + * @instance + */ + MethodSettings.prototype.longRunning = null; + + /** + * MethodSettings autoPopulatedFields. + * @member {Array.} autoPopulatedFields + * @memberof google.api.MethodSettings + * @instance + */ + MethodSettings.prototype.autoPopulatedFields = $util.emptyArray; + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.MethodSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.MethodSettings} MethodSettings + */ + MethodSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.MethodSettings) + return object; + var message = new $root.google.api.MethodSettings(); + if (object.selector != null) + message.selector = String(object.selector); + if (object.longRunning != null) { + if (typeof object.longRunning !== "object") + throw TypeError(".google.api.MethodSettings.longRunning: object expected"); + message.longRunning = $root.google.api.MethodSettings.LongRunning.fromObject(object.longRunning); + } + if (object.autoPopulatedFields) { + if (!Array.isArray(object.autoPopulatedFields)) + throw TypeError(".google.api.MethodSettings.autoPopulatedFields: array expected"); + message.autoPopulatedFields = []; + for (var i = 0; i < object.autoPopulatedFields.length; ++i) + message.autoPopulatedFields[i] = String(object.autoPopulatedFields[i]); + } + return message; + }; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.MethodSettings + * @static + * @param {google.api.MethodSettings} message MethodSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MethodSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.autoPopulatedFields = []; + if (options.defaults) { + object.selector = ""; + object.longRunning = null; + } + if (message.selector != null && message.hasOwnProperty("selector")) + object.selector = message.selector; + if (message.longRunning != null && message.hasOwnProperty("longRunning")) + object.longRunning = $root.google.api.MethodSettings.LongRunning.toObject(message.longRunning, options); + if (message.autoPopulatedFields && message.autoPopulatedFields.length) { + object.autoPopulatedFields = []; + for (var j = 0; j < message.autoPopulatedFields.length; ++j) + object.autoPopulatedFields[j] = message.autoPopulatedFields[j]; + } + return object; + }; + + /** + * Converts this MethodSettings to JSON. + * @function toJSON + * @memberof google.api.MethodSettings + * @instance + * @returns {Object.} JSON object + */ + MethodSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MethodSettings + * @function getTypeUrl + * @memberof google.api.MethodSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MethodSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.MethodSettings"; + }; + + MethodSettings.LongRunning = (function() { + + /** + * Properties of a LongRunning. + * @memberof google.api.MethodSettings + * @interface ILongRunning + * @property {google.protobuf.IDuration|null} [initialPollDelay] LongRunning initialPollDelay + * @property {number|null} [pollDelayMultiplier] LongRunning pollDelayMultiplier + * @property {google.protobuf.IDuration|null} [maxPollDelay] LongRunning maxPollDelay + * @property {google.protobuf.IDuration|null} [totalPollTimeout] LongRunning totalPollTimeout + */ + + /** + * Constructs a new LongRunning. + * @memberof google.api.MethodSettings + * @classdesc Represents a LongRunning. + * @implements ILongRunning + * @constructor + * @param {google.api.MethodSettings.ILongRunning=} [properties] Properties to set + */ + function LongRunning(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * LongRunning initialPollDelay. + * @member {google.protobuf.IDuration|null|undefined} initialPollDelay + * @memberof google.api.MethodSettings.LongRunning + * @instance + */ + LongRunning.prototype.initialPollDelay = null; + + /** + * LongRunning pollDelayMultiplier. + * @member {number} pollDelayMultiplier + * @memberof google.api.MethodSettings.LongRunning + * @instance + */ + LongRunning.prototype.pollDelayMultiplier = 0; + + /** + * LongRunning maxPollDelay. + * @member {google.protobuf.IDuration|null|undefined} maxPollDelay + * @memberof google.api.MethodSettings.LongRunning + * @instance + */ + LongRunning.prototype.maxPollDelay = null; + + /** + * LongRunning totalPollTimeout. + * @member {google.protobuf.IDuration|null|undefined} totalPollTimeout + * @memberof google.api.MethodSettings.LongRunning + * @instance + */ + LongRunning.prototype.totalPollTimeout = null; + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {Object.} object Plain object + * @returns {google.api.MethodSettings.LongRunning} LongRunning + */ + LongRunning.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.MethodSettings.LongRunning) + return object; + var message = new $root.google.api.MethodSettings.LongRunning(); + if (object.initialPollDelay != null) { + if (typeof object.initialPollDelay !== "object") + throw TypeError(".google.api.MethodSettings.LongRunning.initialPollDelay: object expected"); + message.initialPollDelay = $root.google.protobuf.Duration.fromObject(object.initialPollDelay); + } + if (object.pollDelayMultiplier != null) + message.pollDelayMultiplier = Number(object.pollDelayMultiplier); + if (object.maxPollDelay != null) { + if (typeof object.maxPollDelay !== "object") + throw TypeError(".google.api.MethodSettings.LongRunning.maxPollDelay: object expected"); + message.maxPollDelay = $root.google.protobuf.Duration.fromObject(object.maxPollDelay); + } + if (object.totalPollTimeout != null) { + if (typeof object.totalPollTimeout !== "object") + throw TypeError(".google.api.MethodSettings.LongRunning.totalPollTimeout: object expected"); + message.totalPollTimeout = $root.google.protobuf.Duration.fromObject(object.totalPollTimeout); + } + return message; + }; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {google.api.MethodSettings.LongRunning} message LongRunning + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + LongRunning.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.initialPollDelay = null; + object.pollDelayMultiplier = 0; + object.maxPollDelay = null; + object.totalPollTimeout = null; + } + if (message.initialPollDelay != null && message.hasOwnProperty("initialPollDelay")) + object.initialPollDelay = $root.google.protobuf.Duration.toObject(message.initialPollDelay, options); + if (message.pollDelayMultiplier != null && message.hasOwnProperty("pollDelayMultiplier")) + object.pollDelayMultiplier = options.json && !isFinite(message.pollDelayMultiplier) ? String(message.pollDelayMultiplier) : message.pollDelayMultiplier; + if (message.maxPollDelay != null && message.hasOwnProperty("maxPollDelay")) + object.maxPollDelay = $root.google.protobuf.Duration.toObject(message.maxPollDelay, options); + if (message.totalPollTimeout != null && message.hasOwnProperty("totalPollTimeout")) + object.totalPollTimeout = $root.google.protobuf.Duration.toObject(message.totalPollTimeout, options); + return object; + }; + + /** + * Converts this LongRunning to JSON. + * @function toJSON + * @memberof google.api.MethodSettings.LongRunning + * @instance + * @returns {Object.} JSON object + */ + LongRunning.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for LongRunning + * @function getTypeUrl + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + LongRunning.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.MethodSettings.LongRunning"; + }; + + return LongRunning; + })(); + + return MethodSettings; + })(); + + /** + * ClientLibraryOrganization enum. + * @name google.api.ClientLibraryOrganization + * @enum {string} + * @property {string} CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED=CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED value + * @property {string} CLOUD=CLOUD CLOUD value + * @property {string} ADS=ADS ADS value + * @property {string} PHOTOS=PHOTOS PHOTOS value + * @property {string} STREET_VIEW=STREET_VIEW STREET_VIEW value + * @property {string} SHOPPING=SHOPPING SHOPPING value + * @property {string} GEO=GEO GEO value + * @property {string} GENERATIVE_AI=GENERATIVE_AI GENERATIVE_AI value + */ + api.ClientLibraryOrganization = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"] = "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"; + values[valuesById[1] = "CLOUD"] = "CLOUD"; + values[valuesById[2] = "ADS"] = "ADS"; + values[valuesById[3] = "PHOTOS"] = "PHOTOS"; + values[valuesById[4] = "STREET_VIEW"] = "STREET_VIEW"; + values[valuesById[5] = "SHOPPING"] = "SHOPPING"; + values[valuesById[6] = "GEO"] = "GEO"; + values[valuesById[7] = "GENERATIVE_AI"] = "GENERATIVE_AI"; + return values; + })(); + + /** + * ClientLibraryDestination enum. + * @name google.api.ClientLibraryDestination + * @enum {string} + * @property {string} CLIENT_LIBRARY_DESTINATION_UNSPECIFIED=CLIENT_LIBRARY_DESTINATION_UNSPECIFIED CLIENT_LIBRARY_DESTINATION_UNSPECIFIED value + * @property {string} GITHUB=GITHUB GITHUB value + * @property {string} PACKAGE_MANAGER=PACKAGE_MANAGER PACKAGE_MANAGER value + */ + api.ClientLibraryDestination = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"] = "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"; + values[valuesById[10] = "GITHUB"] = "GITHUB"; + values[valuesById[20] = "PACKAGE_MANAGER"] = "PACKAGE_MANAGER"; + return values; + })(); + + api.SelectiveGapicGeneration = (function() { + + /** + * Properties of a SelectiveGapicGeneration. + * @memberof google.api + * @interface ISelectiveGapicGeneration + * @property {Array.|null} [methods] SelectiveGapicGeneration methods + * @property {boolean|null} [generateOmittedAsInternal] SelectiveGapicGeneration generateOmittedAsInternal + */ + + /** + * Constructs a new SelectiveGapicGeneration. + * @memberof google.api + * @classdesc Represents a SelectiveGapicGeneration. + * @implements ISelectiveGapicGeneration + * @constructor + * @param {google.api.ISelectiveGapicGeneration=} [properties] Properties to set + */ + function SelectiveGapicGeneration(properties) { + this.methods = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SelectiveGapicGeneration methods. + * @member {Array.} methods + * @memberof google.api.SelectiveGapicGeneration + * @instance + */ + SelectiveGapicGeneration.prototype.methods = $util.emptyArray; + + /** + * SelectiveGapicGeneration generateOmittedAsInternal. + * @member {boolean} generateOmittedAsInternal + * @memberof google.api.SelectiveGapicGeneration + * @instance + */ + SelectiveGapicGeneration.prototype.generateOmittedAsInternal = false; + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {Object.} object Plain object + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + */ + SelectiveGapicGeneration.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.SelectiveGapicGeneration) + return object; + var message = new $root.google.api.SelectiveGapicGeneration(); + if (object.methods) { + if (!Array.isArray(object.methods)) + throw TypeError(".google.api.SelectiveGapicGeneration.methods: array expected"); + message.methods = []; + for (var i = 0; i < object.methods.length; ++i) + message.methods[i] = String(object.methods[i]); + } + if (object.generateOmittedAsInternal != null) + message.generateOmittedAsInternal = Boolean(object.generateOmittedAsInternal); + return message; + }; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.SelectiveGapicGeneration} message SelectiveGapicGeneration + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SelectiveGapicGeneration.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.methods = []; + if (options.defaults) + object.generateOmittedAsInternal = false; + if (message.methods && message.methods.length) { + object.methods = []; + for (var j = 0; j < message.methods.length; ++j) + object.methods[j] = message.methods[j]; + } + if (message.generateOmittedAsInternal != null && message.hasOwnProperty("generateOmittedAsInternal")) + object.generateOmittedAsInternal = message.generateOmittedAsInternal; + return object; + }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @function toJSON + * @memberof google.api.SelectiveGapicGeneration + * @instance + * @returns {Object.} JSON object + */ + SelectiveGapicGeneration.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @function getTypeUrl + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SelectiveGapicGeneration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.SelectiveGapicGeneration"; + }; + + return SelectiveGapicGeneration; + })(); + + /** + * LaunchStage enum. + * @name google.api.LaunchStage + * @enum {string} + * @property {string} LAUNCH_STAGE_UNSPECIFIED=LAUNCH_STAGE_UNSPECIFIED LAUNCH_STAGE_UNSPECIFIED value + * @property {string} UNIMPLEMENTED=UNIMPLEMENTED UNIMPLEMENTED value + * @property {string} PRELAUNCH=PRELAUNCH PRELAUNCH value + * @property {string} EARLY_ACCESS=EARLY_ACCESS EARLY_ACCESS value + * @property {string} ALPHA=ALPHA ALPHA value + * @property {string} BETA=BETA BETA value + * @property {string} GA=GA GA value + * @property {string} DEPRECATED=DEPRECATED DEPRECATED value + */ + api.LaunchStage = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = "LAUNCH_STAGE_UNSPECIFIED"; + values[valuesById[6] = "UNIMPLEMENTED"] = "UNIMPLEMENTED"; + values[valuesById[7] = "PRELAUNCH"] = "PRELAUNCH"; + values[valuesById[1] = "EARLY_ACCESS"] = "EARLY_ACCESS"; + values[valuesById[2] = "ALPHA"] = "ALPHA"; + values[valuesById[3] = "BETA"] = "BETA"; + values[valuesById[4] = "GA"] = "GA"; + values[valuesById[5] = "DEPRECATED"] = "DEPRECATED"; + return values; + })(); + + api.RoutingRule = (function() { + + /** + * Properties of a RoutingRule. + * @memberof google.api + * @interface IRoutingRule + * @property {Array.|null} [routingParameters] RoutingRule routingParameters + */ + + /** + * Constructs a new RoutingRule. + * @memberof google.api + * @classdesc Represents a RoutingRule. + * @implements IRoutingRule + * @constructor + * @param {google.api.IRoutingRule=} [properties] Properties to set + */ + function RoutingRule(properties) { + this.routingParameters = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RoutingRule routingParameters. + * @member {Array.} routingParameters + * @memberof google.api.RoutingRule + * @instance + */ + RoutingRule.prototype.routingParameters = $util.emptyArray; + + /** + * Creates a RoutingRule message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.RoutingRule + * @static + * @param {Object.} object Plain object + * @returns {google.api.RoutingRule} RoutingRule + */ + RoutingRule.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RoutingRule) + return object; + var message = new $root.google.api.RoutingRule(); + if (object.routingParameters) { + if (!Array.isArray(object.routingParameters)) + throw TypeError(".google.api.RoutingRule.routingParameters: array expected"); + message.routingParameters = []; + for (var i = 0; i < object.routingParameters.length; ++i) { + if (typeof object.routingParameters[i] !== "object") + throw TypeError(".google.api.RoutingRule.routingParameters: object expected"); + message.routingParameters[i] = $root.google.api.RoutingParameter.fromObject(object.routingParameters[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a RoutingRule message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.RoutingRule + * @static + * @param {google.api.RoutingRule} message RoutingRule + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RoutingRule.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.routingParameters = []; + if (message.routingParameters && message.routingParameters.length) { + object.routingParameters = []; + for (var j = 0; j < message.routingParameters.length; ++j) + object.routingParameters[j] = $root.google.api.RoutingParameter.toObject(message.routingParameters[j], options); + } + return object; + }; + + /** + * Converts this RoutingRule to JSON. + * @function toJSON + * @memberof google.api.RoutingRule + * @instance + * @returns {Object.} JSON object + */ + RoutingRule.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RoutingRule + * @function getTypeUrl + * @memberof google.api.RoutingRule + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RoutingRule.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.RoutingRule"; + }; + + return RoutingRule; + })(); + + api.RoutingParameter = (function() { + + /** + * Properties of a RoutingParameter. + * @memberof google.api + * @interface IRoutingParameter + * @property {string|null} [field] RoutingParameter field + * @property {string|null} [pathTemplate] RoutingParameter pathTemplate + */ + + /** + * Constructs a new RoutingParameter. + * @memberof google.api + * @classdesc Represents a RoutingParameter. + * @implements IRoutingParameter + * @constructor + * @param {google.api.IRoutingParameter=} [properties] Properties to set + */ + function RoutingParameter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RoutingParameter field. + * @member {string} field + * @memberof google.api.RoutingParameter + * @instance + */ + RoutingParameter.prototype.field = ""; + + /** + * RoutingParameter pathTemplate. + * @member {string} pathTemplate + * @memberof google.api.RoutingParameter + * @instance + */ + RoutingParameter.prototype.pathTemplate = ""; + + /** + * Creates a RoutingParameter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.RoutingParameter + * @static + * @param {Object.} object Plain object + * @returns {google.api.RoutingParameter} RoutingParameter + */ + RoutingParameter.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RoutingParameter) + return object; + var message = new $root.google.api.RoutingParameter(); + if (object.field != null) + message.field = String(object.field); + if (object.pathTemplate != null) + message.pathTemplate = String(object.pathTemplate); + return message; + }; + + /** + * Creates a plain object from a RoutingParameter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.RoutingParameter + * @static + * @param {google.api.RoutingParameter} message RoutingParameter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RoutingParameter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.field = ""; + object.pathTemplate = ""; + } + if (message.field != null && message.hasOwnProperty("field")) + object.field = message.field; + if (message.pathTemplate != null && message.hasOwnProperty("pathTemplate")) + object.pathTemplate = message.pathTemplate; + return object; + }; + + /** + * Converts this RoutingParameter to JSON. + * @function toJSON + * @memberof google.api.RoutingParameter + * @instance + * @returns {Object.} JSON object + */ + RoutingParameter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RoutingParameter + * @function getTypeUrl + * @memberof google.api.RoutingParameter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RoutingParameter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.RoutingParameter"; + }; + + return RoutingParameter; + })(); + + api.ResourceDescriptor = (function() { + + /** + * Properties of a ResourceDescriptor. + * @memberof google.api + * @interface IResourceDescriptor + * @property {string|null} [type] ResourceDescriptor type + * @property {Array.|null} [pattern] ResourceDescriptor pattern + * @property {string|null} [nameField] ResourceDescriptor nameField + * @property {google.api.ResourceDescriptor.History|null} [history] ResourceDescriptor history + * @property {string|null} [plural] ResourceDescriptor plural + * @property {string|null} [singular] ResourceDescriptor singular + * @property {Array.|null} [style] ResourceDescriptor style + */ + + /** + * Constructs a new ResourceDescriptor. + * @memberof google.api + * @classdesc Represents a ResourceDescriptor. + * @implements IResourceDescriptor + * @constructor + * @param {google.api.IResourceDescriptor=} [properties] Properties to set + */ + function ResourceDescriptor(properties) { + this.pattern = []; + this.style = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResourceDescriptor type. + * @member {string} type + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.type = ""; + + /** + * ResourceDescriptor pattern. + * @member {Array.} pattern + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.pattern = $util.emptyArray; + + /** + * ResourceDescriptor nameField. + * @member {string} nameField + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.nameField = ""; + + /** + * ResourceDescriptor history. + * @member {google.api.ResourceDescriptor.History} history + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.history = 0; + + /** + * ResourceDescriptor plural. + * @member {string} plural + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.plural = ""; + + /** + * ResourceDescriptor singular. + * @member {string} singular + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.singular = ""; + + /** + * ResourceDescriptor style. + * @member {Array.} style + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.style = $util.emptyArray; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ResourceDescriptor + * @static + * @param {Object.} object Plain object + * @returns {google.api.ResourceDescriptor} ResourceDescriptor + */ + ResourceDescriptor.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ResourceDescriptor) + return object; + var message = new $root.google.api.ResourceDescriptor(); + if (object.type != null) + message.type = String(object.type); + if (object.pattern) { + if (!Array.isArray(object.pattern)) + throw TypeError(".google.api.ResourceDescriptor.pattern: array expected"); + message.pattern = []; + for (var i = 0; i < object.pattern.length; ++i) + message.pattern[i] = String(object.pattern[i]); + } + if (object.nameField != null) + message.nameField = String(object.nameField); + switch (object.history) { + default: + if (typeof object.history === "number") { + message.history = object.history; + break; + } + break; + case "HISTORY_UNSPECIFIED": + case 0: + message.history = 0; + break; + case "ORIGINALLY_SINGLE_PATTERN": + case 1: + message.history = 1; + break; + case "FUTURE_MULTI_PATTERN": + case 2: + message.history = 2; + break; + } + if (object.plural != null) + message.plural = String(object.plural); + if (object.singular != null) + message.singular = String(object.singular); + if (object.style) { + if (!Array.isArray(object.style)) + throw TypeError(".google.api.ResourceDescriptor.style: array expected"); + message.style = []; + for (var i = 0; i < object.style.length; ++i) + switch (object.style[i]) { + default: + if (typeof object.style[i] === "number") { + message.style[i] = object.style[i]; + break; + } + case "STYLE_UNSPECIFIED": + case 0: + message.style[i] = 0; + break; + case "DECLARATIVE_FRIENDLY": + case 1: + message.style[i] = 1; + break; + } + } + return message; + }; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ResourceDescriptor + * @static + * @param {google.api.ResourceDescriptor} message ResourceDescriptor + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceDescriptor.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.pattern = []; + object.style = []; + } + if (options.defaults) { + object.type = ""; + object.nameField = ""; + object.history = options.enums === String ? "HISTORY_UNSPECIFIED" : 0; + object.plural = ""; + object.singular = ""; + } + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.pattern && message.pattern.length) { + object.pattern = []; + for (var j = 0; j < message.pattern.length; ++j) + object.pattern[j] = message.pattern[j]; + } + if (message.nameField != null && message.hasOwnProperty("nameField")) + object.nameField = message.nameField; + if (message.history != null && message.hasOwnProperty("history")) + object.history = options.enums === String ? $root.google.api.ResourceDescriptor.History[message.history] === undefined ? message.history : $root.google.api.ResourceDescriptor.History[message.history] : message.history; + if (message.plural != null && message.hasOwnProperty("plural")) + object.plural = message.plural; + if (message.singular != null && message.hasOwnProperty("singular")) + object.singular = message.singular; + if (message.style && message.style.length) { + object.style = []; + for (var j = 0; j < message.style.length; ++j) + object.style[j] = options.enums === String ? $root.google.api.ResourceDescriptor.Style[message.style[j]] === undefined ? message.style[j] : $root.google.api.ResourceDescriptor.Style[message.style[j]] : message.style[j]; + } + return object; + }; + + /** + * Converts this ResourceDescriptor to JSON. + * @function toJSON + * @memberof google.api.ResourceDescriptor + * @instance + * @returns {Object.} JSON object + */ + ResourceDescriptor.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResourceDescriptor + * @function getTypeUrl + * @memberof google.api.ResourceDescriptor + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceDescriptor.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ResourceDescriptor"; + }; + + /** + * History enum. + * @name google.api.ResourceDescriptor.History + * @enum {string} + * @property {string} HISTORY_UNSPECIFIED=HISTORY_UNSPECIFIED HISTORY_UNSPECIFIED value + * @property {string} ORIGINALLY_SINGLE_PATTERN=ORIGINALLY_SINGLE_PATTERN ORIGINALLY_SINGLE_PATTERN value + * @property {string} FUTURE_MULTI_PATTERN=FUTURE_MULTI_PATTERN FUTURE_MULTI_PATTERN value + */ + ResourceDescriptor.History = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "HISTORY_UNSPECIFIED"] = "HISTORY_UNSPECIFIED"; + values[valuesById[1] = "ORIGINALLY_SINGLE_PATTERN"] = "ORIGINALLY_SINGLE_PATTERN"; + values[valuesById[2] = "FUTURE_MULTI_PATTERN"] = "FUTURE_MULTI_PATTERN"; + return values; + })(); + + /** + * Style enum. + * @name google.api.ResourceDescriptor.Style + * @enum {string} + * @property {string} STYLE_UNSPECIFIED=STYLE_UNSPECIFIED STYLE_UNSPECIFIED value + * @property {string} DECLARATIVE_FRIENDLY=DECLARATIVE_FRIENDLY DECLARATIVE_FRIENDLY value + */ + ResourceDescriptor.Style = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STYLE_UNSPECIFIED"] = "STYLE_UNSPECIFIED"; + values[valuesById[1] = "DECLARATIVE_FRIENDLY"] = "DECLARATIVE_FRIENDLY"; + return values; + })(); + + return ResourceDescriptor; + })(); + + api.ResourceReference = (function() { + + /** + * Properties of a ResourceReference. + * @memberof google.api + * @interface IResourceReference + * @property {string|null} [type] ResourceReference type + * @property {string|null} [childType] ResourceReference childType + */ + + /** + * Constructs a new ResourceReference. + * @memberof google.api + * @classdesc Represents a ResourceReference. + * @implements IResourceReference + * @constructor + * @param {google.api.IResourceReference=} [properties] Properties to set + */ + function ResourceReference(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResourceReference type. + * @member {string} type + * @memberof google.api.ResourceReference + * @instance + */ + ResourceReference.prototype.type = ""; + + /** + * ResourceReference childType. + * @member {string} childType + * @memberof google.api.ResourceReference + * @instance + */ + ResourceReference.prototype.childType = ""; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ResourceReference + * @static + * @param {Object.} object Plain object + * @returns {google.api.ResourceReference} ResourceReference + */ + ResourceReference.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ResourceReference) + return object; + var message = new $root.google.api.ResourceReference(); + if (object.type != null) + message.type = String(object.type); + if (object.childType != null) + message.childType = String(object.childType); + return message; + }; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ResourceReference + * @static + * @param {google.api.ResourceReference} message ResourceReference + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceReference.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.type = ""; + object.childType = ""; + } + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.childType != null && message.hasOwnProperty("childType")) + object.childType = message.childType; + return object; + }; + + /** + * Converts this ResourceReference to JSON. + * @function toJSON + * @memberof google.api.ResourceReference + * @instance + * @returns {Object.} JSON object + */ + ResourceReference.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResourceReference + * @function getTypeUrl + * @memberof google.api.ResourceReference + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceReference.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ResourceReference"; + }; + + return ResourceReference; + })(); + + return api; + })(); + + google.protobuf = (function() { + + /** + * Namespace protobuf. + * @memberof google + * @namespace + */ + var protobuf = {}; + + protobuf.FileDescriptorSet = (function() { + + /** + * Properties of a FileDescriptorSet. + * @memberof google.protobuf + * @interface IFileDescriptorSet + * @property {Array.|null} [file] FileDescriptorSet file + */ + + /** + * Constructs a new FileDescriptorSet. + * @memberof google.protobuf + * @classdesc Represents a FileDescriptorSet. + * @implements IFileDescriptorSet + * @constructor + * @param {google.protobuf.IFileDescriptorSet=} [properties] Properties to set + */ + function FileDescriptorSet(properties) { + this.file = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FileDescriptorSet file. + * @member {Array.} file + * @memberof google.protobuf.FileDescriptorSet + * @instance + */ + FileDescriptorSet.prototype.file = $util.emptyArray; + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FileDescriptorSet} FileDescriptorSet + */ + FileDescriptorSet.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FileDescriptorSet) + return object; + var message = new $root.google.protobuf.FileDescriptorSet(); + if (object.file) { + if (!Array.isArray(object.file)) + throw TypeError(".google.protobuf.FileDescriptorSet.file: array expected"); + message.file = []; + for (var i = 0; i < object.file.length; ++i) { + if (typeof object.file[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorSet.file: object expected"); + message.file[i] = $root.google.protobuf.FileDescriptorProto.fromObject(object.file[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {google.protobuf.FileDescriptorSet} message FileDescriptorSet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FileDescriptorSet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.file = []; + if (message.file && message.file.length) { + object.file = []; + for (var j = 0; j < message.file.length; ++j) + object.file[j] = $root.google.protobuf.FileDescriptorProto.toObject(message.file[j], options); + } + return object; + }; + + /** + * Converts this FileDescriptorSet to JSON. + * @function toJSON + * @memberof google.protobuf.FileDescriptorSet + * @instance + * @returns {Object.} JSON object + */ + FileDescriptorSet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FileDescriptorSet + * @function getTypeUrl + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FileDescriptorSet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FileDescriptorSet"; + }; + + return FileDescriptorSet; + })(); + + /** + * Edition enum. + * @name google.protobuf.Edition + * @enum {string} + * @property {string} EDITION_UNKNOWN=EDITION_UNKNOWN EDITION_UNKNOWN value + * @property {string} EDITION_PROTO2=EDITION_PROTO2 EDITION_PROTO2 value + * @property {string} EDITION_PROTO3=EDITION_PROTO3 EDITION_PROTO3 value + * @property {string} EDITION_2023=EDITION_2023 EDITION_2023 value + * @property {string} EDITION_2024=EDITION_2024 EDITION_2024 value + * @property {string} EDITION_1_TEST_ONLY=EDITION_1_TEST_ONLY EDITION_1_TEST_ONLY value + * @property {string} EDITION_2_TEST_ONLY=EDITION_2_TEST_ONLY EDITION_2_TEST_ONLY value + * @property {string} EDITION_99997_TEST_ONLY=EDITION_99997_TEST_ONLY EDITION_99997_TEST_ONLY value + * @property {string} EDITION_99998_TEST_ONLY=EDITION_99998_TEST_ONLY EDITION_99998_TEST_ONLY value + * @property {string} EDITION_99999_TEST_ONLY=EDITION_99999_TEST_ONLY EDITION_99999_TEST_ONLY value + * @property {string} EDITION_MAX=EDITION_MAX EDITION_MAX value + */ + protobuf.Edition = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "EDITION_UNKNOWN"] = "EDITION_UNKNOWN"; + values[valuesById[998] = "EDITION_PROTO2"] = "EDITION_PROTO2"; + values[valuesById[999] = "EDITION_PROTO3"] = "EDITION_PROTO3"; + values[valuesById[1000] = "EDITION_2023"] = "EDITION_2023"; + values[valuesById[1001] = "EDITION_2024"] = "EDITION_2024"; + values[valuesById[1] = "EDITION_1_TEST_ONLY"] = "EDITION_1_TEST_ONLY"; + values[valuesById[2] = "EDITION_2_TEST_ONLY"] = "EDITION_2_TEST_ONLY"; + values[valuesById[99997] = "EDITION_99997_TEST_ONLY"] = "EDITION_99997_TEST_ONLY"; + values[valuesById[99998] = "EDITION_99998_TEST_ONLY"] = "EDITION_99998_TEST_ONLY"; + values[valuesById[99999] = "EDITION_99999_TEST_ONLY"] = "EDITION_99999_TEST_ONLY"; + values[valuesById[2147483647] = "EDITION_MAX"] = "EDITION_MAX"; + return values; + })(); + + protobuf.FileDescriptorProto = (function() { + + /** + * Properties of a FileDescriptorProto. + * @memberof google.protobuf + * @interface IFileDescriptorProto + * @property {string|null} [name] FileDescriptorProto name + * @property {string|null} ["package"] FileDescriptorProto package + * @property {Array.|null} [dependency] FileDescriptorProto dependency + * @property {Array.|null} [publicDependency] FileDescriptorProto publicDependency + * @property {Array.|null} [weakDependency] FileDescriptorProto weakDependency + * @property {Array.|null} [messageType] FileDescriptorProto messageType + * @property {Array.|null} [enumType] FileDescriptorProto enumType + * @property {Array.|null} [service] FileDescriptorProto service + * @property {Array.|null} [extension] FileDescriptorProto extension + * @property {google.protobuf.IFileOptions|null} [options] FileDescriptorProto options + * @property {google.protobuf.ISourceCodeInfo|null} [sourceCodeInfo] FileDescriptorProto sourceCodeInfo + * @property {string|null} [syntax] FileDescriptorProto syntax + * @property {google.protobuf.Edition|null} [edition] FileDescriptorProto edition + */ + + /** + * Constructs a new FileDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a FileDescriptorProto. + * @implements IFileDescriptorProto + * @constructor + * @param {google.protobuf.IFileDescriptorProto=} [properties] Properties to set + */ + function FileDescriptorProto(properties) { + this.dependency = []; + this.publicDependency = []; + this.weakDependency = []; + this.messageType = []; + this.enumType = []; + this.service = []; + this.extension = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FileDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.name = ""; + + /** + * FileDescriptorProto package. + * @member {string} package + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype["package"] = ""; + + /** + * FileDescriptorProto dependency. + * @member {Array.} dependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.dependency = $util.emptyArray; + + /** + * FileDescriptorProto publicDependency. + * @member {Array.} publicDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.publicDependency = $util.emptyArray; + + /** + * FileDescriptorProto weakDependency. + * @member {Array.} weakDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.weakDependency = $util.emptyArray; + + /** + * FileDescriptorProto messageType. + * @member {Array.} messageType + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.messageType = $util.emptyArray; + + /** + * FileDescriptorProto enumType. + * @member {Array.} enumType + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.enumType = $util.emptyArray; + + /** + * FileDescriptorProto service. + * @member {Array.} service + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.service = $util.emptyArray; + + /** + * FileDescriptorProto extension. + * @member {Array.} extension + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.extension = $util.emptyArray; + + /** + * FileDescriptorProto options. + * @member {google.protobuf.IFileOptions|null|undefined} options + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.options = null; + + /** + * FileDescriptorProto sourceCodeInfo. + * @member {google.protobuf.ISourceCodeInfo|null|undefined} sourceCodeInfo + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.sourceCodeInfo = null; + + /** + * FileDescriptorProto syntax. + * @member {string} syntax + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.syntax = ""; + + /** + * FileDescriptorProto edition. + * @member {google.protobuf.Edition} edition + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.edition = 0; + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FileDescriptorProto} FileDescriptorProto + */ + FileDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FileDescriptorProto) + return object; + var message = new $root.google.protobuf.FileDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object["package"] != null) + message["package"] = String(object["package"]); + if (object.dependency) { + if (!Array.isArray(object.dependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.dependency: array expected"); + message.dependency = []; + for (var i = 0; i < object.dependency.length; ++i) + message.dependency[i] = String(object.dependency[i]); + } + if (object.publicDependency) { + if (!Array.isArray(object.publicDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.publicDependency: array expected"); + message.publicDependency = []; + for (var i = 0; i < object.publicDependency.length; ++i) + message.publicDependency[i] = object.publicDependency[i] | 0; + } + if (object.weakDependency) { + if (!Array.isArray(object.weakDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.weakDependency: array expected"); + message.weakDependency = []; + for (var i = 0; i < object.weakDependency.length; ++i) + message.weakDependency[i] = object.weakDependency[i] | 0; + } + if (object.messageType) { + if (!Array.isArray(object.messageType)) + throw TypeError(".google.protobuf.FileDescriptorProto.messageType: array expected"); + message.messageType = []; + for (var i = 0; i < object.messageType.length; ++i) { + if (typeof object.messageType[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.messageType: object expected"); + message.messageType[i] = $root.google.protobuf.DescriptorProto.fromObject(object.messageType[i]); + } + } + if (object.enumType) { + if (!Array.isArray(object.enumType)) + throw TypeError(".google.protobuf.FileDescriptorProto.enumType: array expected"); + message.enumType = []; + for (var i = 0; i < object.enumType.length; ++i) { + if (typeof object.enumType[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.enumType: object expected"); + message.enumType[i] = $root.google.protobuf.EnumDescriptorProto.fromObject(object.enumType[i]); + } + } + if (object.service) { + if (!Array.isArray(object.service)) + throw TypeError(".google.protobuf.FileDescriptorProto.service: array expected"); + message.service = []; + for (var i = 0; i < object.service.length; ++i) { + if (typeof object.service[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.service: object expected"); + message.service[i] = $root.google.protobuf.ServiceDescriptorProto.fromObject(object.service[i]); + } + } + if (object.extension) { + if (!Array.isArray(object.extension)) + throw TypeError(".google.protobuf.FileDescriptorProto.extension: array expected"); + message.extension = []; + for (var i = 0; i < object.extension.length; ++i) { + if (typeof object.extension[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.extension: object expected"); + message.extension[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.extension[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.FileOptions.fromObject(object.options); + } + if (object.sourceCodeInfo != null) { + if (typeof object.sourceCodeInfo !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.sourceCodeInfo: object expected"); + message.sourceCodeInfo = $root.google.protobuf.SourceCodeInfo.fromObject(object.sourceCodeInfo); + } + if (object.syntax != null) + message.syntax = String(object.syntax); + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.edition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.edition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.edition = 999; + break; + case "EDITION_2023": + case 1000: + message.edition = 1000; + break; + case "EDITION_2024": + case 1001: + message.edition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.edition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.edition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.edition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.edition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.edition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.edition = 2147483647; + break; + } + return message; + }; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {google.protobuf.FileDescriptorProto} message FileDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FileDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.dependency = []; + object.messageType = []; + object.enumType = []; + object.service = []; + object.extension = []; + object.publicDependency = []; + object.weakDependency = []; + } + if (options.defaults) { + object.name = ""; + object["package"] = ""; + object.options = null; + object.sourceCodeInfo = null; + object.syntax = ""; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message["package"] != null && message.hasOwnProperty("package")) + object["package"] = message["package"]; + if (message.dependency && message.dependency.length) { + object.dependency = []; + for (var j = 0; j < message.dependency.length; ++j) + object.dependency[j] = message.dependency[j]; + } + if (message.messageType && message.messageType.length) { + object.messageType = []; + for (var j = 0; j < message.messageType.length; ++j) + object.messageType[j] = $root.google.protobuf.DescriptorProto.toObject(message.messageType[j], options); + } + if (message.enumType && message.enumType.length) { + object.enumType = []; + for (var j = 0; j < message.enumType.length; ++j) + object.enumType[j] = $root.google.protobuf.EnumDescriptorProto.toObject(message.enumType[j], options); + } + if (message.service && message.service.length) { + object.service = []; + for (var j = 0; j < message.service.length; ++j) + object.service[j] = $root.google.protobuf.ServiceDescriptorProto.toObject(message.service[j], options); + } + if (message.extension && message.extension.length) { + object.extension = []; + for (var j = 0; j < message.extension.length; ++j) + object.extension[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.extension[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.FileOptions.toObject(message.options, options); + if (message.sourceCodeInfo != null && message.hasOwnProperty("sourceCodeInfo")) + object.sourceCodeInfo = $root.google.protobuf.SourceCodeInfo.toObject(message.sourceCodeInfo, options); + if (message.publicDependency && message.publicDependency.length) { + object.publicDependency = []; + for (var j = 0; j < message.publicDependency.length; ++j) + object.publicDependency[j] = message.publicDependency[j]; + } + if (message.weakDependency && message.weakDependency.length) { + object.weakDependency = []; + for (var j = 0; j < message.weakDependency.length; ++j) + object.weakDependency[j] = message.weakDependency[j]; + } + if (message.syntax != null && message.hasOwnProperty("syntax")) + object.syntax = message.syntax; + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; + return object; + }; + + /** + * Converts this FileDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.FileDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + FileDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FileDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FileDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FileDescriptorProto"; + }; + + return FileDescriptorProto; + })(); + + protobuf.DescriptorProto = (function() { + + /** + * Properties of a DescriptorProto. + * @memberof google.protobuf + * @interface IDescriptorProto + * @property {string|null} [name] DescriptorProto name + * @property {Array.|null} [field] DescriptorProto field + * @property {Array.|null} [extension] DescriptorProto extension + * @property {Array.|null} [nestedType] DescriptorProto nestedType + * @property {Array.|null} [enumType] DescriptorProto enumType + * @property {Array.|null} [extensionRange] DescriptorProto extensionRange + * @property {Array.|null} [oneofDecl] DescriptorProto oneofDecl + * @property {google.protobuf.IMessageOptions|null} [options] DescriptorProto options + * @property {Array.|null} [reservedRange] DescriptorProto reservedRange + * @property {Array.|null} [reservedName] DescriptorProto reservedName + */ + + /** + * Constructs a new DescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a DescriptorProto. + * @implements IDescriptorProto + * @constructor + * @param {google.protobuf.IDescriptorProto=} [properties] Properties to set + */ + function DescriptorProto(properties) { + this.field = []; + this.extension = []; + this.nestedType = []; + this.enumType = []; + this.extensionRange = []; + this.oneofDecl = []; + this.reservedRange = []; + this.reservedName = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DescriptorProto name. + * @member {string} name + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.name = ""; + + /** + * DescriptorProto field. + * @member {Array.} field + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.field = $util.emptyArray; + + /** + * DescriptorProto extension. + * @member {Array.} extension + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.extension = $util.emptyArray; + + /** + * DescriptorProto nestedType. + * @member {Array.} nestedType + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.nestedType = $util.emptyArray; + + /** + * DescriptorProto enumType. + * @member {Array.} enumType + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.enumType = $util.emptyArray; + + /** + * DescriptorProto extensionRange. + * @member {Array.} extensionRange + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.extensionRange = $util.emptyArray; + + /** + * DescriptorProto oneofDecl. + * @member {Array.} oneofDecl + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.oneofDecl = $util.emptyArray; + + /** + * DescriptorProto options. + * @member {google.protobuf.IMessageOptions|null|undefined} options + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.options = null; + + /** + * DescriptorProto reservedRange. + * @member {Array.} reservedRange + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.reservedRange = $util.emptyArray; + + /** + * DescriptorProto reservedName. + * @member {Array.} reservedName + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.reservedName = $util.emptyArray; + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DescriptorProto} DescriptorProto + */ + DescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DescriptorProto) + return object; + var message = new $root.google.protobuf.DescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.field) { + if (!Array.isArray(object.field)) + throw TypeError(".google.protobuf.DescriptorProto.field: array expected"); + message.field = []; + for (var i = 0; i < object.field.length; ++i) { + if (typeof object.field[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.field: object expected"); + message.field[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.field[i]); + } + } + if (object.extension) { + if (!Array.isArray(object.extension)) + throw TypeError(".google.protobuf.DescriptorProto.extension: array expected"); + message.extension = []; + for (var i = 0; i < object.extension.length; ++i) { + if (typeof object.extension[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.extension: object expected"); + message.extension[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.extension[i]); + } + } + if (object.nestedType) { + if (!Array.isArray(object.nestedType)) + throw TypeError(".google.protobuf.DescriptorProto.nestedType: array expected"); + message.nestedType = []; + for (var i = 0; i < object.nestedType.length; ++i) { + if (typeof object.nestedType[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.nestedType: object expected"); + message.nestedType[i] = $root.google.protobuf.DescriptorProto.fromObject(object.nestedType[i]); + } + } + if (object.enumType) { + if (!Array.isArray(object.enumType)) + throw TypeError(".google.protobuf.DescriptorProto.enumType: array expected"); + message.enumType = []; + for (var i = 0; i < object.enumType.length; ++i) { + if (typeof object.enumType[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.enumType: object expected"); + message.enumType[i] = $root.google.protobuf.EnumDescriptorProto.fromObject(object.enumType[i]); + } + } + if (object.extensionRange) { + if (!Array.isArray(object.extensionRange)) + throw TypeError(".google.protobuf.DescriptorProto.extensionRange: array expected"); + message.extensionRange = []; + for (var i = 0; i < object.extensionRange.length; ++i) { + if (typeof object.extensionRange[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.extensionRange: object expected"); + message.extensionRange[i] = $root.google.protobuf.DescriptorProto.ExtensionRange.fromObject(object.extensionRange[i]); + } + } + if (object.oneofDecl) { + if (!Array.isArray(object.oneofDecl)) + throw TypeError(".google.protobuf.DescriptorProto.oneofDecl: array expected"); + message.oneofDecl = []; + for (var i = 0; i < object.oneofDecl.length; ++i) { + if (typeof object.oneofDecl[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.oneofDecl: object expected"); + message.oneofDecl[i] = $root.google.protobuf.OneofDescriptorProto.fromObject(object.oneofDecl[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.DescriptorProto.options: object expected"); + message.options = $root.google.protobuf.MessageOptions.fromObject(object.options); + } + if (object.reservedRange) { + if (!Array.isArray(object.reservedRange)) + throw TypeError(".google.protobuf.DescriptorProto.reservedRange: array expected"); + message.reservedRange = []; + for (var i = 0; i < object.reservedRange.length; ++i) { + if (typeof object.reservedRange[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.reservedRange: object expected"); + message.reservedRange[i] = $root.google.protobuf.DescriptorProto.ReservedRange.fromObject(object.reservedRange[i]); + } + } + if (object.reservedName) { + if (!Array.isArray(object.reservedName)) + throw TypeError(".google.protobuf.DescriptorProto.reservedName: array expected"); + message.reservedName = []; + for (var i = 0; i < object.reservedName.length; ++i) + message.reservedName[i] = String(object.reservedName[i]); + } + return message; + }; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.DescriptorProto + * @static + * @param {google.protobuf.DescriptorProto} message DescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.field = []; + object.nestedType = []; + object.enumType = []; + object.extensionRange = []; + object.extension = []; + object.oneofDecl = []; + object.reservedRange = []; + object.reservedName = []; + } + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.field && message.field.length) { + object.field = []; + for (var j = 0; j < message.field.length; ++j) + object.field[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.field[j], options); + } + if (message.nestedType && message.nestedType.length) { + object.nestedType = []; + for (var j = 0; j < message.nestedType.length; ++j) + object.nestedType[j] = $root.google.protobuf.DescriptorProto.toObject(message.nestedType[j], options); + } + if (message.enumType && message.enumType.length) { + object.enumType = []; + for (var j = 0; j < message.enumType.length; ++j) + object.enumType[j] = $root.google.protobuf.EnumDescriptorProto.toObject(message.enumType[j], options); + } + if (message.extensionRange && message.extensionRange.length) { + object.extensionRange = []; + for (var j = 0; j < message.extensionRange.length; ++j) + object.extensionRange[j] = $root.google.protobuf.DescriptorProto.ExtensionRange.toObject(message.extensionRange[j], options); + } + if (message.extension && message.extension.length) { + object.extension = []; + for (var j = 0; j < message.extension.length; ++j) + object.extension[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.extension[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.MessageOptions.toObject(message.options, options); + if (message.oneofDecl && message.oneofDecl.length) { + object.oneofDecl = []; + for (var j = 0; j < message.oneofDecl.length; ++j) + object.oneofDecl[j] = $root.google.protobuf.OneofDescriptorProto.toObject(message.oneofDecl[j], options); + } + if (message.reservedRange && message.reservedRange.length) { + object.reservedRange = []; + for (var j = 0; j < message.reservedRange.length; ++j) + object.reservedRange[j] = $root.google.protobuf.DescriptorProto.ReservedRange.toObject(message.reservedRange[j], options); + } + if (message.reservedName && message.reservedName.length) { + object.reservedName = []; + for (var j = 0; j < message.reservedName.length; ++j) + object.reservedName[j] = message.reservedName[j]; + } + return object; + }; + + /** + * Converts this DescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.DescriptorProto + * @instance + * @returns {Object.} JSON object + */ + DescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.DescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.DescriptorProto"; + }; + + DescriptorProto.ExtensionRange = (function() { + + /** + * Properties of an ExtensionRange. + * @memberof google.protobuf.DescriptorProto + * @interface IExtensionRange + * @property {number|null} [start] ExtensionRange start + * @property {number|null} [end] ExtensionRange end + * @property {google.protobuf.IExtensionRangeOptions|null} [options] ExtensionRange options + */ + + /** + * Constructs a new ExtensionRange. + * @memberof google.protobuf.DescriptorProto + * @classdesc Represents an ExtensionRange. + * @implements IExtensionRange + * @constructor + * @param {google.protobuf.DescriptorProto.IExtensionRange=} [properties] Properties to set + */ + function ExtensionRange(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExtensionRange start. + * @member {number} start + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @instance + */ + ExtensionRange.prototype.start = 0; + + /** + * ExtensionRange end. + * @member {number} end + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @instance + */ + ExtensionRange.prototype.end = 0; + + /** + * ExtensionRange options. + * @member {google.protobuf.IExtensionRangeOptions|null|undefined} options + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @instance + */ + ExtensionRange.prototype.options = null; + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DescriptorProto.ExtensionRange} ExtensionRange + */ + ExtensionRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DescriptorProto.ExtensionRange) + return object; + var message = new $root.google.protobuf.DescriptorProto.ExtensionRange(); + if (object.start != null) + message.start = object.start | 0; + if (object.end != null) + message.end = object.end | 0; + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.DescriptorProto.ExtensionRange.options: object expected"); + message.options = $root.google.protobuf.ExtensionRangeOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {google.protobuf.DescriptorProto.ExtensionRange} message ExtensionRange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExtensionRange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.start = 0; + object.end = 0; + object.options = null; + } + if (message.start != null && message.hasOwnProperty("start")) + object.start = message.start; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.ExtensionRangeOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this ExtensionRange to JSON. + * @function toJSON + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @instance + * @returns {Object.} JSON object + */ + ExtensionRange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExtensionRange + * @function getTypeUrl + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExtensionRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.DescriptorProto.ExtensionRange"; + }; + + return ExtensionRange; + })(); + + DescriptorProto.ReservedRange = (function() { + + /** + * Properties of a ReservedRange. + * @memberof google.protobuf.DescriptorProto + * @interface IReservedRange + * @property {number|null} [start] ReservedRange start + * @property {number|null} [end] ReservedRange end + */ + + /** + * Constructs a new ReservedRange. + * @memberof google.protobuf.DescriptorProto + * @classdesc Represents a ReservedRange. + * @implements IReservedRange + * @constructor + * @param {google.protobuf.DescriptorProto.IReservedRange=} [properties] Properties to set + */ + function ReservedRange(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReservedRange start. + * @member {number} start + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @instance + */ + ReservedRange.prototype.start = 0; + + /** + * ReservedRange end. + * @member {number} end + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @instance + */ + ReservedRange.prototype.end = 0; + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DescriptorProto.ReservedRange} ReservedRange + */ + ReservedRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DescriptorProto.ReservedRange) + return object; + var message = new $root.google.protobuf.DescriptorProto.ReservedRange(); + if (object.start != null) + message.start = object.start | 0; + if (object.end != null) + message.end = object.end | 0; + return message; + }; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {google.protobuf.DescriptorProto.ReservedRange} message ReservedRange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReservedRange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.start = 0; + object.end = 0; + } + if (message.start != null && message.hasOwnProperty("start")) + object.start = message.start; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + return object; + }; + + /** + * Converts this ReservedRange to JSON. + * @function toJSON + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @instance + * @returns {Object.} JSON object + */ + ReservedRange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReservedRange + * @function getTypeUrl + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReservedRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.DescriptorProto.ReservedRange"; + }; + + return ReservedRange; + })(); + + return DescriptorProto; + })(); + + protobuf.ExtensionRangeOptions = (function() { + + /** + * Properties of an ExtensionRangeOptions. + * @memberof google.protobuf + * @interface IExtensionRangeOptions + * @property {Array.|null} [uninterpretedOption] ExtensionRangeOptions uninterpretedOption + * @property {Array.|null} [declaration] ExtensionRangeOptions declaration + * @property {google.protobuf.IFeatureSet|null} [features] ExtensionRangeOptions features + * @property {google.protobuf.ExtensionRangeOptions.VerificationState|null} [verification] ExtensionRangeOptions verification + */ + + /** + * Constructs a new ExtensionRangeOptions. + * @memberof google.protobuf + * @classdesc Represents an ExtensionRangeOptions. + * @implements IExtensionRangeOptions + * @constructor + * @param {google.protobuf.IExtensionRangeOptions=} [properties] Properties to set + */ + function ExtensionRangeOptions(properties) { + this.uninterpretedOption = []; + this.declaration = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExtensionRangeOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * ExtensionRangeOptions declaration. + * @member {Array.} declaration + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.declaration = $util.emptyArray; + + /** + * ExtensionRangeOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.features = null; + + /** + * ExtensionRangeOptions verification. + * @member {google.protobuf.ExtensionRangeOptions.VerificationState} verification + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.verification = 1; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ExtensionRangeOptions} ExtensionRangeOptions + */ + ExtensionRangeOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ExtensionRangeOptions) + return object; + var message = new $root.google.protobuf.ExtensionRangeOptions(); + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.ExtensionRangeOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.ExtensionRangeOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object.declaration) { + if (!Array.isArray(object.declaration)) + throw TypeError(".google.protobuf.ExtensionRangeOptions.declaration: array expected"); + message.declaration = []; + for (var i = 0; i < object.declaration.length; ++i) { + if (typeof object.declaration[i] !== "object") + throw TypeError(".google.protobuf.ExtensionRangeOptions.declaration: object expected"); + message.declaration[i] = $root.google.protobuf.ExtensionRangeOptions.Declaration.fromObject(object.declaration[i]); + } + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.ExtensionRangeOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + switch (object.verification) { + case "DECLARATION": + case 0: + message.verification = 0; + break; + default: + if (typeof object.verification === "number") { + message.verification = object.verification; + break; + } + break; + case "UNVERIFIED": + case 1: + message.verification = 1; + break; + } + return message; + }; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {google.protobuf.ExtensionRangeOptions} message ExtensionRangeOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExtensionRangeOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.declaration = []; + object.uninterpretedOption = []; + } + if (options.defaults) { + object.verification = options.enums === String ? "UNVERIFIED" : 1; + object.features = null; + } + if (message.declaration && message.declaration.length) { + object.declaration = []; + for (var j = 0; j < message.declaration.length; ++j) + object.declaration[j] = $root.google.protobuf.ExtensionRangeOptions.Declaration.toObject(message.declaration[j], options); + } + if (message.verification != null && message.hasOwnProperty("verification")) + object.verification = options.enums === String ? $root.google.protobuf.ExtensionRangeOptions.VerificationState[message.verification] === undefined ? message.verification : $root.google.protobuf.ExtensionRangeOptions.VerificationState[message.verification] : message.verification; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @function toJSON + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + * @returns {Object.} JSON object + */ + ExtensionRangeOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @function getTypeUrl + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExtensionRangeOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ExtensionRangeOptions"; + }; + + ExtensionRangeOptions.Declaration = (function() { + + /** + * Properties of a Declaration. + * @memberof google.protobuf.ExtensionRangeOptions + * @interface IDeclaration + * @property {number|null} [number] Declaration number + * @property {string|null} [fullName] Declaration fullName + * @property {string|null} [type] Declaration type + * @property {boolean|null} [reserved] Declaration reserved + * @property {boolean|null} [repeated] Declaration repeated + */ + + /** + * Constructs a new Declaration. + * @memberof google.protobuf.ExtensionRangeOptions + * @classdesc Represents a Declaration. + * @implements IDeclaration + * @constructor + * @param {google.protobuf.ExtensionRangeOptions.IDeclaration=} [properties] Properties to set + */ + function Declaration(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Declaration number. + * @member {number} number + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.number = 0; + + /** + * Declaration fullName. + * @member {string} fullName + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.fullName = ""; + + /** + * Declaration type. + * @member {string} type + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.type = ""; + + /** + * Declaration reserved. + * @member {boolean} reserved + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.reserved = false; + + /** + * Declaration repeated. + * @member {boolean} repeated + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.repeated = false; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ExtensionRangeOptions.Declaration} Declaration + */ + Declaration.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ExtensionRangeOptions.Declaration) + return object; + var message = new $root.google.protobuf.ExtensionRangeOptions.Declaration(); + if (object.number != null) + message.number = object.number | 0; + if (object.fullName != null) + message.fullName = String(object.fullName); + if (object.type != null) + message.type = String(object.type); + if (object.reserved != null) + message.reserved = Boolean(object.reserved); + if (object.repeated != null) + message.repeated = Boolean(object.repeated); + return message; + }; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {google.protobuf.ExtensionRangeOptions.Declaration} message Declaration + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Declaration.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.number = 0; + object.fullName = ""; + object.type = ""; + object.reserved = false; + object.repeated = false; + } + if (message.number != null && message.hasOwnProperty("number")) + object.number = message.number; + if (message.fullName != null && message.hasOwnProperty("fullName")) + object.fullName = message.fullName; + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.reserved != null && message.hasOwnProperty("reserved")) + object.reserved = message.reserved; + if (message.repeated != null && message.hasOwnProperty("repeated")) + object.repeated = message.repeated; + return object; + }; + + /** + * Converts this Declaration to JSON. + * @function toJSON + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + * @returns {Object.} JSON object + */ + Declaration.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Declaration + * @function getTypeUrl + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Declaration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ExtensionRangeOptions.Declaration"; + }; + + return Declaration; + })(); + + /** + * VerificationState enum. + * @name google.protobuf.ExtensionRangeOptions.VerificationState + * @enum {string} + * @property {string} DECLARATION=DECLARATION DECLARATION value + * @property {string} UNVERIFIED=UNVERIFIED UNVERIFIED value + */ + ExtensionRangeOptions.VerificationState = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DECLARATION"] = "DECLARATION"; + values[valuesById[1] = "UNVERIFIED"] = "UNVERIFIED"; + return values; + })(); + + return ExtensionRangeOptions; + })(); + + protobuf.FieldDescriptorProto = (function() { + + /** + * Properties of a FieldDescriptorProto. + * @memberof google.protobuf + * @interface IFieldDescriptorProto + * @property {string|null} [name] FieldDescriptorProto name + * @property {number|null} [number] FieldDescriptorProto number + * @property {google.protobuf.FieldDescriptorProto.Label|null} [label] FieldDescriptorProto label + * @property {google.protobuf.FieldDescriptorProto.Type|null} [type] FieldDescriptorProto type + * @property {string|null} [typeName] FieldDescriptorProto typeName + * @property {string|null} [extendee] FieldDescriptorProto extendee + * @property {string|null} [defaultValue] FieldDescriptorProto defaultValue + * @property {number|null} [oneofIndex] FieldDescriptorProto oneofIndex + * @property {string|null} [jsonName] FieldDescriptorProto jsonName + * @property {google.protobuf.IFieldOptions|null} [options] FieldDescriptorProto options + * @property {boolean|null} [proto3Optional] FieldDescriptorProto proto3Optional + */ + + /** + * Constructs a new FieldDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a FieldDescriptorProto. + * @implements IFieldDescriptorProto + * @constructor + * @param {google.protobuf.IFieldDescriptorProto=} [properties] Properties to set + */ + function FieldDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.name = ""; + + /** + * FieldDescriptorProto number. + * @member {number} number + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.number = 0; + + /** + * FieldDescriptorProto label. + * @member {google.protobuf.FieldDescriptorProto.Label} label + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.label = 1; + + /** + * FieldDescriptorProto type. + * @member {google.protobuf.FieldDescriptorProto.Type} type + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.type = 1; + + /** + * FieldDescriptorProto typeName. + * @member {string} typeName + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.typeName = ""; + + /** + * FieldDescriptorProto extendee. + * @member {string} extendee + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.extendee = ""; + + /** + * FieldDescriptorProto defaultValue. + * @member {string} defaultValue + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.defaultValue = ""; + + /** + * FieldDescriptorProto oneofIndex. + * @member {number} oneofIndex + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.oneofIndex = 0; + + /** + * FieldDescriptorProto jsonName. + * @member {string} jsonName + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.jsonName = ""; + + /** + * FieldDescriptorProto options. + * @member {google.protobuf.IFieldOptions|null|undefined} options + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.options = null; + + /** + * FieldDescriptorProto proto3Optional. + * @member {boolean} proto3Optional + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.proto3Optional = false; + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldDescriptorProto} FieldDescriptorProto + */ + FieldDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldDescriptorProto) + return object; + var message = new $root.google.protobuf.FieldDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.number != null) + message.number = object.number | 0; + switch (object.label) { + default: + if (typeof object.label === "number") { + message.label = object.label; + break; + } + break; + case "LABEL_OPTIONAL": + case 1: + message.label = 1; + break; + case "LABEL_REPEATED": + case 3: + message.label = 3; + break; + case "LABEL_REQUIRED": + case 2: + message.label = 2; + break; + } + switch (object.type) { + default: + if (typeof object.type === "number") { + message.type = object.type; + break; + } + break; + case "TYPE_DOUBLE": + case 1: + message.type = 1; + break; + case "TYPE_FLOAT": + case 2: + message.type = 2; + break; + case "TYPE_INT64": + case 3: + message.type = 3; + break; + case "TYPE_UINT64": + case 4: + message.type = 4; + break; + case "TYPE_INT32": + case 5: + message.type = 5; + break; + case "TYPE_FIXED64": + case 6: + message.type = 6; + break; + case "TYPE_FIXED32": + case 7: + message.type = 7; + break; + case "TYPE_BOOL": + case 8: + message.type = 8; + break; + case "TYPE_STRING": + case 9: + message.type = 9; + break; + case "TYPE_GROUP": + case 10: + message.type = 10; + break; + case "TYPE_MESSAGE": + case 11: + message.type = 11; + break; + case "TYPE_BYTES": + case 12: + message.type = 12; + break; + case "TYPE_UINT32": + case 13: + message.type = 13; + break; + case "TYPE_ENUM": + case 14: + message.type = 14; + break; + case "TYPE_SFIXED32": + case 15: + message.type = 15; + break; + case "TYPE_SFIXED64": + case 16: + message.type = 16; + break; + case "TYPE_SINT32": + case 17: + message.type = 17; + break; + case "TYPE_SINT64": + case 18: + message.type = 18; + break; + } + if (object.typeName != null) + message.typeName = String(object.typeName); + if (object.extendee != null) + message.extendee = String(object.extendee); + if (object.defaultValue != null) + message.defaultValue = String(object.defaultValue); + if (object.oneofIndex != null) + message.oneofIndex = object.oneofIndex | 0; + if (object.jsonName != null) + message.jsonName = String(object.jsonName); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.FieldDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.FieldOptions.fromObject(object.options); + } + if (object.proto3Optional != null) + message.proto3Optional = Boolean(object.proto3Optional); + return message; + }; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {google.protobuf.FieldDescriptorProto} message FieldDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.extendee = ""; + object.number = 0; + object.label = options.enums === String ? "LABEL_OPTIONAL" : 1; + object.type = options.enums === String ? "TYPE_DOUBLE" : 1; + object.typeName = ""; + object.defaultValue = ""; + object.options = null; + object.oneofIndex = 0; + object.jsonName = ""; + object.proto3Optional = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.extendee != null && message.hasOwnProperty("extendee")) + object.extendee = message.extendee; + if (message.number != null && message.hasOwnProperty("number")) + object.number = message.number; + if (message.label != null && message.hasOwnProperty("label")) + object.label = options.enums === String ? $root.google.protobuf.FieldDescriptorProto.Label[message.label] === undefined ? message.label : $root.google.protobuf.FieldDescriptorProto.Label[message.label] : message.label; + if (message.type != null && message.hasOwnProperty("type")) + object.type = options.enums === String ? $root.google.protobuf.FieldDescriptorProto.Type[message.type] === undefined ? message.type : $root.google.protobuf.FieldDescriptorProto.Type[message.type] : message.type; + if (message.typeName != null && message.hasOwnProperty("typeName")) + object.typeName = message.typeName; + if (message.defaultValue != null && message.hasOwnProperty("defaultValue")) + object.defaultValue = message.defaultValue; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.FieldOptions.toObject(message.options, options); + if (message.oneofIndex != null && message.hasOwnProperty("oneofIndex")) + object.oneofIndex = message.oneofIndex; + if (message.jsonName != null && message.hasOwnProperty("jsonName")) + object.jsonName = message.jsonName; + if (message.proto3Optional != null && message.hasOwnProperty("proto3Optional")) + object.proto3Optional = message.proto3Optional; + return object; + }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.FieldDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + FieldDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldDescriptorProto"; + }; + + /** + * Type enum. + * @name google.protobuf.FieldDescriptorProto.Type + * @enum {string} + * @property {string} TYPE_DOUBLE=TYPE_DOUBLE TYPE_DOUBLE value + * @property {string} TYPE_FLOAT=TYPE_FLOAT TYPE_FLOAT value + * @property {string} TYPE_INT64=TYPE_INT64 TYPE_INT64 value + * @property {string} TYPE_UINT64=TYPE_UINT64 TYPE_UINT64 value + * @property {string} TYPE_INT32=TYPE_INT32 TYPE_INT32 value + * @property {string} TYPE_FIXED64=TYPE_FIXED64 TYPE_FIXED64 value + * @property {string} TYPE_FIXED32=TYPE_FIXED32 TYPE_FIXED32 value + * @property {string} TYPE_BOOL=TYPE_BOOL TYPE_BOOL value + * @property {string} TYPE_STRING=TYPE_STRING TYPE_STRING value + * @property {string} TYPE_GROUP=TYPE_GROUP TYPE_GROUP value + * @property {string} TYPE_MESSAGE=TYPE_MESSAGE TYPE_MESSAGE value + * @property {string} TYPE_BYTES=TYPE_BYTES TYPE_BYTES value + * @property {string} TYPE_UINT32=TYPE_UINT32 TYPE_UINT32 value + * @property {string} TYPE_ENUM=TYPE_ENUM TYPE_ENUM value + * @property {string} TYPE_SFIXED32=TYPE_SFIXED32 TYPE_SFIXED32 value + * @property {string} TYPE_SFIXED64=TYPE_SFIXED64 TYPE_SFIXED64 value + * @property {string} TYPE_SINT32=TYPE_SINT32 TYPE_SINT32 value + * @property {string} TYPE_SINT64=TYPE_SINT64 TYPE_SINT64 value + */ + FieldDescriptorProto.Type = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[1] = "TYPE_DOUBLE"] = "TYPE_DOUBLE"; + values[valuesById[2] = "TYPE_FLOAT"] = "TYPE_FLOAT"; + values[valuesById[3] = "TYPE_INT64"] = "TYPE_INT64"; + values[valuesById[4] = "TYPE_UINT64"] = "TYPE_UINT64"; + values[valuesById[5] = "TYPE_INT32"] = "TYPE_INT32"; + values[valuesById[6] = "TYPE_FIXED64"] = "TYPE_FIXED64"; + values[valuesById[7] = "TYPE_FIXED32"] = "TYPE_FIXED32"; + values[valuesById[8] = "TYPE_BOOL"] = "TYPE_BOOL"; + values[valuesById[9] = "TYPE_STRING"] = "TYPE_STRING"; + values[valuesById[10] = "TYPE_GROUP"] = "TYPE_GROUP"; + values[valuesById[11] = "TYPE_MESSAGE"] = "TYPE_MESSAGE"; + values[valuesById[12] = "TYPE_BYTES"] = "TYPE_BYTES"; + values[valuesById[13] = "TYPE_UINT32"] = "TYPE_UINT32"; + values[valuesById[14] = "TYPE_ENUM"] = "TYPE_ENUM"; + values[valuesById[15] = "TYPE_SFIXED32"] = "TYPE_SFIXED32"; + values[valuesById[16] = "TYPE_SFIXED64"] = "TYPE_SFIXED64"; + values[valuesById[17] = "TYPE_SINT32"] = "TYPE_SINT32"; + values[valuesById[18] = "TYPE_SINT64"] = "TYPE_SINT64"; + return values; + })(); + + /** + * Label enum. + * @name google.protobuf.FieldDescriptorProto.Label + * @enum {string} + * @property {string} LABEL_OPTIONAL=LABEL_OPTIONAL LABEL_OPTIONAL value + * @property {string} LABEL_REPEATED=LABEL_REPEATED LABEL_REPEATED value + * @property {string} LABEL_REQUIRED=LABEL_REQUIRED LABEL_REQUIRED value + */ + FieldDescriptorProto.Label = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[1] = "LABEL_OPTIONAL"] = "LABEL_OPTIONAL"; + values[valuesById[3] = "LABEL_REPEATED"] = "LABEL_REPEATED"; + values[valuesById[2] = "LABEL_REQUIRED"] = "LABEL_REQUIRED"; + return values; + })(); + + return FieldDescriptorProto; + })(); + + protobuf.OneofDescriptorProto = (function() { + + /** + * Properties of an OneofDescriptorProto. + * @memberof google.protobuf + * @interface IOneofDescriptorProto + * @property {string|null} [name] OneofDescriptorProto name + * @property {google.protobuf.IOneofOptions|null} [options] OneofDescriptorProto options + */ + + /** + * Constructs a new OneofDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents an OneofDescriptorProto. + * @implements IOneofDescriptorProto + * @constructor + * @param {google.protobuf.IOneofDescriptorProto=} [properties] Properties to set + */ + function OneofDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OneofDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.OneofDescriptorProto + * @instance + */ + OneofDescriptorProto.prototype.name = ""; + + /** + * OneofDescriptorProto options. + * @member {google.protobuf.IOneofOptions|null|undefined} options + * @memberof google.protobuf.OneofDescriptorProto + * @instance + */ + OneofDescriptorProto.prototype.options = null; + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.OneofDescriptorProto} OneofDescriptorProto + */ + OneofDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.OneofDescriptorProto) + return object; + var message = new $root.google.protobuf.OneofDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.OneofDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.OneofOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {google.protobuf.OneofDescriptorProto} message OneofDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OneofDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.OneofOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.OneofDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + OneofDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OneofDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OneofDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.OneofDescriptorProto"; + }; + + return OneofDescriptorProto; + })(); + + protobuf.EnumDescriptorProto = (function() { + + /** + * Properties of an EnumDescriptorProto. + * @memberof google.protobuf + * @interface IEnumDescriptorProto + * @property {string|null} [name] EnumDescriptorProto name + * @property {Array.|null} [value] EnumDescriptorProto value + * @property {google.protobuf.IEnumOptions|null} [options] EnumDescriptorProto options + * @property {Array.|null} [reservedRange] EnumDescriptorProto reservedRange + * @property {Array.|null} [reservedName] EnumDescriptorProto reservedName + */ + + /** + * Constructs a new EnumDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents an EnumDescriptorProto. + * @implements IEnumDescriptorProto + * @constructor + * @param {google.protobuf.IEnumDescriptorProto=} [properties] Properties to set + */ + function EnumDescriptorProto(properties) { + this.value = []; + this.reservedRange = []; + this.reservedName = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.name = ""; + + /** + * EnumDescriptorProto value. + * @member {Array.} value + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.value = $util.emptyArray; + + /** + * EnumDescriptorProto options. + * @member {google.protobuf.IEnumOptions|null|undefined} options + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.options = null; + + /** + * EnumDescriptorProto reservedRange. + * @member {Array.} reservedRange + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.reservedRange = $util.emptyArray; + + /** + * EnumDescriptorProto reservedName. + * @member {Array.} reservedName + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.reservedName = $util.emptyArray; + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumDescriptorProto} EnumDescriptorProto + */ + EnumDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumDescriptorProto) + return object; + var message = new $root.google.protobuf.EnumDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.value) { + if (!Array.isArray(object.value)) + throw TypeError(".google.protobuf.EnumDescriptorProto.value: array expected"); + message.value = []; + for (var i = 0; i < object.value.length; ++i) { + if (typeof object.value[i] !== "object") + throw TypeError(".google.protobuf.EnumDescriptorProto.value: object expected"); + message.value[i] = $root.google.protobuf.EnumValueDescriptorProto.fromObject(object.value[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.EnumDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.EnumOptions.fromObject(object.options); + } + if (object.reservedRange) { + if (!Array.isArray(object.reservedRange)) + throw TypeError(".google.protobuf.EnumDescriptorProto.reservedRange: array expected"); + message.reservedRange = []; + for (var i = 0; i < object.reservedRange.length; ++i) { + if (typeof object.reservedRange[i] !== "object") + throw TypeError(".google.protobuf.EnumDescriptorProto.reservedRange: object expected"); + message.reservedRange[i] = $root.google.protobuf.EnumDescriptorProto.EnumReservedRange.fromObject(object.reservedRange[i]); + } + } + if (object.reservedName) { + if (!Array.isArray(object.reservedName)) + throw TypeError(".google.protobuf.EnumDescriptorProto.reservedName: array expected"); + message.reservedName = []; + for (var i = 0; i < object.reservedName.length; ++i) + message.reservedName[i] = String(object.reservedName[i]); + } + return message; + }; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {google.protobuf.EnumDescriptorProto} message EnumDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.value = []; + object.reservedRange = []; + object.reservedName = []; + } + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.value && message.value.length) { + object.value = []; + for (var j = 0; j < message.value.length; ++j) + object.value[j] = $root.google.protobuf.EnumValueDescriptorProto.toObject(message.value[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.EnumOptions.toObject(message.options, options); + if (message.reservedRange && message.reservedRange.length) { + object.reservedRange = []; + for (var j = 0; j < message.reservedRange.length; ++j) + object.reservedRange[j] = $root.google.protobuf.EnumDescriptorProto.EnumReservedRange.toObject(message.reservedRange[j], options); + } + if (message.reservedName && message.reservedName.length) { + object.reservedName = []; + for (var j = 0; j < message.reservedName.length; ++j) + object.reservedName[j] = message.reservedName[j]; + } + return object; + }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.EnumDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + EnumDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumDescriptorProto"; + }; + + EnumDescriptorProto.EnumReservedRange = (function() { + + /** + * Properties of an EnumReservedRange. + * @memberof google.protobuf.EnumDescriptorProto + * @interface IEnumReservedRange + * @property {number|null} [start] EnumReservedRange start + * @property {number|null} [end] EnumReservedRange end + */ + + /** + * Constructs a new EnumReservedRange. + * @memberof google.protobuf.EnumDescriptorProto + * @classdesc Represents an EnumReservedRange. + * @implements IEnumReservedRange + * @constructor + * @param {google.protobuf.EnumDescriptorProto.IEnumReservedRange=} [properties] Properties to set + */ + function EnumReservedRange(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumReservedRange start. + * @member {number} start + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @instance + */ + EnumReservedRange.prototype.start = 0; + + /** + * EnumReservedRange end. + * @member {number} end + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @instance + */ + EnumReservedRange.prototype.end = 0; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumDescriptorProto.EnumReservedRange} EnumReservedRange + */ + EnumReservedRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumDescriptorProto.EnumReservedRange) + return object; + var message = new $root.google.protobuf.EnumDescriptorProto.EnumReservedRange(); + if (object.start != null) + message.start = object.start | 0; + if (object.end != null) + message.end = object.end | 0; + return message; + }; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {google.protobuf.EnumDescriptorProto.EnumReservedRange} message EnumReservedRange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumReservedRange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.start = 0; + object.end = 0; + } + if (message.start != null && message.hasOwnProperty("start")) + object.start = message.start; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + return object; + }; + + /** + * Converts this EnumReservedRange to JSON. + * @function toJSON + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @instance + * @returns {Object.} JSON object + */ + EnumReservedRange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumReservedRange + * @function getTypeUrl + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumReservedRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumDescriptorProto.EnumReservedRange"; + }; + + return EnumReservedRange; + })(); + + return EnumDescriptorProto; + })(); + + protobuf.EnumValueDescriptorProto = (function() { + + /** + * Properties of an EnumValueDescriptorProto. + * @memberof google.protobuf + * @interface IEnumValueDescriptorProto + * @property {string|null} [name] EnumValueDescriptorProto name + * @property {number|null} [number] EnumValueDescriptorProto number + * @property {google.protobuf.IEnumValueOptions|null} [options] EnumValueDescriptorProto options + */ + + /** + * Constructs a new EnumValueDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents an EnumValueDescriptorProto. + * @implements IEnumValueDescriptorProto + * @constructor + * @param {google.protobuf.IEnumValueDescriptorProto=} [properties] Properties to set + */ + function EnumValueDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumValueDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + */ + EnumValueDescriptorProto.prototype.name = ""; + + /** + * EnumValueDescriptorProto number. + * @member {number} number + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + */ + EnumValueDescriptorProto.prototype.number = 0; + + /** + * EnumValueDescriptorProto options. + * @member {google.protobuf.IEnumValueOptions|null|undefined} options + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + */ + EnumValueDescriptorProto.prototype.options = null; + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumValueDescriptorProto} EnumValueDescriptorProto + */ + EnumValueDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumValueDescriptorProto) + return object; + var message = new $root.google.protobuf.EnumValueDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.number != null) + message.number = object.number | 0; + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.EnumValueDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.EnumValueOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {google.protobuf.EnumValueDescriptorProto} message EnumValueDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumValueDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.number = 0; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.number != null && message.hasOwnProperty("number")) + object.number = message.number; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.EnumValueOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + EnumValueDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumValueDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumValueDescriptorProto"; + }; + + return EnumValueDescriptorProto; + })(); + + protobuf.ServiceDescriptorProto = (function() { + + /** + * Properties of a ServiceDescriptorProto. + * @memberof google.protobuf + * @interface IServiceDescriptorProto + * @property {string|null} [name] ServiceDescriptorProto name + * @property {Array.|null} [method] ServiceDescriptorProto method + * @property {google.protobuf.IServiceOptions|null} [options] ServiceDescriptorProto options + */ + + /** + * Constructs a new ServiceDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a ServiceDescriptorProto. + * @implements IServiceDescriptorProto + * @constructor + * @param {google.protobuf.IServiceDescriptorProto=} [properties] Properties to set + */ + function ServiceDescriptorProto(properties) { + this.method = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ServiceDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + */ + ServiceDescriptorProto.prototype.name = ""; + + /** + * ServiceDescriptorProto method. + * @member {Array.} method + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + */ + ServiceDescriptorProto.prototype.method = $util.emptyArray; + + /** + * ServiceDescriptorProto options. + * @member {google.protobuf.IServiceOptions|null|undefined} options + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + */ + ServiceDescriptorProto.prototype.options = null; + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ServiceDescriptorProto} ServiceDescriptorProto + */ + ServiceDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ServiceDescriptorProto) + return object; + var message = new $root.google.protobuf.ServiceDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.method) { + if (!Array.isArray(object.method)) + throw TypeError(".google.protobuf.ServiceDescriptorProto.method: array expected"); + message.method = []; + for (var i = 0; i < object.method.length; ++i) { + if (typeof object.method[i] !== "object") + throw TypeError(".google.protobuf.ServiceDescriptorProto.method: object expected"); + message.method[i] = $root.google.protobuf.MethodDescriptorProto.fromObject(object.method[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.ServiceDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.ServiceOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {google.protobuf.ServiceDescriptorProto} message ServiceDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ServiceDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.method = []; + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.method && message.method.length) { + object.method = []; + for (var j = 0; j < message.method.length; ++j) + object.method[j] = $root.google.protobuf.MethodDescriptorProto.toObject(message.method[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.ServiceOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + ServiceDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ServiceDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ServiceDescriptorProto"; + }; + + return ServiceDescriptorProto; + })(); + + protobuf.MethodDescriptorProto = (function() { + + /** + * Properties of a MethodDescriptorProto. + * @memberof google.protobuf + * @interface IMethodDescriptorProto + * @property {string|null} [name] MethodDescriptorProto name + * @property {string|null} [inputType] MethodDescriptorProto inputType + * @property {string|null} [outputType] MethodDescriptorProto outputType + * @property {google.protobuf.IMethodOptions|null} [options] MethodDescriptorProto options + * @property {boolean|null} [clientStreaming] MethodDescriptorProto clientStreaming + * @property {boolean|null} [serverStreaming] MethodDescriptorProto serverStreaming + */ + + /** + * Constructs a new MethodDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a MethodDescriptorProto. + * @implements IMethodDescriptorProto + * @constructor + * @param {google.protobuf.IMethodDescriptorProto=} [properties] Properties to set + */ + function MethodDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MethodDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.name = ""; + + /** + * MethodDescriptorProto inputType. + * @member {string} inputType + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.inputType = ""; + + /** + * MethodDescriptorProto outputType. + * @member {string} outputType + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.outputType = ""; + + /** + * MethodDescriptorProto options. + * @member {google.protobuf.IMethodOptions|null|undefined} options + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.options = null; + + /** + * MethodDescriptorProto clientStreaming. + * @member {boolean} clientStreaming + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.clientStreaming = false; + + /** + * MethodDescriptorProto serverStreaming. + * @member {boolean} serverStreaming + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.serverStreaming = false; + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.MethodDescriptorProto} MethodDescriptorProto + */ + MethodDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.MethodDescriptorProto) + return object; + var message = new $root.google.protobuf.MethodDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.inputType != null) + message.inputType = String(object.inputType); + if (object.outputType != null) + message.outputType = String(object.outputType); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.MethodDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.MethodOptions.fromObject(object.options); + } + if (object.clientStreaming != null) + message.clientStreaming = Boolean(object.clientStreaming); + if (object.serverStreaming != null) + message.serverStreaming = Boolean(object.serverStreaming); + return message; + }; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {google.protobuf.MethodDescriptorProto} message MethodDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MethodDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.inputType = ""; + object.outputType = ""; + object.options = null; + object.clientStreaming = false; + object.serverStreaming = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.inputType != null && message.hasOwnProperty("inputType")) + object.inputType = message.inputType; + if (message.outputType != null && message.hasOwnProperty("outputType")) + object.outputType = message.outputType; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.MethodOptions.toObject(message.options, options); + if (message.clientStreaming != null && message.hasOwnProperty("clientStreaming")) + object.clientStreaming = message.clientStreaming; + if (message.serverStreaming != null && message.hasOwnProperty("serverStreaming")) + object.serverStreaming = message.serverStreaming; + return object; + }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.MethodDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + MethodDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MethodDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MethodDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.MethodDescriptorProto"; + }; + + return MethodDescriptorProto; + })(); + + protobuf.FileOptions = (function() { + + /** + * Properties of a FileOptions. + * @memberof google.protobuf + * @interface IFileOptions + * @property {string|null} [javaPackage] FileOptions javaPackage + * @property {string|null} [javaOuterClassname] FileOptions javaOuterClassname + * @property {boolean|null} [javaMultipleFiles] FileOptions javaMultipleFiles + * @property {boolean|null} [javaGenerateEqualsAndHash] FileOptions javaGenerateEqualsAndHash + * @property {boolean|null} [javaStringCheckUtf8] FileOptions javaStringCheckUtf8 + * @property {google.protobuf.FileOptions.OptimizeMode|null} [optimizeFor] FileOptions optimizeFor + * @property {string|null} [goPackage] FileOptions goPackage + * @property {boolean|null} [ccGenericServices] FileOptions ccGenericServices + * @property {boolean|null} [javaGenericServices] FileOptions javaGenericServices + * @property {boolean|null} [pyGenericServices] FileOptions pyGenericServices + * @property {boolean|null} [deprecated] FileOptions deprecated + * @property {boolean|null} [ccEnableArenas] FileOptions ccEnableArenas + * @property {string|null} [objcClassPrefix] FileOptions objcClassPrefix + * @property {string|null} [csharpNamespace] FileOptions csharpNamespace + * @property {string|null} [swiftPrefix] FileOptions swiftPrefix + * @property {string|null} [phpClassPrefix] FileOptions phpClassPrefix + * @property {string|null} [phpNamespace] FileOptions phpNamespace + * @property {string|null} [phpMetadataNamespace] FileOptions phpMetadataNamespace + * @property {string|null} [rubyPackage] FileOptions rubyPackage + * @property {google.protobuf.IFeatureSet|null} [features] FileOptions features + * @property {Array.|null} [uninterpretedOption] FileOptions uninterpretedOption + * @property {Array.|null} [".google.api.resourceDefinition"] FileOptions .google.api.resourceDefinition + */ + + /** + * Constructs a new FileOptions. + * @memberof google.protobuf + * @classdesc Represents a FileOptions. + * @implements IFileOptions + * @constructor + * @param {google.protobuf.IFileOptions=} [properties] Properties to set + */ + function FileOptions(properties) { + this.uninterpretedOption = []; + this[".google.api.resourceDefinition"] = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FileOptions javaPackage. + * @member {string} javaPackage + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaPackage = ""; + + /** + * FileOptions javaOuterClassname. + * @member {string} javaOuterClassname + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaOuterClassname = ""; + + /** + * FileOptions javaMultipleFiles. + * @member {boolean} javaMultipleFiles + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaMultipleFiles = false; + + /** + * FileOptions javaGenerateEqualsAndHash. + * @member {boolean} javaGenerateEqualsAndHash + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaGenerateEqualsAndHash = false; + + /** + * FileOptions javaStringCheckUtf8. + * @member {boolean} javaStringCheckUtf8 + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaStringCheckUtf8 = false; + + /** + * FileOptions optimizeFor. + * @member {google.protobuf.FileOptions.OptimizeMode} optimizeFor + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.optimizeFor = 1; + + /** + * FileOptions goPackage. + * @member {string} goPackage + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.goPackage = ""; + + /** + * FileOptions ccGenericServices. + * @member {boolean} ccGenericServices + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.ccGenericServices = false; + + /** + * FileOptions javaGenericServices. + * @member {boolean} javaGenericServices + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaGenericServices = false; + + /** + * FileOptions pyGenericServices. + * @member {boolean} pyGenericServices + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.pyGenericServices = false; + + /** + * FileOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.deprecated = false; + + /** + * FileOptions ccEnableArenas. + * @member {boolean} ccEnableArenas + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.ccEnableArenas = true; + + /** + * FileOptions objcClassPrefix. + * @member {string} objcClassPrefix + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.objcClassPrefix = ""; + + /** + * FileOptions csharpNamespace. + * @member {string} csharpNamespace + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.csharpNamespace = ""; + + /** + * FileOptions swiftPrefix. + * @member {string} swiftPrefix + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.swiftPrefix = ""; + + /** + * FileOptions phpClassPrefix. + * @member {string} phpClassPrefix + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.phpClassPrefix = ""; + + /** + * FileOptions phpNamespace. + * @member {string} phpNamespace + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.phpNamespace = ""; + + /** + * FileOptions phpMetadataNamespace. + * @member {string} phpMetadataNamespace + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.phpMetadataNamespace = ""; + + /** + * FileOptions rubyPackage. + * @member {string} rubyPackage + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.rubyPackage = ""; + + /** + * FileOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.features = null; + + /** + * FileOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * FileOptions .google.api.resourceDefinition. + * @member {Array.} .google.api.resourceDefinition + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype[".google.api.resourceDefinition"] = $util.emptyArray; + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FileOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FileOptions} FileOptions + */ + FileOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FileOptions) + return object; + var message = new $root.google.protobuf.FileOptions(); + if (object.javaPackage != null) + message.javaPackage = String(object.javaPackage); + if (object.javaOuterClassname != null) + message.javaOuterClassname = String(object.javaOuterClassname); + if (object.javaMultipleFiles != null) + message.javaMultipleFiles = Boolean(object.javaMultipleFiles); + if (object.javaGenerateEqualsAndHash != null) + message.javaGenerateEqualsAndHash = Boolean(object.javaGenerateEqualsAndHash); + if (object.javaStringCheckUtf8 != null) + message.javaStringCheckUtf8 = Boolean(object.javaStringCheckUtf8); + switch (object.optimizeFor) { + default: + if (typeof object.optimizeFor === "number") { + message.optimizeFor = object.optimizeFor; + break; + } + break; + case "SPEED": + case 1: + message.optimizeFor = 1; + break; + case "CODE_SIZE": + case 2: + message.optimizeFor = 2; + break; + case "LITE_RUNTIME": + case 3: + message.optimizeFor = 3; + break; + } + if (object.goPackage != null) + message.goPackage = String(object.goPackage); + if (object.ccGenericServices != null) + message.ccGenericServices = Boolean(object.ccGenericServices); + if (object.javaGenericServices != null) + message.javaGenericServices = Boolean(object.javaGenericServices); + if (object.pyGenericServices != null) + message.pyGenericServices = Boolean(object.pyGenericServices); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.ccEnableArenas != null) + message.ccEnableArenas = Boolean(object.ccEnableArenas); + if (object.objcClassPrefix != null) + message.objcClassPrefix = String(object.objcClassPrefix); + if (object.csharpNamespace != null) + message.csharpNamespace = String(object.csharpNamespace); + if (object.swiftPrefix != null) + message.swiftPrefix = String(object.swiftPrefix); + if (object.phpClassPrefix != null) + message.phpClassPrefix = String(object.phpClassPrefix); + if (object.phpNamespace != null) + message.phpNamespace = String(object.phpNamespace); + if (object.phpMetadataNamespace != null) + message.phpMetadataNamespace = String(object.phpMetadataNamespace); + if (object.rubyPackage != null) + message.rubyPackage = String(object.rubyPackage); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.FileOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.FileOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.FileOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.resourceDefinition"]) { + if (!Array.isArray(object[".google.api.resourceDefinition"])) + throw TypeError(".google.protobuf.FileOptions..google.api.resourceDefinition: array expected"); + message[".google.api.resourceDefinition"] = []; + for (var i = 0; i < object[".google.api.resourceDefinition"].length; ++i) { + if (typeof object[".google.api.resourceDefinition"][i] !== "object") + throw TypeError(".google.protobuf.FileOptions..google.api.resourceDefinition: object expected"); + message[".google.api.resourceDefinition"][i] = $root.google.api.ResourceDescriptor.fromObject(object[".google.api.resourceDefinition"][i]); + } + } + return message; + }; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FileOptions + * @static + * @param {google.protobuf.FileOptions} message FileOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FileOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.uninterpretedOption = []; + object[".google.api.resourceDefinition"] = []; + } + if (options.defaults) { + object.javaPackage = ""; + object.javaOuterClassname = ""; + object.optimizeFor = options.enums === String ? "SPEED" : 1; + object.javaMultipleFiles = false; + object.goPackage = ""; + object.ccGenericServices = false; + object.javaGenericServices = false; + object.pyGenericServices = false; + object.javaGenerateEqualsAndHash = false; + object.deprecated = false; + object.javaStringCheckUtf8 = false; + object.ccEnableArenas = true; + object.objcClassPrefix = ""; + object.csharpNamespace = ""; + object.swiftPrefix = ""; + object.phpClassPrefix = ""; + object.phpNamespace = ""; + object.phpMetadataNamespace = ""; + object.rubyPackage = ""; + object.features = null; + } + if (message.javaPackage != null && message.hasOwnProperty("javaPackage")) + object.javaPackage = message.javaPackage; + if (message.javaOuterClassname != null && message.hasOwnProperty("javaOuterClassname")) + object.javaOuterClassname = message.javaOuterClassname; + if (message.optimizeFor != null && message.hasOwnProperty("optimizeFor")) + object.optimizeFor = options.enums === String ? $root.google.protobuf.FileOptions.OptimizeMode[message.optimizeFor] === undefined ? message.optimizeFor : $root.google.protobuf.FileOptions.OptimizeMode[message.optimizeFor] : message.optimizeFor; + if (message.javaMultipleFiles != null && message.hasOwnProperty("javaMultipleFiles")) + object.javaMultipleFiles = message.javaMultipleFiles; + if (message.goPackage != null && message.hasOwnProperty("goPackage")) + object.goPackage = message.goPackage; + if (message.ccGenericServices != null && message.hasOwnProperty("ccGenericServices")) + object.ccGenericServices = message.ccGenericServices; + if (message.javaGenericServices != null && message.hasOwnProperty("javaGenericServices")) + object.javaGenericServices = message.javaGenericServices; + if (message.pyGenericServices != null && message.hasOwnProperty("pyGenericServices")) + object.pyGenericServices = message.pyGenericServices; + if (message.javaGenerateEqualsAndHash != null && message.hasOwnProperty("javaGenerateEqualsAndHash")) + object.javaGenerateEqualsAndHash = message.javaGenerateEqualsAndHash; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.javaStringCheckUtf8 != null && message.hasOwnProperty("javaStringCheckUtf8")) + object.javaStringCheckUtf8 = message.javaStringCheckUtf8; + if (message.ccEnableArenas != null && message.hasOwnProperty("ccEnableArenas")) + object.ccEnableArenas = message.ccEnableArenas; + if (message.objcClassPrefix != null && message.hasOwnProperty("objcClassPrefix")) + object.objcClassPrefix = message.objcClassPrefix; + if (message.csharpNamespace != null && message.hasOwnProperty("csharpNamespace")) + object.csharpNamespace = message.csharpNamespace; + if (message.swiftPrefix != null && message.hasOwnProperty("swiftPrefix")) + object.swiftPrefix = message.swiftPrefix; + if (message.phpClassPrefix != null && message.hasOwnProperty("phpClassPrefix")) + object.phpClassPrefix = message.phpClassPrefix; + if (message.phpNamespace != null && message.hasOwnProperty("phpNamespace")) + object.phpNamespace = message.phpNamespace; + if (message.phpMetadataNamespace != null && message.hasOwnProperty("phpMetadataNamespace")) + object.phpMetadataNamespace = message.phpMetadataNamespace; + if (message.rubyPackage != null && message.hasOwnProperty("rubyPackage")) + object.rubyPackage = message.rubyPackage; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.resourceDefinition"] && message[".google.api.resourceDefinition"].length) { + object[".google.api.resourceDefinition"] = []; + for (var j = 0; j < message[".google.api.resourceDefinition"].length; ++j) + object[".google.api.resourceDefinition"][j] = $root.google.api.ResourceDescriptor.toObject(message[".google.api.resourceDefinition"][j], options); + } + return object; + }; + + /** + * Converts this FileOptions to JSON. + * @function toJSON + * @memberof google.protobuf.FileOptions + * @instance + * @returns {Object.} JSON object + */ + FileOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FileOptions + * @function getTypeUrl + * @memberof google.protobuf.FileOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FileOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FileOptions"; + }; + + /** + * OptimizeMode enum. + * @name google.protobuf.FileOptions.OptimizeMode + * @enum {string} + * @property {string} SPEED=SPEED SPEED value + * @property {string} CODE_SIZE=CODE_SIZE CODE_SIZE value + * @property {string} LITE_RUNTIME=LITE_RUNTIME LITE_RUNTIME value + */ + FileOptions.OptimizeMode = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[1] = "SPEED"] = "SPEED"; + values[valuesById[2] = "CODE_SIZE"] = "CODE_SIZE"; + values[valuesById[3] = "LITE_RUNTIME"] = "LITE_RUNTIME"; + return values; + })(); + + return FileOptions; + })(); + + protobuf.MessageOptions = (function() { + + /** + * Properties of a MessageOptions. + * @memberof google.protobuf + * @interface IMessageOptions + * @property {boolean|null} [messageSetWireFormat] MessageOptions messageSetWireFormat + * @property {boolean|null} [noStandardDescriptorAccessor] MessageOptions noStandardDescriptorAccessor + * @property {boolean|null} [deprecated] MessageOptions deprecated + * @property {boolean|null} [mapEntry] MessageOptions mapEntry + * @property {boolean|null} [deprecatedLegacyJsonFieldConflicts] MessageOptions deprecatedLegacyJsonFieldConflicts + * @property {google.protobuf.IFeatureSet|null} [features] MessageOptions features + * @property {Array.|null} [uninterpretedOption] MessageOptions uninterpretedOption + * @property {google.api.IResourceDescriptor|null} [".google.api.resource"] MessageOptions .google.api.resource + */ + + /** + * Constructs a new MessageOptions. + * @memberof google.protobuf + * @classdesc Represents a MessageOptions. + * @implements IMessageOptions + * @constructor + * @param {google.protobuf.IMessageOptions=} [properties] Properties to set + */ + function MessageOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MessageOptions messageSetWireFormat. + * @member {boolean} messageSetWireFormat + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.messageSetWireFormat = false; + + /** + * MessageOptions noStandardDescriptorAccessor. + * @member {boolean} noStandardDescriptorAccessor + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.noStandardDescriptorAccessor = false; + + /** + * MessageOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.deprecated = false; + + /** + * MessageOptions mapEntry. + * @member {boolean} mapEntry + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.mapEntry = false; + + /** + * MessageOptions deprecatedLegacyJsonFieldConflicts. + * @member {boolean} deprecatedLegacyJsonFieldConflicts + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.deprecatedLegacyJsonFieldConflicts = false; + + /** + * MessageOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.features = null; + + /** + * MessageOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * MessageOptions .google.api.resource. + * @member {google.api.IResourceDescriptor|null|undefined} .google.api.resource + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype[".google.api.resource"] = null; + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.MessageOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.MessageOptions} MessageOptions + */ + MessageOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.MessageOptions) + return object; + var message = new $root.google.protobuf.MessageOptions(); + if (object.messageSetWireFormat != null) + message.messageSetWireFormat = Boolean(object.messageSetWireFormat); + if (object.noStandardDescriptorAccessor != null) + message.noStandardDescriptorAccessor = Boolean(object.noStandardDescriptorAccessor); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.mapEntry != null) + message.mapEntry = Boolean(object.mapEntry); + if (object.deprecatedLegacyJsonFieldConflicts != null) + message.deprecatedLegacyJsonFieldConflicts = Boolean(object.deprecatedLegacyJsonFieldConflicts); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.MessageOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.MessageOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.MessageOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.resource"] != null) { + if (typeof object[".google.api.resource"] !== "object") + throw TypeError(".google.protobuf.MessageOptions..google.api.resource: object expected"); + message[".google.api.resource"] = $root.google.api.ResourceDescriptor.fromObject(object[".google.api.resource"]); + } + return message; + }; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.MessageOptions + * @static + * @param {google.protobuf.MessageOptions} message MessageOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MessageOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.messageSetWireFormat = false; + object.noStandardDescriptorAccessor = false; + object.deprecated = false; + object.mapEntry = false; + object.deprecatedLegacyJsonFieldConflicts = false; + object.features = null; + object[".google.api.resource"] = null; + } + if (message.messageSetWireFormat != null && message.hasOwnProperty("messageSetWireFormat")) + object.messageSetWireFormat = message.messageSetWireFormat; + if (message.noStandardDescriptorAccessor != null && message.hasOwnProperty("noStandardDescriptorAccessor")) + object.noStandardDescriptorAccessor = message.noStandardDescriptorAccessor; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.mapEntry != null && message.hasOwnProperty("mapEntry")) + object.mapEntry = message.mapEntry; + if (message.deprecatedLegacyJsonFieldConflicts != null && message.hasOwnProperty("deprecatedLegacyJsonFieldConflicts")) + object.deprecatedLegacyJsonFieldConflicts = message.deprecatedLegacyJsonFieldConflicts; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.resource"] != null && message.hasOwnProperty(".google.api.resource")) + object[".google.api.resource"] = $root.google.api.ResourceDescriptor.toObject(message[".google.api.resource"], options); + return object; + }; + + /** + * Converts this MessageOptions to JSON. + * @function toJSON + * @memberof google.protobuf.MessageOptions + * @instance + * @returns {Object.} JSON object + */ + MessageOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MessageOptions + * @function getTypeUrl + * @memberof google.protobuf.MessageOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MessageOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.MessageOptions"; + }; + + return MessageOptions; + })(); + + protobuf.FieldOptions = (function() { + + /** + * Properties of a FieldOptions. + * @memberof google.protobuf + * @interface IFieldOptions + * @property {google.protobuf.FieldOptions.CType|null} [ctype] FieldOptions ctype + * @property {boolean|null} [packed] FieldOptions packed + * @property {google.protobuf.FieldOptions.JSType|null} [jstype] FieldOptions jstype + * @property {boolean|null} [lazy] FieldOptions lazy + * @property {boolean|null} [unverifiedLazy] FieldOptions unverifiedLazy + * @property {boolean|null} [deprecated] FieldOptions deprecated + * @property {boolean|null} [weak] FieldOptions weak + * @property {boolean|null} [debugRedact] FieldOptions debugRedact + * @property {google.protobuf.FieldOptions.OptionRetention|null} [retention] FieldOptions retention + * @property {Array.|null} [targets] FieldOptions targets + * @property {Array.|null} [editionDefaults] FieldOptions editionDefaults + * @property {google.protobuf.IFeatureSet|null} [features] FieldOptions features + * @property {Array.|null} [uninterpretedOption] FieldOptions uninterpretedOption + * @property {Array.|null} [".google.api.fieldBehavior"] FieldOptions .google.api.fieldBehavior + * @property {google.api.IResourceReference|null} [".google.api.resourceReference"] FieldOptions .google.api.resourceReference + */ + + /** + * Constructs a new FieldOptions. + * @memberof google.protobuf + * @classdesc Represents a FieldOptions. + * @implements IFieldOptions + * @constructor + * @param {google.protobuf.IFieldOptions=} [properties] Properties to set + */ + function FieldOptions(properties) { + this.targets = []; + this.editionDefaults = []; + this.uninterpretedOption = []; + this[".google.api.fieldBehavior"] = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldOptions ctype. + * @member {google.protobuf.FieldOptions.CType} ctype + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.ctype = 0; + + /** + * FieldOptions packed. + * @member {boolean} packed + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.packed = false; + + /** + * FieldOptions jstype. + * @member {google.protobuf.FieldOptions.JSType} jstype + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.jstype = 0; + + /** + * FieldOptions lazy. + * @member {boolean} lazy + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.lazy = false; + + /** + * FieldOptions unverifiedLazy. + * @member {boolean} unverifiedLazy + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.unverifiedLazy = false; + + /** + * FieldOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.deprecated = false; + + /** + * FieldOptions weak. + * @member {boolean} weak + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.weak = false; + + /** + * FieldOptions debugRedact. + * @member {boolean} debugRedact + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.debugRedact = false; + + /** + * FieldOptions retention. + * @member {google.protobuf.FieldOptions.OptionRetention} retention + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.retention = 0; + + /** + * FieldOptions targets. + * @member {Array.} targets + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.targets = $util.emptyArray; + + /** + * FieldOptions editionDefaults. + * @member {Array.} editionDefaults + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.editionDefaults = $util.emptyArray; + + /** + * FieldOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.features = null; + + /** + * FieldOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * FieldOptions .google.api.fieldBehavior. + * @member {Array.} .google.api.fieldBehavior + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype[".google.api.fieldBehavior"] = $util.emptyArray; + + /** + * FieldOptions .google.api.resourceReference. + * @member {google.api.IResourceReference|null|undefined} .google.api.resourceReference + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype[".google.api.resourceReference"] = null; + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldOptions} FieldOptions + */ + FieldOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldOptions) + return object; + var message = new $root.google.protobuf.FieldOptions(); + switch (object.ctype) { + default: + if (typeof object.ctype === "number") { + message.ctype = object.ctype; + break; + } + break; + case "STRING": + case 0: + message.ctype = 0; + break; + case "CORD": + case 1: + message.ctype = 1; + break; + case "STRING_PIECE": + case 2: + message.ctype = 2; + break; + } + if (object.packed != null) + message.packed = Boolean(object.packed); + switch (object.jstype) { + default: + if (typeof object.jstype === "number") { + message.jstype = object.jstype; + break; + } + break; + case "JS_NORMAL": + case 0: + message.jstype = 0; + break; + case "JS_STRING": + case 1: + message.jstype = 1; + break; + case "JS_NUMBER": + case 2: + message.jstype = 2; + break; + } + if (object.lazy != null) + message.lazy = Boolean(object.lazy); + if (object.unverifiedLazy != null) + message.unverifiedLazy = Boolean(object.unverifiedLazy); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.weak != null) + message.weak = Boolean(object.weak); + if (object.debugRedact != null) + message.debugRedact = Boolean(object.debugRedact); + switch (object.retention) { + default: + if (typeof object.retention === "number") { + message.retention = object.retention; + break; + } + break; + case "RETENTION_UNKNOWN": + case 0: + message.retention = 0; + break; + case "RETENTION_RUNTIME": + case 1: + message.retention = 1; + break; + case "RETENTION_SOURCE": + case 2: + message.retention = 2; + break; + } + if (object.targets) { + if (!Array.isArray(object.targets)) + throw TypeError(".google.protobuf.FieldOptions.targets: array expected"); + message.targets = []; + for (var i = 0; i < object.targets.length; ++i) + switch (object.targets[i]) { + default: + if (typeof object.targets[i] === "number") { + message.targets[i] = object.targets[i]; + break; + } + case "TARGET_TYPE_UNKNOWN": + case 0: + message.targets[i] = 0; + break; + case "TARGET_TYPE_FILE": + case 1: + message.targets[i] = 1; + break; + case "TARGET_TYPE_EXTENSION_RANGE": + case 2: + message.targets[i] = 2; + break; + case "TARGET_TYPE_MESSAGE": + case 3: + message.targets[i] = 3; + break; + case "TARGET_TYPE_FIELD": + case 4: + message.targets[i] = 4; + break; + case "TARGET_TYPE_ONEOF": + case 5: + message.targets[i] = 5; + break; + case "TARGET_TYPE_ENUM": + case 6: + message.targets[i] = 6; + break; + case "TARGET_TYPE_ENUM_ENTRY": + case 7: + message.targets[i] = 7; + break; + case "TARGET_TYPE_SERVICE": + case 8: + message.targets[i] = 8; + break; + case "TARGET_TYPE_METHOD": + case 9: + message.targets[i] = 9; + break; + } + } + if (object.editionDefaults) { + if (!Array.isArray(object.editionDefaults)) + throw TypeError(".google.protobuf.FieldOptions.editionDefaults: array expected"); + message.editionDefaults = []; + for (var i = 0; i < object.editionDefaults.length; ++i) { + if (typeof object.editionDefaults[i] !== "object") + throw TypeError(".google.protobuf.FieldOptions.editionDefaults: object expected"); + message.editionDefaults[i] = $root.google.protobuf.FieldOptions.EditionDefault.fromObject(object.editionDefaults[i]); + } + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.FieldOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.FieldOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.FieldOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.fieldBehavior"]) { + if (!Array.isArray(object[".google.api.fieldBehavior"])) + throw TypeError(".google.protobuf.FieldOptions..google.api.fieldBehavior: array expected"); + message[".google.api.fieldBehavior"] = []; + for (var i = 0; i < object[".google.api.fieldBehavior"].length; ++i) + switch (object[".google.api.fieldBehavior"][i]) { + default: + if (typeof object[".google.api.fieldBehavior"][i] === "number") { + message[".google.api.fieldBehavior"][i] = object[".google.api.fieldBehavior"][i]; + break; + } + case "FIELD_BEHAVIOR_UNSPECIFIED": + case 0: + message[".google.api.fieldBehavior"][i] = 0; + break; + case "OPTIONAL": + case 1: + message[".google.api.fieldBehavior"][i] = 1; + break; + case "REQUIRED": + case 2: + message[".google.api.fieldBehavior"][i] = 2; + break; + case "OUTPUT_ONLY": + case 3: + message[".google.api.fieldBehavior"][i] = 3; + break; + case "INPUT_ONLY": + case 4: + message[".google.api.fieldBehavior"][i] = 4; + break; + case "IMMUTABLE": + case 5: + message[".google.api.fieldBehavior"][i] = 5; + break; + case "UNORDERED_LIST": + case 6: + message[".google.api.fieldBehavior"][i] = 6; + break; + case "NON_EMPTY_DEFAULT": + case 7: + message[".google.api.fieldBehavior"][i] = 7; + break; + case "IDENTIFIER": + case 8: + message[".google.api.fieldBehavior"][i] = 8; + break; + } + } + if (object[".google.api.resourceReference"] != null) { + if (typeof object[".google.api.resourceReference"] !== "object") + throw TypeError(".google.protobuf.FieldOptions..google.api.resourceReference: object expected"); + message[".google.api.resourceReference"] = $root.google.api.ResourceReference.fromObject(object[".google.api.resourceReference"]); + } + return message; + }; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldOptions + * @static + * @param {google.protobuf.FieldOptions} message FieldOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.targets = []; + object.editionDefaults = []; + object.uninterpretedOption = []; + object[".google.api.fieldBehavior"] = []; + } + if (options.defaults) { + object.ctype = options.enums === String ? "STRING" : 0; + object.packed = false; + object.deprecated = false; + object.lazy = false; + object.jstype = options.enums === String ? "JS_NORMAL" : 0; + object.weak = false; + object.unverifiedLazy = false; + object.debugRedact = false; + object.retention = options.enums === String ? "RETENTION_UNKNOWN" : 0; + object.features = null; + object[".google.api.resourceReference"] = null; + } + if (message.ctype != null && message.hasOwnProperty("ctype")) + object.ctype = options.enums === String ? $root.google.protobuf.FieldOptions.CType[message.ctype] === undefined ? message.ctype : $root.google.protobuf.FieldOptions.CType[message.ctype] : message.ctype; + if (message.packed != null && message.hasOwnProperty("packed")) + object.packed = message.packed; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.lazy != null && message.hasOwnProperty("lazy")) + object.lazy = message.lazy; + if (message.jstype != null && message.hasOwnProperty("jstype")) + object.jstype = options.enums === String ? $root.google.protobuf.FieldOptions.JSType[message.jstype] === undefined ? message.jstype : $root.google.protobuf.FieldOptions.JSType[message.jstype] : message.jstype; + if (message.weak != null && message.hasOwnProperty("weak")) + object.weak = message.weak; + if (message.unverifiedLazy != null && message.hasOwnProperty("unverifiedLazy")) + object.unverifiedLazy = message.unverifiedLazy; + if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) + object.debugRedact = message.debugRedact; + if (message.retention != null && message.hasOwnProperty("retention")) + object.retention = options.enums === String ? $root.google.protobuf.FieldOptions.OptionRetention[message.retention] === undefined ? message.retention : $root.google.protobuf.FieldOptions.OptionRetention[message.retention] : message.retention; + if (message.targets && message.targets.length) { + object.targets = []; + for (var j = 0; j < message.targets.length; ++j) + object.targets[j] = options.enums === String ? $root.google.protobuf.FieldOptions.OptionTargetType[message.targets[j]] === undefined ? message.targets[j] : $root.google.protobuf.FieldOptions.OptionTargetType[message.targets[j]] : message.targets[j]; + } + if (message.editionDefaults && message.editionDefaults.length) { + object.editionDefaults = []; + for (var j = 0; j < message.editionDefaults.length; ++j) + object.editionDefaults[j] = $root.google.protobuf.FieldOptions.EditionDefault.toObject(message.editionDefaults[j], options); + } + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.fieldBehavior"] && message[".google.api.fieldBehavior"].length) { + object[".google.api.fieldBehavior"] = []; + for (var j = 0; j < message[".google.api.fieldBehavior"].length; ++j) + object[".google.api.fieldBehavior"][j] = options.enums === String ? $root.google.api.FieldBehavior[message[".google.api.fieldBehavior"][j]] === undefined ? message[".google.api.fieldBehavior"][j] : $root.google.api.FieldBehavior[message[".google.api.fieldBehavior"][j]] : message[".google.api.fieldBehavior"][j]; + } + if (message[".google.api.resourceReference"] != null && message.hasOwnProperty(".google.api.resourceReference")) + object[".google.api.resourceReference"] = $root.google.api.ResourceReference.toObject(message[".google.api.resourceReference"], options); + return object; + }; + + /** + * Converts this FieldOptions to JSON. + * @function toJSON + * @memberof google.protobuf.FieldOptions + * @instance + * @returns {Object.} JSON object + */ + FieldOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldOptions + * @function getTypeUrl + * @memberof google.protobuf.FieldOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldOptions"; + }; + + /** + * CType enum. + * @name google.protobuf.FieldOptions.CType + * @enum {string} + * @property {string} STRING=STRING STRING value + * @property {string} CORD=CORD CORD value + * @property {string} STRING_PIECE=STRING_PIECE STRING_PIECE value + */ + FieldOptions.CType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STRING"] = "STRING"; + values[valuesById[1] = "CORD"] = "CORD"; + values[valuesById[2] = "STRING_PIECE"] = "STRING_PIECE"; + return values; + })(); + + /** + * JSType enum. + * @name google.protobuf.FieldOptions.JSType + * @enum {string} + * @property {string} JS_NORMAL=JS_NORMAL JS_NORMAL value + * @property {string} JS_STRING=JS_STRING JS_STRING value + * @property {string} JS_NUMBER=JS_NUMBER JS_NUMBER value + */ + FieldOptions.JSType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "JS_NORMAL"] = "JS_NORMAL"; + values[valuesById[1] = "JS_STRING"] = "JS_STRING"; + values[valuesById[2] = "JS_NUMBER"] = "JS_NUMBER"; + return values; + })(); + + /** + * OptionRetention enum. + * @name google.protobuf.FieldOptions.OptionRetention + * @enum {string} + * @property {string} RETENTION_UNKNOWN=RETENTION_UNKNOWN RETENTION_UNKNOWN value + * @property {string} RETENTION_RUNTIME=RETENTION_RUNTIME RETENTION_RUNTIME value + * @property {string} RETENTION_SOURCE=RETENTION_SOURCE RETENTION_SOURCE value + */ + FieldOptions.OptionRetention = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "RETENTION_UNKNOWN"] = "RETENTION_UNKNOWN"; + values[valuesById[1] = "RETENTION_RUNTIME"] = "RETENTION_RUNTIME"; + values[valuesById[2] = "RETENTION_SOURCE"] = "RETENTION_SOURCE"; + return values; + })(); + + /** + * OptionTargetType enum. + * @name google.protobuf.FieldOptions.OptionTargetType + * @enum {string} + * @property {string} TARGET_TYPE_UNKNOWN=TARGET_TYPE_UNKNOWN TARGET_TYPE_UNKNOWN value + * @property {string} TARGET_TYPE_FILE=TARGET_TYPE_FILE TARGET_TYPE_FILE value + * @property {string} TARGET_TYPE_EXTENSION_RANGE=TARGET_TYPE_EXTENSION_RANGE TARGET_TYPE_EXTENSION_RANGE value + * @property {string} TARGET_TYPE_MESSAGE=TARGET_TYPE_MESSAGE TARGET_TYPE_MESSAGE value + * @property {string} TARGET_TYPE_FIELD=TARGET_TYPE_FIELD TARGET_TYPE_FIELD value + * @property {string} TARGET_TYPE_ONEOF=TARGET_TYPE_ONEOF TARGET_TYPE_ONEOF value + * @property {string} TARGET_TYPE_ENUM=TARGET_TYPE_ENUM TARGET_TYPE_ENUM value + * @property {string} TARGET_TYPE_ENUM_ENTRY=TARGET_TYPE_ENUM_ENTRY TARGET_TYPE_ENUM_ENTRY value + * @property {string} TARGET_TYPE_SERVICE=TARGET_TYPE_SERVICE TARGET_TYPE_SERVICE value + * @property {string} TARGET_TYPE_METHOD=TARGET_TYPE_METHOD TARGET_TYPE_METHOD value + */ + FieldOptions.OptionTargetType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "TARGET_TYPE_UNKNOWN"] = "TARGET_TYPE_UNKNOWN"; + values[valuesById[1] = "TARGET_TYPE_FILE"] = "TARGET_TYPE_FILE"; + values[valuesById[2] = "TARGET_TYPE_EXTENSION_RANGE"] = "TARGET_TYPE_EXTENSION_RANGE"; + values[valuesById[3] = "TARGET_TYPE_MESSAGE"] = "TARGET_TYPE_MESSAGE"; + values[valuesById[4] = "TARGET_TYPE_FIELD"] = "TARGET_TYPE_FIELD"; + values[valuesById[5] = "TARGET_TYPE_ONEOF"] = "TARGET_TYPE_ONEOF"; + values[valuesById[6] = "TARGET_TYPE_ENUM"] = "TARGET_TYPE_ENUM"; + values[valuesById[7] = "TARGET_TYPE_ENUM_ENTRY"] = "TARGET_TYPE_ENUM_ENTRY"; + values[valuesById[8] = "TARGET_TYPE_SERVICE"] = "TARGET_TYPE_SERVICE"; + values[valuesById[9] = "TARGET_TYPE_METHOD"] = "TARGET_TYPE_METHOD"; + return values; + })(); + + FieldOptions.EditionDefault = (function() { + + /** + * Properties of an EditionDefault. + * @memberof google.protobuf.FieldOptions + * @interface IEditionDefault + * @property {google.protobuf.Edition|null} [edition] EditionDefault edition + * @property {string|null} [value] EditionDefault value + */ + + /** + * Constructs a new EditionDefault. + * @memberof google.protobuf.FieldOptions + * @classdesc Represents an EditionDefault. + * @implements IEditionDefault + * @constructor + * @param {google.protobuf.FieldOptions.IEditionDefault=} [properties] Properties to set + */ + function EditionDefault(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EditionDefault edition. + * @member {google.protobuf.Edition} edition + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + */ + EditionDefault.prototype.edition = 0; + + /** + * EditionDefault value. + * @member {string} value + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + */ + EditionDefault.prototype.value = ""; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldOptions.EditionDefault} EditionDefault + */ + EditionDefault.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldOptions.EditionDefault) + return object; + var message = new $root.google.protobuf.FieldOptions.EditionDefault(); + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.edition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.edition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.edition = 999; + break; + case "EDITION_2023": + case 1000: + message.edition = 1000; + break; + case "EDITION_2024": + case 1001: + message.edition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.edition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.edition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.edition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.edition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.edition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.edition = 2147483647; + break; + } + if (object.value != null) + message.value = String(object.value); + return message; + }; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {google.protobuf.FieldOptions.EditionDefault} message EditionDefault + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EditionDefault.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.value = ""; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; + return object; + }; + + /** + * Converts this EditionDefault to JSON. + * @function toJSON + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + * @returns {Object.} JSON object + */ + EditionDefault.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EditionDefault + * @function getTypeUrl + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldOptions.EditionDefault"; + }; + + return EditionDefault; + })(); + + return FieldOptions; + })(); + + protobuf.OneofOptions = (function() { + + /** + * Properties of an OneofOptions. + * @memberof google.protobuf + * @interface IOneofOptions + * @property {google.protobuf.IFeatureSet|null} [features] OneofOptions features + * @property {Array.|null} [uninterpretedOption] OneofOptions uninterpretedOption + */ + + /** + * Constructs a new OneofOptions. + * @memberof google.protobuf + * @classdesc Represents an OneofOptions. + * @implements IOneofOptions + * @constructor + * @param {google.protobuf.IOneofOptions=} [properties] Properties to set + */ + function OneofOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OneofOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.OneofOptions + * @instance + */ + OneofOptions.prototype.features = null; + + /** + * OneofOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.OneofOptions + * @instance + */ + OneofOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.OneofOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.OneofOptions} OneofOptions + */ + OneofOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.OneofOptions) + return object; + var message = new $root.google.protobuf.OneofOptions(); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.OneofOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.OneofOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.OneofOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.OneofOptions + * @static + * @param {google.protobuf.OneofOptions} message OneofOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OneofOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) + object.features = null; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this OneofOptions to JSON. + * @function toJSON + * @memberof google.protobuf.OneofOptions + * @instance + * @returns {Object.} JSON object + */ + OneofOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OneofOptions + * @function getTypeUrl + * @memberof google.protobuf.OneofOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OneofOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.OneofOptions"; + }; + + return OneofOptions; + })(); + + protobuf.EnumOptions = (function() { + + /** + * Properties of an EnumOptions. + * @memberof google.protobuf + * @interface IEnumOptions + * @property {boolean|null} [allowAlias] EnumOptions allowAlias + * @property {boolean|null} [deprecated] EnumOptions deprecated + * @property {boolean|null} [deprecatedLegacyJsonFieldConflicts] EnumOptions deprecatedLegacyJsonFieldConflicts + * @property {google.protobuf.IFeatureSet|null} [features] EnumOptions features + * @property {Array.|null} [uninterpretedOption] EnumOptions uninterpretedOption + */ + + /** + * Constructs a new EnumOptions. + * @memberof google.protobuf + * @classdesc Represents an EnumOptions. + * @implements IEnumOptions + * @constructor + * @param {google.protobuf.IEnumOptions=} [properties] Properties to set + */ + function EnumOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumOptions allowAlias. + * @member {boolean} allowAlias + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.allowAlias = false; + + /** + * EnumOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.deprecated = false; + + /** + * EnumOptions deprecatedLegacyJsonFieldConflicts. + * @member {boolean} deprecatedLegacyJsonFieldConflicts + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.deprecatedLegacyJsonFieldConflicts = false; + + /** + * EnumOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.features = null; + + /** + * EnumOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumOptions} EnumOptions + */ + EnumOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumOptions) + return object; + var message = new $root.google.protobuf.EnumOptions(); + if (object.allowAlias != null) + message.allowAlias = Boolean(object.allowAlias); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.deprecatedLegacyJsonFieldConflicts != null) + message.deprecatedLegacyJsonFieldConflicts = Boolean(object.deprecatedLegacyJsonFieldConflicts); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.EnumOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.EnumOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.EnumOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumOptions + * @static + * @param {google.protobuf.EnumOptions} message EnumOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.allowAlias = false; + object.deprecated = false; + object.deprecatedLegacyJsonFieldConflicts = false; + object.features = null; + } + if (message.allowAlias != null && message.hasOwnProperty("allowAlias")) + object.allowAlias = message.allowAlias; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.deprecatedLegacyJsonFieldConflicts != null && message.hasOwnProperty("deprecatedLegacyJsonFieldConflicts")) + object.deprecatedLegacyJsonFieldConflicts = message.deprecatedLegacyJsonFieldConflicts; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this EnumOptions to JSON. + * @function toJSON + * @memberof google.protobuf.EnumOptions + * @instance + * @returns {Object.} JSON object + */ + EnumOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumOptions + * @function getTypeUrl + * @memberof google.protobuf.EnumOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumOptions"; + }; + + return EnumOptions; + })(); + + protobuf.EnumValueOptions = (function() { + + /** + * Properties of an EnumValueOptions. + * @memberof google.protobuf + * @interface IEnumValueOptions + * @property {boolean|null} [deprecated] EnumValueOptions deprecated + * @property {google.protobuf.IFeatureSet|null} [features] EnumValueOptions features + * @property {boolean|null} [debugRedact] EnumValueOptions debugRedact + * @property {Array.|null} [uninterpretedOption] EnumValueOptions uninterpretedOption + */ + + /** + * Constructs a new EnumValueOptions. + * @memberof google.protobuf + * @classdesc Represents an EnumValueOptions. + * @implements IEnumValueOptions + * @constructor + * @param {google.protobuf.IEnumValueOptions=} [properties] Properties to set + */ + function EnumValueOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumValueOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.deprecated = false; + + /** + * EnumValueOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.features = null; + + /** + * EnumValueOptions debugRedact. + * @member {boolean} debugRedact + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.debugRedact = false; + + /** + * EnumValueOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumValueOptions} EnumValueOptions + */ + EnumValueOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumValueOptions) + return object; + var message = new $root.google.protobuf.EnumValueOptions(); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.debugRedact != null) + message.debugRedact = Boolean(object.debugRedact); + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.EnumValueOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {google.protobuf.EnumValueOptions} message EnumValueOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumValueOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.deprecated = false; + object.features = null; + object.debugRedact = false; + } + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) + object.debugRedact = message.debugRedact; + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this EnumValueOptions to JSON. + * @function toJSON + * @memberof google.protobuf.EnumValueOptions + * @instance + * @returns {Object.} JSON object + */ + EnumValueOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumValueOptions + * @function getTypeUrl + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumValueOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumValueOptions"; + }; + + return EnumValueOptions; + })(); + + protobuf.ServiceOptions = (function() { + + /** + * Properties of a ServiceOptions. + * @memberof google.protobuf + * @interface IServiceOptions + * @property {google.protobuf.IFeatureSet|null} [features] ServiceOptions features + * @property {boolean|null} [deprecated] ServiceOptions deprecated + * @property {Array.|null} [uninterpretedOption] ServiceOptions uninterpretedOption + * @property {string|null} [".google.api.defaultHost"] ServiceOptions .google.api.defaultHost + * @property {string|null} [".google.api.oauthScopes"] ServiceOptions .google.api.oauthScopes + * @property {string|null} [".google.api.apiVersion"] ServiceOptions .google.api.apiVersion + */ + + /** + * Constructs a new ServiceOptions. + * @memberof google.protobuf + * @classdesc Represents a ServiceOptions. + * @implements IServiceOptions + * @constructor + * @param {google.protobuf.IServiceOptions=} [properties] Properties to set + */ + function ServiceOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ServiceOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype.features = null; + + /** + * ServiceOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype.deprecated = false; + + /** + * ServiceOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * ServiceOptions .google.api.defaultHost. + * @member {string} .google.api.defaultHost + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype[".google.api.defaultHost"] = ""; + + /** + * ServiceOptions .google.api.oauthScopes. + * @member {string} .google.api.oauthScopes + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype[".google.api.oauthScopes"] = ""; + + /** + * ServiceOptions .google.api.apiVersion. + * @member {string} .google.api.apiVersion + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype[".google.api.apiVersion"] = ""; + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ServiceOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ServiceOptions} ServiceOptions + */ + ServiceOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ServiceOptions) + return object; + var message = new $root.google.protobuf.ServiceOptions(); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.ServiceOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.ServiceOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.ServiceOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.defaultHost"] != null) + message[".google.api.defaultHost"] = String(object[".google.api.defaultHost"]); + if (object[".google.api.oauthScopes"] != null) + message[".google.api.oauthScopes"] = String(object[".google.api.oauthScopes"]); + if (object[".google.api.apiVersion"] != null) + message[".google.api.apiVersion"] = String(object[".google.api.apiVersion"]); + return message; + }; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ServiceOptions + * @static + * @param {google.protobuf.ServiceOptions} message ServiceOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ServiceOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.deprecated = false; + object.features = null; + object[".google.api.defaultHost"] = ""; + object[".google.api.oauthScopes"] = ""; + object[".google.api.apiVersion"] = ""; + } + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.defaultHost"] != null && message.hasOwnProperty(".google.api.defaultHost")) + object[".google.api.defaultHost"] = message[".google.api.defaultHost"]; + if (message[".google.api.oauthScopes"] != null && message.hasOwnProperty(".google.api.oauthScopes")) + object[".google.api.oauthScopes"] = message[".google.api.oauthScopes"]; + if (message[".google.api.apiVersion"] != null && message.hasOwnProperty(".google.api.apiVersion")) + object[".google.api.apiVersion"] = message[".google.api.apiVersion"]; + return object; + }; + + /** + * Converts this ServiceOptions to JSON. + * @function toJSON + * @memberof google.protobuf.ServiceOptions + * @instance + * @returns {Object.} JSON object + */ + ServiceOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ServiceOptions + * @function getTypeUrl + * @memberof google.protobuf.ServiceOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ServiceOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ServiceOptions"; + }; + + return ServiceOptions; + })(); + + protobuf.MethodOptions = (function() { + + /** + * Properties of a MethodOptions. + * @memberof google.protobuf + * @interface IMethodOptions + * @property {boolean|null} [deprecated] MethodOptions deprecated + * @property {google.protobuf.MethodOptions.IdempotencyLevel|null} [idempotencyLevel] MethodOptions idempotencyLevel + * @property {google.protobuf.IFeatureSet|null} [features] MethodOptions features + * @property {Array.|null} [uninterpretedOption] MethodOptions uninterpretedOption + * @property {google.api.IHttpRule|null} [".google.api.http"] MethodOptions .google.api.http + * @property {Array.|null} [".google.api.methodSignature"] MethodOptions .google.api.methodSignature + * @property {google.api.IRoutingRule|null} [".google.api.routing"] MethodOptions .google.api.routing + * @property {google.longrunning.IOperationInfo|null} [".google.longrunning.operationInfo"] MethodOptions .google.longrunning.operationInfo + */ + + /** + * Constructs a new MethodOptions. + * @memberof google.protobuf + * @classdesc Represents a MethodOptions. + * @implements IMethodOptions + * @constructor + * @param {google.protobuf.IMethodOptions=} [properties] Properties to set + */ + function MethodOptions(properties) { + this.uninterpretedOption = []; + this[".google.api.methodSignature"] = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MethodOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.deprecated = false; + + /** + * MethodOptions idempotencyLevel. + * @member {google.protobuf.MethodOptions.IdempotencyLevel} idempotencyLevel + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.idempotencyLevel = 0; + + /** + * MethodOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.features = null; + + /** + * MethodOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * MethodOptions .google.api.http. + * @member {google.api.IHttpRule|null|undefined} .google.api.http + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.api.http"] = null; + + /** + * MethodOptions .google.api.methodSignature. + * @member {Array.} .google.api.methodSignature + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.api.methodSignature"] = $util.emptyArray; + + /** + * MethodOptions .google.api.routing. + * @member {google.api.IRoutingRule|null|undefined} .google.api.routing + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.api.routing"] = null; + + /** + * MethodOptions .google.longrunning.operationInfo. + * @member {google.longrunning.IOperationInfo|null|undefined} .google.longrunning.operationInfo + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.longrunning.operationInfo"] = null; + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.MethodOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.MethodOptions} MethodOptions + */ + MethodOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.MethodOptions) + return object; + var message = new $root.google.protobuf.MethodOptions(); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + switch (object.idempotencyLevel) { + default: + if (typeof object.idempotencyLevel === "number") { + message.idempotencyLevel = object.idempotencyLevel; + break; + } + break; + case "IDEMPOTENCY_UNKNOWN": + case 0: + message.idempotencyLevel = 0; + break; + case "NO_SIDE_EFFECTS": + case 1: + message.idempotencyLevel = 1; + break; + case "IDEMPOTENT": + case 2: + message.idempotencyLevel = 2; + break; + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.MethodOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.MethodOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.MethodOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.http"] != null) { + if (typeof object[".google.api.http"] !== "object") + throw TypeError(".google.protobuf.MethodOptions..google.api.http: object expected"); + message[".google.api.http"] = $root.google.api.HttpRule.fromObject(object[".google.api.http"]); + } + if (object[".google.api.methodSignature"]) { + if (!Array.isArray(object[".google.api.methodSignature"])) + throw TypeError(".google.protobuf.MethodOptions..google.api.methodSignature: array expected"); + message[".google.api.methodSignature"] = []; + for (var i = 0; i < object[".google.api.methodSignature"].length; ++i) + message[".google.api.methodSignature"][i] = String(object[".google.api.methodSignature"][i]); + } + if (object[".google.api.routing"] != null) { + if (typeof object[".google.api.routing"] !== "object") + throw TypeError(".google.protobuf.MethodOptions..google.api.routing: object expected"); + message[".google.api.routing"] = $root.google.api.RoutingRule.fromObject(object[".google.api.routing"]); + } + if (object[".google.longrunning.operationInfo"] != null) { + if (typeof object[".google.longrunning.operationInfo"] !== "object") + throw TypeError(".google.protobuf.MethodOptions..google.longrunning.operationInfo: object expected"); + message[".google.longrunning.operationInfo"] = $root.google.longrunning.OperationInfo.fromObject(object[".google.longrunning.operationInfo"]); + } + return message; + }; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.MethodOptions + * @static + * @param {google.protobuf.MethodOptions} message MethodOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MethodOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.uninterpretedOption = []; + object[".google.api.methodSignature"] = []; + } + if (options.defaults) { + object.deprecated = false; + object.idempotencyLevel = options.enums === String ? "IDEMPOTENCY_UNKNOWN" : 0; + object.features = null; + object[".google.longrunning.operationInfo"] = null; + object[".google.api.http"] = null; + object[".google.api.routing"] = null; + } + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.idempotencyLevel != null && message.hasOwnProperty("idempotencyLevel")) + object.idempotencyLevel = options.enums === String ? $root.google.protobuf.MethodOptions.IdempotencyLevel[message.idempotencyLevel] === undefined ? message.idempotencyLevel : $root.google.protobuf.MethodOptions.IdempotencyLevel[message.idempotencyLevel] : message.idempotencyLevel; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.longrunning.operationInfo"] != null && message.hasOwnProperty(".google.longrunning.operationInfo")) + object[".google.longrunning.operationInfo"] = $root.google.longrunning.OperationInfo.toObject(message[".google.longrunning.operationInfo"], options); + if (message[".google.api.methodSignature"] && message[".google.api.methodSignature"].length) { + object[".google.api.methodSignature"] = []; + for (var j = 0; j < message[".google.api.methodSignature"].length; ++j) + object[".google.api.methodSignature"][j] = message[".google.api.methodSignature"][j]; + } + if (message[".google.api.http"] != null && message.hasOwnProperty(".google.api.http")) + object[".google.api.http"] = $root.google.api.HttpRule.toObject(message[".google.api.http"], options); + if (message[".google.api.routing"] != null && message.hasOwnProperty(".google.api.routing")) + object[".google.api.routing"] = $root.google.api.RoutingRule.toObject(message[".google.api.routing"], options); + return object; + }; + + /** + * Converts this MethodOptions to JSON. + * @function toJSON + * @memberof google.protobuf.MethodOptions + * @instance + * @returns {Object.} JSON object + */ + MethodOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MethodOptions + * @function getTypeUrl + * @memberof google.protobuf.MethodOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MethodOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.MethodOptions"; + }; + + /** + * IdempotencyLevel enum. + * @name google.protobuf.MethodOptions.IdempotencyLevel + * @enum {string} + * @property {string} IDEMPOTENCY_UNKNOWN=IDEMPOTENCY_UNKNOWN IDEMPOTENCY_UNKNOWN value + * @property {string} NO_SIDE_EFFECTS=NO_SIDE_EFFECTS NO_SIDE_EFFECTS value + * @property {string} IDEMPOTENT=IDEMPOTENT IDEMPOTENT value + */ + MethodOptions.IdempotencyLevel = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; + values[valuesById[1] = "NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; + values[valuesById[2] = "IDEMPOTENT"] = "IDEMPOTENT"; + return values; + })(); + + return MethodOptions; + })(); + + protobuf.UninterpretedOption = (function() { + + /** + * Properties of an UninterpretedOption. + * @memberof google.protobuf + * @interface IUninterpretedOption + * @property {Array.|null} [name] UninterpretedOption name + * @property {string|null} [identifierValue] UninterpretedOption identifierValue + * @property {number|string|null} [positiveIntValue] UninterpretedOption positiveIntValue + * @property {number|string|null} [negativeIntValue] UninterpretedOption negativeIntValue + * @property {number|null} [doubleValue] UninterpretedOption doubleValue + * @property {Uint8Array|null} [stringValue] UninterpretedOption stringValue + * @property {string|null} [aggregateValue] UninterpretedOption aggregateValue + */ + + /** + * Constructs a new UninterpretedOption. + * @memberof google.protobuf + * @classdesc Represents an UninterpretedOption. + * @implements IUninterpretedOption + * @constructor + * @param {google.protobuf.IUninterpretedOption=} [properties] Properties to set + */ + function UninterpretedOption(properties) { + this.name = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UninterpretedOption name. + * @member {Array.} name + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.name = $util.emptyArray; + + /** + * UninterpretedOption identifierValue. + * @member {string} identifierValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.identifierValue = ""; + + /** + * UninterpretedOption positiveIntValue. + * @member {number|string} positiveIntValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.positiveIntValue = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * UninterpretedOption negativeIntValue. + * @member {number|string} negativeIntValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.negativeIntValue = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * UninterpretedOption doubleValue. + * @member {number} doubleValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.doubleValue = 0; + + /** + * UninterpretedOption stringValue. + * @member {Uint8Array} stringValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.stringValue = $util.newBuffer([]); + + /** + * UninterpretedOption aggregateValue. + * @member {string} aggregateValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.aggregateValue = ""; + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.UninterpretedOption} UninterpretedOption + */ + UninterpretedOption.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UninterpretedOption) + return object; + var message = new $root.google.protobuf.UninterpretedOption(); + if (object.name) { + if (!Array.isArray(object.name)) + throw TypeError(".google.protobuf.UninterpretedOption.name: array expected"); + message.name = []; + for (var i = 0; i < object.name.length; ++i) { + if (typeof object.name[i] !== "object") + throw TypeError(".google.protobuf.UninterpretedOption.name: object expected"); + message.name[i] = $root.google.protobuf.UninterpretedOption.NamePart.fromObject(object.name[i]); + } + } + if (object.identifierValue != null) + message.identifierValue = String(object.identifierValue); + if (object.positiveIntValue != null) + if ($util.Long) + (message.positiveIntValue = $util.Long.fromValue(object.positiveIntValue)).unsigned = true; + else if (typeof object.positiveIntValue === "string") + message.positiveIntValue = parseInt(object.positiveIntValue, 10); + else if (typeof object.positiveIntValue === "number") + message.positiveIntValue = object.positiveIntValue; + else if (typeof object.positiveIntValue === "object") + message.positiveIntValue = new $util.LongBits(object.positiveIntValue.low >>> 0, object.positiveIntValue.high >>> 0).toNumber(true); + if (object.negativeIntValue != null) + if ($util.Long) + (message.negativeIntValue = $util.Long.fromValue(object.negativeIntValue)).unsigned = false; + else if (typeof object.negativeIntValue === "string") + message.negativeIntValue = parseInt(object.negativeIntValue, 10); + else if (typeof object.negativeIntValue === "number") + message.negativeIntValue = object.negativeIntValue; + else if (typeof object.negativeIntValue === "object") + message.negativeIntValue = new $util.LongBits(object.negativeIntValue.low >>> 0, object.negativeIntValue.high >>> 0).toNumber(); + if (object.doubleValue != null) + message.doubleValue = Number(object.doubleValue); + if (object.stringValue != null) + if (typeof object.stringValue === "string") + $util.base64.decode(object.stringValue, message.stringValue = $util.newBuffer($util.base64.length(object.stringValue)), 0); + else if (object.stringValue.length >= 0) + message.stringValue = object.stringValue; + if (object.aggregateValue != null) + message.aggregateValue = String(object.aggregateValue); + return message; + }; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {google.protobuf.UninterpretedOption} message UninterpretedOption + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UninterpretedOption.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.name = []; + if (options.defaults) { + object.identifierValue = ""; + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.positiveIntValue = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.positiveIntValue = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.negativeIntValue = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.negativeIntValue = options.longs === String ? "0" : 0; + object.doubleValue = 0; + if (options.bytes === String) + object.stringValue = ""; + else { + object.stringValue = []; + if (options.bytes !== Array) + object.stringValue = $util.newBuffer(object.stringValue); + } + object.aggregateValue = ""; + } + if (message.name && message.name.length) { + object.name = []; + for (var j = 0; j < message.name.length; ++j) + object.name[j] = $root.google.protobuf.UninterpretedOption.NamePart.toObject(message.name[j], options); + } + if (message.identifierValue != null && message.hasOwnProperty("identifierValue")) + object.identifierValue = message.identifierValue; + if (message.positiveIntValue != null && message.hasOwnProperty("positiveIntValue")) + if (typeof message.positiveIntValue === "number") + object.positiveIntValue = options.longs === String ? String(message.positiveIntValue) : message.positiveIntValue; + else + object.positiveIntValue = options.longs === String ? $util.Long.prototype.toString.call(message.positiveIntValue) : options.longs === Number ? new $util.LongBits(message.positiveIntValue.low >>> 0, message.positiveIntValue.high >>> 0).toNumber(true) : message.positiveIntValue; + if (message.negativeIntValue != null && message.hasOwnProperty("negativeIntValue")) + if (typeof message.negativeIntValue === "number") + object.negativeIntValue = options.longs === String ? String(message.negativeIntValue) : message.negativeIntValue; + else + object.negativeIntValue = options.longs === String ? $util.Long.prototype.toString.call(message.negativeIntValue) : options.longs === Number ? new $util.LongBits(message.negativeIntValue.low >>> 0, message.negativeIntValue.high >>> 0).toNumber() : message.negativeIntValue; + if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) + object.doubleValue = options.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue; + if (message.stringValue != null && message.hasOwnProperty("stringValue")) + object.stringValue = options.bytes === String ? $util.base64.encode(message.stringValue, 0, message.stringValue.length) : options.bytes === Array ? Array.prototype.slice.call(message.stringValue) : message.stringValue; + if (message.aggregateValue != null && message.hasOwnProperty("aggregateValue")) + object.aggregateValue = message.aggregateValue; + return object; + }; + + /** + * Converts this UninterpretedOption to JSON. + * @function toJSON + * @memberof google.protobuf.UninterpretedOption + * @instance + * @returns {Object.} JSON object + */ + UninterpretedOption.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UninterpretedOption + * @function getTypeUrl + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UninterpretedOption.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.UninterpretedOption"; + }; + + UninterpretedOption.NamePart = (function() { + + /** + * Properties of a NamePart. + * @memberof google.protobuf.UninterpretedOption + * @interface INamePart + * @property {string} namePart NamePart namePart + * @property {boolean} isExtension NamePart isExtension + */ + + /** + * Constructs a new NamePart. + * @memberof google.protobuf.UninterpretedOption + * @classdesc Represents a NamePart. + * @implements INamePart + * @constructor + * @param {google.protobuf.UninterpretedOption.INamePart=} [properties] Properties to set + */ + function NamePart(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * NamePart namePart. + * @member {string} namePart + * @memberof google.protobuf.UninterpretedOption.NamePart + * @instance + */ + NamePart.prototype.namePart = ""; + + /** + * NamePart isExtension. + * @member {boolean} isExtension + * @memberof google.protobuf.UninterpretedOption.NamePart + * @instance + */ + NamePart.prototype.isExtension = false; + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.UninterpretedOption.NamePart} NamePart + */ + NamePart.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UninterpretedOption.NamePart) + return object; + var message = new $root.google.protobuf.UninterpretedOption.NamePart(); + if (object.namePart != null) + message.namePart = String(object.namePart); + if (object.isExtension != null) + message.isExtension = Boolean(object.isExtension); + return message; + }; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {google.protobuf.UninterpretedOption.NamePart} message NamePart + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + NamePart.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.namePart = ""; + object.isExtension = false; + } + if (message.namePart != null && message.hasOwnProperty("namePart")) + object.namePart = message.namePart; + if (message.isExtension != null && message.hasOwnProperty("isExtension")) + object.isExtension = message.isExtension; + return object; + }; + + /** + * Converts this NamePart to JSON. + * @function toJSON + * @memberof google.protobuf.UninterpretedOption.NamePart + * @instance + * @returns {Object.} JSON object + */ + NamePart.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for NamePart + * @function getTypeUrl + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + NamePart.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.UninterpretedOption.NamePart"; + }; + + return NamePart; + })(); + + return UninterpretedOption; + })(); + + protobuf.FeatureSet = (function() { + + /** + * Properties of a FeatureSet. + * @memberof google.protobuf + * @interface IFeatureSet + * @property {google.protobuf.FeatureSet.FieldPresence|null} [fieldPresence] FeatureSet fieldPresence + * @property {google.protobuf.FeatureSet.EnumType|null} [enumType] FeatureSet enumType + * @property {google.protobuf.FeatureSet.RepeatedFieldEncoding|null} [repeatedFieldEncoding] FeatureSet repeatedFieldEncoding + * @property {google.protobuf.FeatureSet.Utf8Validation|null} [utf8Validation] FeatureSet utf8Validation + * @property {google.protobuf.FeatureSet.MessageEncoding|null} [messageEncoding] FeatureSet messageEncoding + * @property {google.protobuf.FeatureSet.JsonFormat|null} [jsonFormat] FeatureSet jsonFormat + */ + + /** + * Constructs a new FeatureSet. + * @memberof google.protobuf + * @classdesc Represents a FeatureSet. + * @implements IFeatureSet + * @constructor + * @param {google.protobuf.IFeatureSet=} [properties] Properties to set + */ + function FeatureSet(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FeatureSet fieldPresence. + * @member {google.protobuf.FeatureSet.FieldPresence} fieldPresence + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.fieldPresence = 0; + + /** + * FeatureSet enumType. + * @member {google.protobuf.FeatureSet.EnumType} enumType + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.enumType = 0; + + /** + * FeatureSet repeatedFieldEncoding. + * @member {google.protobuf.FeatureSet.RepeatedFieldEncoding} repeatedFieldEncoding + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.repeatedFieldEncoding = 0; + + /** + * FeatureSet utf8Validation. + * @member {google.protobuf.FeatureSet.Utf8Validation} utf8Validation + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.utf8Validation = 0; + + /** + * FeatureSet messageEncoding. + * @member {google.protobuf.FeatureSet.MessageEncoding} messageEncoding + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.messageEncoding = 0; + + /** + * FeatureSet jsonFormat. + * @member {google.protobuf.FeatureSet.JsonFormat} jsonFormat + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.jsonFormat = 0; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSet + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSet} FeatureSet + */ + FeatureSet.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSet) + return object; + var message = new $root.google.protobuf.FeatureSet(); + switch (object.fieldPresence) { + default: + if (typeof object.fieldPresence === "number") { + message.fieldPresence = object.fieldPresence; + break; + } + break; + case "FIELD_PRESENCE_UNKNOWN": + case 0: + message.fieldPresence = 0; + break; + case "EXPLICIT": + case 1: + message.fieldPresence = 1; + break; + case "IMPLICIT": + case 2: + message.fieldPresence = 2; + break; + case "LEGACY_REQUIRED": + case 3: + message.fieldPresence = 3; + break; + } + switch (object.enumType) { + default: + if (typeof object.enumType === "number") { + message.enumType = object.enumType; + break; + } + break; + case "ENUM_TYPE_UNKNOWN": + case 0: + message.enumType = 0; + break; + case "OPEN": + case 1: + message.enumType = 1; + break; + case "CLOSED": + case 2: + message.enumType = 2; + break; + } + switch (object.repeatedFieldEncoding) { + default: + if (typeof object.repeatedFieldEncoding === "number") { + message.repeatedFieldEncoding = object.repeatedFieldEncoding; + break; + } + break; + case "REPEATED_FIELD_ENCODING_UNKNOWN": + case 0: + message.repeatedFieldEncoding = 0; + break; + case "PACKED": + case 1: + message.repeatedFieldEncoding = 1; + break; + case "EXPANDED": + case 2: + message.repeatedFieldEncoding = 2; + break; + } + switch (object.utf8Validation) { + default: + if (typeof object.utf8Validation === "number") { + message.utf8Validation = object.utf8Validation; + break; + } + break; + case "UTF8_VALIDATION_UNKNOWN": + case 0: + message.utf8Validation = 0; + break; + case "VERIFY": + case 2: + message.utf8Validation = 2; + break; + case "NONE": + case 3: + message.utf8Validation = 3; + break; + } + switch (object.messageEncoding) { + default: + if (typeof object.messageEncoding === "number") { + message.messageEncoding = object.messageEncoding; + break; + } + break; + case "MESSAGE_ENCODING_UNKNOWN": + case 0: + message.messageEncoding = 0; + break; + case "LENGTH_PREFIXED": + case 1: + message.messageEncoding = 1; + break; + case "DELIMITED": + case 2: + message.messageEncoding = 2; + break; + } + switch (object.jsonFormat) { + default: + if (typeof object.jsonFormat === "number") { + message.jsonFormat = object.jsonFormat; + break; + } + break; + case "JSON_FORMAT_UNKNOWN": + case 0: + message.jsonFormat = 0; + break; + case "ALLOW": + case 1: + message.jsonFormat = 1; + break; + case "LEGACY_BEST_EFFORT": + case 2: + message.jsonFormat = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSet + * @static + * @param {google.protobuf.FeatureSet} message FeatureSet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FeatureSet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.fieldPresence = options.enums === String ? "FIELD_PRESENCE_UNKNOWN" : 0; + object.enumType = options.enums === String ? "ENUM_TYPE_UNKNOWN" : 0; + object.repeatedFieldEncoding = options.enums === String ? "REPEATED_FIELD_ENCODING_UNKNOWN" : 0; + object.utf8Validation = options.enums === String ? "UTF8_VALIDATION_UNKNOWN" : 0; + object.messageEncoding = options.enums === String ? "MESSAGE_ENCODING_UNKNOWN" : 0; + object.jsonFormat = options.enums === String ? "JSON_FORMAT_UNKNOWN" : 0; + } + if (message.fieldPresence != null && message.hasOwnProperty("fieldPresence")) + object.fieldPresence = options.enums === String ? $root.google.protobuf.FeatureSet.FieldPresence[message.fieldPresence] === undefined ? message.fieldPresence : $root.google.protobuf.FeatureSet.FieldPresence[message.fieldPresence] : message.fieldPresence; + if (message.enumType != null && message.hasOwnProperty("enumType")) + object.enumType = options.enums === String ? $root.google.protobuf.FeatureSet.EnumType[message.enumType] === undefined ? message.enumType : $root.google.protobuf.FeatureSet.EnumType[message.enumType] : message.enumType; + if (message.repeatedFieldEncoding != null && message.hasOwnProperty("repeatedFieldEncoding")) + object.repeatedFieldEncoding = options.enums === String ? $root.google.protobuf.FeatureSet.RepeatedFieldEncoding[message.repeatedFieldEncoding] === undefined ? message.repeatedFieldEncoding : $root.google.protobuf.FeatureSet.RepeatedFieldEncoding[message.repeatedFieldEncoding] : message.repeatedFieldEncoding; + if (message.utf8Validation != null && message.hasOwnProperty("utf8Validation")) + object.utf8Validation = options.enums === String ? $root.google.protobuf.FeatureSet.Utf8Validation[message.utf8Validation] === undefined ? message.utf8Validation : $root.google.protobuf.FeatureSet.Utf8Validation[message.utf8Validation] : message.utf8Validation; + if (message.messageEncoding != null && message.hasOwnProperty("messageEncoding")) + object.messageEncoding = options.enums === String ? $root.google.protobuf.FeatureSet.MessageEncoding[message.messageEncoding] === undefined ? message.messageEncoding : $root.google.protobuf.FeatureSet.MessageEncoding[message.messageEncoding] : message.messageEncoding; + if (message.jsonFormat != null && message.hasOwnProperty("jsonFormat")) + object.jsonFormat = options.enums === String ? $root.google.protobuf.FeatureSet.JsonFormat[message.jsonFormat] === undefined ? message.jsonFormat : $root.google.protobuf.FeatureSet.JsonFormat[message.jsonFormat] : message.jsonFormat; + return object; + }; + + /** + * Converts this FeatureSet to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSet + * @instance + * @returns {Object.} JSON object + */ + FeatureSet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FeatureSet + * @function getTypeUrl + * @memberof google.protobuf.FeatureSet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FeatureSet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSet"; + }; + + /** + * FieldPresence enum. + * @name google.protobuf.FeatureSet.FieldPresence + * @enum {string} + * @property {string} FIELD_PRESENCE_UNKNOWN=FIELD_PRESENCE_UNKNOWN FIELD_PRESENCE_UNKNOWN value + * @property {string} EXPLICIT=EXPLICIT EXPLICIT value + * @property {string} IMPLICIT=IMPLICIT IMPLICIT value + * @property {string} LEGACY_REQUIRED=LEGACY_REQUIRED LEGACY_REQUIRED value + */ + FeatureSet.FieldPresence = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "FIELD_PRESENCE_UNKNOWN"] = "FIELD_PRESENCE_UNKNOWN"; + values[valuesById[1] = "EXPLICIT"] = "EXPLICIT"; + values[valuesById[2] = "IMPLICIT"] = "IMPLICIT"; + values[valuesById[3] = "LEGACY_REQUIRED"] = "LEGACY_REQUIRED"; + return values; + })(); + + /** + * EnumType enum. + * @name google.protobuf.FeatureSet.EnumType + * @enum {string} + * @property {string} ENUM_TYPE_UNKNOWN=ENUM_TYPE_UNKNOWN ENUM_TYPE_UNKNOWN value + * @property {string} OPEN=OPEN OPEN value + * @property {string} CLOSED=CLOSED CLOSED value + */ + FeatureSet.EnumType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ENUM_TYPE_UNKNOWN"] = "ENUM_TYPE_UNKNOWN"; + values[valuesById[1] = "OPEN"] = "OPEN"; + values[valuesById[2] = "CLOSED"] = "CLOSED"; + return values; + })(); + + /** + * RepeatedFieldEncoding enum. + * @name google.protobuf.FeatureSet.RepeatedFieldEncoding + * @enum {string} + * @property {string} REPEATED_FIELD_ENCODING_UNKNOWN=REPEATED_FIELD_ENCODING_UNKNOWN REPEATED_FIELD_ENCODING_UNKNOWN value + * @property {string} PACKED=PACKED PACKED value + * @property {string} EXPANDED=EXPANDED EXPANDED value + */ + FeatureSet.RepeatedFieldEncoding = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "REPEATED_FIELD_ENCODING_UNKNOWN"] = "REPEATED_FIELD_ENCODING_UNKNOWN"; + values[valuesById[1] = "PACKED"] = "PACKED"; + values[valuesById[2] = "EXPANDED"] = "EXPANDED"; + return values; + })(); + + /** + * Utf8Validation enum. + * @name google.protobuf.FeatureSet.Utf8Validation + * @enum {string} + * @property {string} UTF8_VALIDATION_UNKNOWN=UTF8_VALIDATION_UNKNOWN UTF8_VALIDATION_UNKNOWN value + * @property {string} VERIFY=VERIFY VERIFY value + * @property {string} NONE=NONE NONE value + */ + FeatureSet.Utf8Validation = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UTF8_VALIDATION_UNKNOWN"] = "UTF8_VALIDATION_UNKNOWN"; + values[valuesById[2] = "VERIFY"] = "VERIFY"; + values[valuesById[3] = "NONE"] = "NONE"; + return values; + })(); + + /** + * MessageEncoding enum. + * @name google.protobuf.FeatureSet.MessageEncoding + * @enum {string} + * @property {string} MESSAGE_ENCODING_UNKNOWN=MESSAGE_ENCODING_UNKNOWN MESSAGE_ENCODING_UNKNOWN value + * @property {string} LENGTH_PREFIXED=LENGTH_PREFIXED LENGTH_PREFIXED value + * @property {string} DELIMITED=DELIMITED DELIMITED value + */ + FeatureSet.MessageEncoding = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "MESSAGE_ENCODING_UNKNOWN"] = "MESSAGE_ENCODING_UNKNOWN"; + values[valuesById[1] = "LENGTH_PREFIXED"] = "LENGTH_PREFIXED"; + values[valuesById[2] = "DELIMITED"] = "DELIMITED"; + return values; + })(); + + /** + * JsonFormat enum. + * @name google.protobuf.FeatureSet.JsonFormat + * @enum {string} + * @property {string} JSON_FORMAT_UNKNOWN=JSON_FORMAT_UNKNOWN JSON_FORMAT_UNKNOWN value + * @property {string} ALLOW=ALLOW ALLOW value + * @property {string} LEGACY_BEST_EFFORT=LEGACY_BEST_EFFORT LEGACY_BEST_EFFORT value + */ + FeatureSet.JsonFormat = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "JSON_FORMAT_UNKNOWN"] = "JSON_FORMAT_UNKNOWN"; + values[valuesById[1] = "ALLOW"] = "ALLOW"; + values[valuesById[2] = "LEGACY_BEST_EFFORT"] = "LEGACY_BEST_EFFORT"; + return values; + })(); + + return FeatureSet; + })(); + + protobuf.FeatureSetDefaults = (function() { + + /** + * Properties of a FeatureSetDefaults. + * @memberof google.protobuf + * @interface IFeatureSetDefaults + * @property {Array.|null} [defaults] FeatureSetDefaults defaults + * @property {google.protobuf.Edition|null} [minimumEdition] FeatureSetDefaults minimumEdition + * @property {google.protobuf.Edition|null} [maximumEdition] FeatureSetDefaults maximumEdition + */ + + /** + * Constructs a new FeatureSetDefaults. + * @memberof google.protobuf + * @classdesc Represents a FeatureSetDefaults. + * @implements IFeatureSetDefaults + * @constructor + * @param {google.protobuf.IFeatureSetDefaults=} [properties] Properties to set + */ + function FeatureSetDefaults(properties) { + this.defaults = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FeatureSetDefaults defaults. + * @member {Array.} defaults + * @memberof google.protobuf.FeatureSetDefaults + * @instance + */ + FeatureSetDefaults.prototype.defaults = $util.emptyArray; + + /** + * FeatureSetDefaults minimumEdition. + * @member {google.protobuf.Edition} minimumEdition + * @memberof google.protobuf.FeatureSetDefaults + * @instance + */ + FeatureSetDefaults.prototype.minimumEdition = 0; + + /** + * FeatureSetDefaults maximumEdition. + * @member {google.protobuf.Edition} maximumEdition + * @memberof google.protobuf.FeatureSetDefaults + * @instance + */ + FeatureSetDefaults.prototype.maximumEdition = 0; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSetDefaults} FeatureSetDefaults + */ + FeatureSetDefaults.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSetDefaults) + return object; + var message = new $root.google.protobuf.FeatureSetDefaults(); + if (object.defaults) { + if (!Array.isArray(object.defaults)) + throw TypeError(".google.protobuf.FeatureSetDefaults.defaults: array expected"); + message.defaults = []; + for (var i = 0; i < object.defaults.length; ++i) { + if (typeof object.defaults[i] !== "object") + throw TypeError(".google.protobuf.FeatureSetDefaults.defaults: object expected"); + message.defaults[i] = $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.fromObject(object.defaults[i]); + } + } + switch (object.minimumEdition) { + default: + if (typeof object.minimumEdition === "number") { + message.minimumEdition = object.minimumEdition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.minimumEdition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.minimumEdition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.minimumEdition = 999; + break; + case "EDITION_2023": + case 1000: + message.minimumEdition = 1000; + break; + case "EDITION_2024": + case 1001: + message.minimumEdition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.minimumEdition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.minimumEdition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.minimumEdition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.minimumEdition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.minimumEdition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.minimumEdition = 2147483647; + break; + } + switch (object.maximumEdition) { + default: + if (typeof object.maximumEdition === "number") { + message.maximumEdition = object.maximumEdition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.maximumEdition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.maximumEdition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.maximumEdition = 999; + break; + case "EDITION_2023": + case 1000: + message.maximumEdition = 1000; + break; + case "EDITION_2024": + case 1001: + message.maximumEdition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.maximumEdition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.maximumEdition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.maximumEdition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.maximumEdition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.maximumEdition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.maximumEdition = 2147483647; + break; + } + return message; + }; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {google.protobuf.FeatureSetDefaults} message FeatureSetDefaults + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FeatureSetDefaults.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.defaults = []; + if (options.defaults) { + object.minimumEdition = options.enums === String ? "EDITION_UNKNOWN" : 0; + object.maximumEdition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.defaults && message.defaults.length) { + object.defaults = []; + for (var j = 0; j < message.defaults.length; ++j) + object.defaults[j] = $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.toObject(message.defaults[j], options); + } + if (message.minimumEdition != null && message.hasOwnProperty("minimumEdition")) + object.minimumEdition = options.enums === String ? $root.google.protobuf.Edition[message.minimumEdition] === undefined ? message.minimumEdition : $root.google.protobuf.Edition[message.minimumEdition] : message.minimumEdition; + if (message.maximumEdition != null && message.hasOwnProperty("maximumEdition")) + object.maximumEdition = options.enums === String ? $root.google.protobuf.Edition[message.maximumEdition] === undefined ? message.maximumEdition : $root.google.protobuf.Edition[message.maximumEdition] : message.maximumEdition; + return object; + }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSetDefaults + * @instance + * @returns {Object.} JSON object + */ + FeatureSetDefaults.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FeatureSetDefaults + * @function getTypeUrl + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FeatureSetDefaults.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSetDefaults"; + }; + + FeatureSetDefaults.FeatureSetEditionDefault = (function() { + + /** + * Properties of a FeatureSetEditionDefault. + * @memberof google.protobuf.FeatureSetDefaults + * @interface IFeatureSetEditionDefault + * @property {google.protobuf.Edition|null} [edition] FeatureSetEditionDefault edition + * @property {google.protobuf.IFeatureSet|null} [features] FeatureSetEditionDefault features + */ + + /** + * Constructs a new FeatureSetEditionDefault. + * @memberof google.protobuf.FeatureSetDefaults + * @classdesc Represents a FeatureSetEditionDefault. + * @implements IFeatureSetEditionDefault + * @constructor + * @param {google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault=} [properties] Properties to set + */ + function FeatureSetEditionDefault(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FeatureSetEditionDefault edition. + * @member {google.protobuf.Edition} edition + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @instance + */ + FeatureSetEditionDefault.prototype.edition = 0; + + /** + * FeatureSetEditionDefault features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @instance + */ + FeatureSetEditionDefault.prototype.features = null; + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault} FeatureSetEditionDefault + */ + FeatureSetEditionDefault.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault) + return object; + var message = new $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault(); + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.edition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.edition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.edition = 999; + break; + case "EDITION_2023": + case 1000: + message.edition = 1000; + break; + case "EDITION_2024": + case 1001: + message.edition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.edition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.edition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.edition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.edition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.edition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.edition = 2147483647; + break; + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + return message; + }; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault} message FeatureSetEditionDefault + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FeatureSetEditionDefault.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.features = null; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; + return object; + }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @instance + * @returns {Object.} JSON object + */ + FeatureSetEditionDefault.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @function getTypeUrl + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FeatureSetEditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault"; + }; + + return FeatureSetEditionDefault; + })(); + + return FeatureSetDefaults; + })(); + + protobuf.SourceCodeInfo = (function() { + + /** + * Properties of a SourceCodeInfo. + * @memberof google.protobuf + * @interface ISourceCodeInfo + * @property {Array.|null} [location] SourceCodeInfo location + */ + + /** + * Constructs a new SourceCodeInfo. + * @memberof google.protobuf + * @classdesc Represents a SourceCodeInfo. + * @implements ISourceCodeInfo + * @constructor + * @param {google.protobuf.ISourceCodeInfo=} [properties] Properties to set + */ + function SourceCodeInfo(properties) { + this.location = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SourceCodeInfo location. + * @member {Array.} location + * @memberof google.protobuf.SourceCodeInfo + * @instance + */ + SourceCodeInfo.prototype.location = $util.emptyArray; + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.SourceCodeInfo} SourceCodeInfo + */ + SourceCodeInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.SourceCodeInfo) + return object; + var message = new $root.google.protobuf.SourceCodeInfo(); + if (object.location) { + if (!Array.isArray(object.location)) + throw TypeError(".google.protobuf.SourceCodeInfo.location: array expected"); + message.location = []; + for (var i = 0; i < object.location.length; ++i) { + if (typeof object.location[i] !== "object") + throw TypeError(".google.protobuf.SourceCodeInfo.location: object expected"); + message.location[i] = $root.google.protobuf.SourceCodeInfo.Location.fromObject(object.location[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {google.protobuf.SourceCodeInfo} message SourceCodeInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SourceCodeInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.location = []; + if (message.location && message.location.length) { + object.location = []; + for (var j = 0; j < message.location.length; ++j) + object.location[j] = $root.google.protobuf.SourceCodeInfo.Location.toObject(message.location[j], options); + } + return object; + }; + + /** + * Converts this SourceCodeInfo to JSON. + * @function toJSON + * @memberof google.protobuf.SourceCodeInfo + * @instance + * @returns {Object.} JSON object + */ + SourceCodeInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SourceCodeInfo + * @function getTypeUrl + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SourceCodeInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.SourceCodeInfo"; + }; + + SourceCodeInfo.Location = (function() { + + /** + * Properties of a Location. + * @memberof google.protobuf.SourceCodeInfo + * @interface ILocation + * @property {Array.|null} [path] Location path + * @property {Array.|null} [span] Location span + * @property {string|null} [leadingComments] Location leadingComments + * @property {string|null} [trailingComments] Location trailingComments + * @property {Array.|null} [leadingDetachedComments] Location leadingDetachedComments + */ + + /** + * Constructs a new Location. + * @memberof google.protobuf.SourceCodeInfo + * @classdesc Represents a Location. + * @implements ILocation + * @constructor + * @param {google.protobuf.SourceCodeInfo.ILocation=} [properties] Properties to set + */ + function Location(properties) { + this.path = []; + this.span = []; + this.leadingDetachedComments = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Location path. + * @member {Array.} path + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.path = $util.emptyArray; + + /** + * Location span. + * @member {Array.} span + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.span = $util.emptyArray; + + /** + * Location leadingComments. + * @member {string} leadingComments + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.leadingComments = ""; + + /** + * Location trailingComments. + * @member {string} trailingComments + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.trailingComments = ""; + + /** + * Location leadingDetachedComments. + * @member {Array.} leadingDetachedComments + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.leadingDetachedComments = $util.emptyArray; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.SourceCodeInfo.Location} Location + */ + Location.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.SourceCodeInfo.Location) + return object; + var message = new $root.google.protobuf.SourceCodeInfo.Location(); + if (object.path) { + if (!Array.isArray(object.path)) + throw TypeError(".google.protobuf.SourceCodeInfo.Location.path: array expected"); + message.path = []; + for (var i = 0; i < object.path.length; ++i) + message.path[i] = object.path[i] | 0; + } + if (object.span) { + if (!Array.isArray(object.span)) + throw TypeError(".google.protobuf.SourceCodeInfo.Location.span: array expected"); + message.span = []; + for (var i = 0; i < object.span.length; ++i) + message.span[i] = object.span[i] | 0; + } + if (object.leadingComments != null) + message.leadingComments = String(object.leadingComments); + if (object.trailingComments != null) + message.trailingComments = String(object.trailingComments); + if (object.leadingDetachedComments) { + if (!Array.isArray(object.leadingDetachedComments)) + throw TypeError(".google.protobuf.SourceCodeInfo.Location.leadingDetachedComments: array expected"); + message.leadingDetachedComments = []; + for (var i = 0; i < object.leadingDetachedComments.length; ++i) + message.leadingDetachedComments[i] = String(object.leadingDetachedComments[i]); + } + return message; + }; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {google.protobuf.SourceCodeInfo.Location} message Location + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Location.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.path = []; + object.span = []; + object.leadingDetachedComments = []; + } + if (options.defaults) { + object.leadingComments = ""; + object.trailingComments = ""; + } + if (message.path && message.path.length) { + object.path = []; + for (var j = 0; j < message.path.length; ++j) + object.path[j] = message.path[j]; + } + if (message.span && message.span.length) { + object.span = []; + for (var j = 0; j < message.span.length; ++j) + object.span[j] = message.span[j]; + } + if (message.leadingComments != null && message.hasOwnProperty("leadingComments")) + object.leadingComments = message.leadingComments; + if (message.trailingComments != null && message.hasOwnProperty("trailingComments")) + object.trailingComments = message.trailingComments; + if (message.leadingDetachedComments && message.leadingDetachedComments.length) { + object.leadingDetachedComments = []; + for (var j = 0; j < message.leadingDetachedComments.length; ++j) + object.leadingDetachedComments[j] = message.leadingDetachedComments[j]; + } + return object; + }; + + /** + * Converts this Location to JSON. + * @function toJSON + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + * @returns {Object.} JSON object + */ + Location.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Location + * @function getTypeUrl + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Location.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.SourceCodeInfo.Location"; + }; + + return Location; + })(); + + return SourceCodeInfo; + })(); + + protobuf.GeneratedCodeInfo = (function() { + + /** + * Properties of a GeneratedCodeInfo. + * @memberof google.protobuf + * @interface IGeneratedCodeInfo + * @property {Array.|null} [annotation] GeneratedCodeInfo annotation + */ + + /** + * Constructs a new GeneratedCodeInfo. + * @memberof google.protobuf + * @classdesc Represents a GeneratedCodeInfo. + * @implements IGeneratedCodeInfo + * @constructor + * @param {google.protobuf.IGeneratedCodeInfo=} [properties] Properties to set + */ + function GeneratedCodeInfo(properties) { + this.annotation = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GeneratedCodeInfo annotation. + * @member {Array.} annotation + * @memberof google.protobuf.GeneratedCodeInfo + * @instance + */ + GeneratedCodeInfo.prototype.annotation = $util.emptyArray; + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.GeneratedCodeInfo} GeneratedCodeInfo + */ + GeneratedCodeInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.GeneratedCodeInfo) + return object; + var message = new $root.google.protobuf.GeneratedCodeInfo(); + if (object.annotation) { + if (!Array.isArray(object.annotation)) + throw TypeError(".google.protobuf.GeneratedCodeInfo.annotation: array expected"); + message.annotation = []; + for (var i = 0; i < object.annotation.length; ++i) { + if (typeof object.annotation[i] !== "object") + throw TypeError(".google.protobuf.GeneratedCodeInfo.annotation: object expected"); + message.annotation[i] = $root.google.protobuf.GeneratedCodeInfo.Annotation.fromObject(object.annotation[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {google.protobuf.GeneratedCodeInfo} message GeneratedCodeInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GeneratedCodeInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.annotation = []; + if (message.annotation && message.annotation.length) { + object.annotation = []; + for (var j = 0; j < message.annotation.length; ++j) + object.annotation[j] = $root.google.protobuf.GeneratedCodeInfo.Annotation.toObject(message.annotation[j], options); + } + return object; + }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @function toJSON + * @memberof google.protobuf.GeneratedCodeInfo + * @instance + * @returns {Object.} JSON object + */ + GeneratedCodeInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @function getTypeUrl + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GeneratedCodeInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.GeneratedCodeInfo"; + }; + + GeneratedCodeInfo.Annotation = (function() { + + /** + * Properties of an Annotation. + * @memberof google.protobuf.GeneratedCodeInfo + * @interface IAnnotation + * @property {Array.|null} [path] Annotation path + * @property {string|null} [sourceFile] Annotation sourceFile + * @property {number|null} [begin] Annotation begin + * @property {number|null} [end] Annotation end + * @property {google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null} [semantic] Annotation semantic + */ + + /** + * Constructs a new Annotation. + * @memberof google.protobuf.GeneratedCodeInfo + * @classdesc Represents an Annotation. + * @implements IAnnotation + * @constructor + * @param {google.protobuf.GeneratedCodeInfo.IAnnotation=} [properties] Properties to set + */ + function Annotation(properties) { + this.path = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Annotation path. + * @member {Array.} path + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.path = $util.emptyArray; + + /** + * Annotation sourceFile. + * @member {string} sourceFile + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.sourceFile = ""; + + /** + * Annotation begin. + * @member {number} begin + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.begin = 0; + + /** + * Annotation end. + * @member {number} end + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.end = 0; + + /** + * Annotation semantic. + * @member {google.protobuf.GeneratedCodeInfo.Annotation.Semantic} semantic + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.semantic = 0; + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.GeneratedCodeInfo.Annotation} Annotation + */ + Annotation.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.GeneratedCodeInfo.Annotation) + return object; + var message = new $root.google.protobuf.GeneratedCodeInfo.Annotation(); + if (object.path) { + if (!Array.isArray(object.path)) + throw TypeError(".google.protobuf.GeneratedCodeInfo.Annotation.path: array expected"); + message.path = []; + for (var i = 0; i < object.path.length; ++i) + message.path[i] = object.path[i] | 0; + } + if (object.sourceFile != null) + message.sourceFile = String(object.sourceFile); + if (object.begin != null) + message.begin = object.begin | 0; + if (object.end != null) + message.end = object.end | 0; + switch (object.semantic) { + default: + if (typeof object.semantic === "number") { + message.semantic = object.semantic; + break; + } + break; + case "NONE": + case 0: + message.semantic = 0; + break; + case "SET": + case 1: + message.semantic = 1; + break; + case "ALIAS": + case 2: + message.semantic = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {google.protobuf.GeneratedCodeInfo.Annotation} message Annotation + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Annotation.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.path = []; + if (options.defaults) { + object.sourceFile = ""; + object.begin = 0; + object.end = 0; + object.semantic = options.enums === String ? "NONE" : 0; + } + if (message.path && message.path.length) { + object.path = []; + for (var j = 0; j < message.path.length; ++j) + object.path[j] = message.path[j]; + } + if (message.sourceFile != null && message.hasOwnProperty("sourceFile")) + object.sourceFile = message.sourceFile; + if (message.begin != null && message.hasOwnProperty("begin")) + object.begin = message.begin; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + if (message.semantic != null && message.hasOwnProperty("semantic")) + object.semantic = options.enums === String ? $root.google.protobuf.GeneratedCodeInfo.Annotation.Semantic[message.semantic] === undefined ? message.semantic : $root.google.protobuf.GeneratedCodeInfo.Annotation.Semantic[message.semantic] : message.semantic; + return object; + }; + + /** + * Converts this Annotation to JSON. + * @function toJSON + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + * @returns {Object.} JSON object + */ + Annotation.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Annotation + * @function getTypeUrl + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Annotation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.GeneratedCodeInfo.Annotation"; + }; + + /** + * Semantic enum. + * @name google.protobuf.GeneratedCodeInfo.Annotation.Semantic + * @enum {string} + * @property {string} NONE=NONE NONE value + * @property {string} SET=SET SET value + * @property {string} ALIAS=ALIAS ALIAS value + */ + Annotation.Semantic = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "NONE"] = "NONE"; + values[valuesById[1] = "SET"] = "SET"; + values[valuesById[2] = "ALIAS"] = "ALIAS"; + return values; + })(); + + return Annotation; + })(); + + return GeneratedCodeInfo; + })(); + + protobuf.Struct = (function() { + + /** + * Properties of a Struct. + * @memberof google.protobuf + * @interface IStruct + * @property {Object.|null} [fields] Struct fields + */ + + /** + * Constructs a new Struct. + * @memberof google.protobuf + * @classdesc Represents a Struct. + * @implements IStruct + * @constructor + * @param {google.protobuf.IStruct=} [properties] Properties to set + */ + function Struct(properties) { + this.fields = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Struct fields. + * @member {Object.} fields + * @memberof google.protobuf.Struct + * @instance + */ + Struct.prototype.fields = $util.emptyObject; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Struct + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Struct} Struct + */ + Struct.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Struct) + return object; + var message = new $root.google.protobuf.Struct(); + if (object.fields) { + if (typeof object.fields !== "object") + throw TypeError(".google.protobuf.Struct.fields: object expected"); + message.fields = {}; + for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { + if (typeof object.fields[keys[i]] !== "object") + throw TypeError(".google.protobuf.Struct.fields: object expected"); + message.fields[keys[i]] = $root.google.protobuf.Value.fromObject(object.fields[keys[i]]); + } + } + return message; + }; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Struct + * @static + * @param {google.protobuf.Struct} message Struct + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Struct.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.fields = {}; + var keys2; + if (message.fields && (keys2 = Object.keys(message.fields)).length) { + object.fields = {}; + for (var j = 0; j < keys2.length; ++j) + object.fields[keys2[j]] = $root.google.protobuf.Value.toObject(message.fields[keys2[j]], options); + } + return object; + }; + + /** + * Converts this Struct to JSON. + * @function toJSON + * @memberof google.protobuf.Struct + * @instance + * @returns {Object.} JSON object + */ + Struct.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Struct + * @function getTypeUrl + * @memberof google.protobuf.Struct + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Struct.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Struct"; + }; + + return Struct; + })(); + + protobuf.Value = (function() { + + /** + * Properties of a Value. + * @memberof google.protobuf + * @interface IValue + * @property {google.protobuf.NullValue|null} [nullValue] Value nullValue + * @property {number|null} [numberValue] Value numberValue + * @property {string|null} [stringValue] Value stringValue + * @property {boolean|null} [boolValue] Value boolValue + * @property {google.protobuf.IStruct|null} [structValue] Value structValue + * @property {google.protobuf.IListValue|null} [listValue] Value listValue + */ + + /** + * Constructs a new Value. + * @memberof google.protobuf + * @classdesc Represents a Value. + * @implements IValue + * @constructor + * @param {google.protobuf.IValue=} [properties] Properties to set + */ + function Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Value nullValue. + * @member {google.protobuf.NullValue|null|undefined} nullValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.nullValue = null; + + /** + * Value numberValue. + * @member {number|null|undefined} numberValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.numberValue = null; + + /** + * Value stringValue. + * @member {string|null|undefined} stringValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.stringValue = null; + + /** + * Value boolValue. + * @member {boolean|null|undefined} boolValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.boolValue = null; + + /** + * Value structValue. + * @member {google.protobuf.IStruct|null|undefined} structValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.structValue = null; + + /** + * Value listValue. + * @member {google.protobuf.IListValue|null|undefined} listValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.listValue = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Value kind. + * @member {"nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"|undefined} kind + * @memberof google.protobuf.Value + * @instance + */ + Object.defineProperty(Value.prototype, "kind", { + get: $util.oneOfGetter($oneOfFields = ["nullValue", "numberValue", "stringValue", "boolValue", "structValue", "listValue"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Value + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Value} Value + */ + Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Value) + return object; + var message = new $root.google.protobuf.Value(); + switch (object.nullValue) { + default: + if (typeof object.nullValue === "number") { + message.nullValue = object.nullValue; + break; + } + break; + case "NULL_VALUE": + case 0: + message.nullValue = 0; + break; + } + if (object.numberValue != null) + message.numberValue = Number(object.numberValue); + if (object.stringValue != null) + message.stringValue = String(object.stringValue); + if (object.boolValue != null) + message.boolValue = Boolean(object.boolValue); + if (object.structValue != null) { + if (typeof object.structValue !== "object") + throw TypeError(".google.protobuf.Value.structValue: object expected"); + message.structValue = $root.google.protobuf.Struct.fromObject(object.structValue); + } + if (object.listValue != null) { + if (typeof object.listValue !== "object") + throw TypeError(".google.protobuf.Value.listValue: object expected"); + message.listValue = $root.google.protobuf.ListValue.fromObject(object.listValue); + } + return message; + }; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Value + * @static + * @param {google.protobuf.Value} message Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.nullValue != null && message.hasOwnProperty("nullValue")) { + object.nullValue = options.enums === String ? $root.google.protobuf.NullValue[message.nullValue] === undefined ? message.nullValue : $root.google.protobuf.NullValue[message.nullValue] : message.nullValue; + if (options.oneofs) + object.kind = "nullValue"; + } + if (message.numberValue != null && message.hasOwnProperty("numberValue")) { + object.numberValue = options.json && !isFinite(message.numberValue) ? String(message.numberValue) : message.numberValue; + if (options.oneofs) + object.kind = "numberValue"; + } + if (message.stringValue != null && message.hasOwnProperty("stringValue")) { + object.stringValue = message.stringValue; + if (options.oneofs) + object.kind = "stringValue"; + } + if (message.boolValue != null && message.hasOwnProperty("boolValue")) { + object.boolValue = message.boolValue; + if (options.oneofs) + object.kind = "boolValue"; + } + if (message.structValue != null && message.hasOwnProperty("structValue")) { + object.structValue = $root.google.protobuf.Struct.toObject(message.structValue, options); + if (options.oneofs) + object.kind = "structValue"; + } + if (message.listValue != null && message.hasOwnProperty("listValue")) { + object.listValue = $root.google.protobuf.ListValue.toObject(message.listValue, options); + if (options.oneofs) + object.kind = "listValue"; + } + return object; + }; + + /** + * Converts this Value to JSON. + * @function toJSON + * @memberof google.protobuf.Value + * @instance + * @returns {Object.} JSON object + */ + Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Value + * @function getTypeUrl + * @memberof google.protobuf.Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Value"; + }; + + return Value; + })(); + + /** + * NullValue enum. + * @name google.protobuf.NullValue + * @enum {string} + * @property {string} NULL_VALUE=NULL_VALUE NULL_VALUE value + */ + protobuf.NullValue = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "NULL_VALUE"] = "NULL_VALUE"; + return values; + })(); + + protobuf.ListValue = (function() { + + /** + * Properties of a ListValue. + * @memberof google.protobuf + * @interface IListValue + * @property {Array.|null} [values] ListValue values + */ + + /** + * Constructs a new ListValue. + * @memberof google.protobuf + * @classdesc Represents a ListValue. + * @implements IListValue + * @constructor + * @param {google.protobuf.IListValue=} [properties] Properties to set + */ + function ListValue(properties) { + this.values = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListValue values. + * @member {Array.} values + * @memberof google.protobuf.ListValue + * @instance + */ + ListValue.prototype.values = $util.emptyArray; + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ListValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ListValue} ListValue + */ + ListValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ListValue) + return object; + var message = new $root.google.protobuf.ListValue(); + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".google.protobuf.ListValue.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".google.protobuf.ListValue.values: object expected"); + message.values[i] = $root.google.protobuf.Value.fromObject(object.values[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ListValue + * @static + * @param {google.protobuf.ListValue} message ListValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.values = []; + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.google.protobuf.Value.toObject(message.values[j], options); + } + return object; + }; + + /** + * Converts this ListValue to JSON. + * @function toJSON + * @memberof google.protobuf.ListValue + * @instance + * @returns {Object.} JSON object + */ + ListValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListValue + * @function getTypeUrl + * @memberof google.protobuf.ListValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ListValue"; + }; + + return ListValue; + })(); + + protobuf.Timestamp = (function() { + + /** + * Properties of a Timestamp. + * @memberof google.protobuf + * @interface ITimestamp + * @property {number|string|null} [seconds] Timestamp seconds + * @property {number|null} [nanos] Timestamp nanos + */ + + /** + * Constructs a new Timestamp. + * @memberof google.protobuf + * @classdesc Represents a Timestamp. + * @implements ITimestamp + * @constructor + * @param {google.protobuf.ITimestamp=} [properties] Properties to set + */ + function Timestamp(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Timestamp seconds. + * @member {number|string} seconds + * @memberof google.protobuf.Timestamp + * @instance + */ + Timestamp.prototype.seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Timestamp nanos. + * @member {number} nanos + * @memberof google.protobuf.Timestamp + * @instance + */ + Timestamp.prototype.nanos = 0; + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Timestamp + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Timestamp} Timestamp + */ + Timestamp.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Timestamp) + return object; + var message = new $root.google.protobuf.Timestamp(); + if (object.seconds != null) + if ($util.Long) + (message.seconds = $util.Long.fromValue(object.seconds)).unsigned = false; + else if (typeof object.seconds === "string") + message.seconds = parseInt(object.seconds, 10); + else if (typeof object.seconds === "number") + message.seconds = object.seconds; + else if (typeof object.seconds === "object") + message.seconds = new $util.LongBits(object.seconds.low >>> 0, object.seconds.high >>> 0).toNumber(); + if (object.nanos != null) + message.nanos = object.nanos | 0; + return message; + }; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Timestamp + * @static + * @param {google.protobuf.Timestamp} message Timestamp + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Timestamp.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.seconds = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.seconds = options.longs === String ? "0" : 0; + object.nanos = 0; + } + if (message.seconds != null && message.hasOwnProperty("seconds")) + if (typeof message.seconds === "number") + object.seconds = options.longs === String ? String(message.seconds) : message.seconds; + else + object.seconds = options.longs === String ? $util.Long.prototype.toString.call(message.seconds) : options.longs === Number ? new $util.LongBits(message.seconds.low >>> 0, message.seconds.high >>> 0).toNumber() : message.seconds; + if (message.nanos != null && message.hasOwnProperty("nanos")) + object.nanos = message.nanos; + return object; + }; + + /** + * Converts this Timestamp to JSON. + * @function toJSON + * @memberof google.protobuf.Timestamp + * @instance + * @returns {Object.} JSON object + */ + Timestamp.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Timestamp + * @function getTypeUrl + * @memberof google.protobuf.Timestamp + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Timestamp.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Timestamp"; + }; + + return Timestamp; + })(); + + protobuf.Any = (function() { + + /** + * Properties of an Any. + * @memberof google.protobuf + * @interface IAny + * @property {string|null} [type_url] Any type_url + * @property {Uint8Array|null} [value] Any value + */ + + /** + * Constructs a new Any. + * @memberof google.protobuf + * @classdesc Represents an Any. + * @implements IAny + * @constructor + * @param {google.protobuf.IAny=} [properties] Properties to set + */ + function Any(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Any type_url. + * @member {string} type_url + * @memberof google.protobuf.Any + * @instance + */ + Any.prototype.type_url = ""; + + /** + * Any value. + * @member {Uint8Array} value + * @memberof google.protobuf.Any + * @instance + */ + Any.prototype.value = $util.newBuffer([]); + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Any + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Any} Any + */ + Any.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Any) + return object; + var message = new $root.google.protobuf.Any(); + if (object.type_url != null) + message.type_url = String(object.type_url); + if (object.value != null) + if (typeof object.value === "string") + $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0); + else if (object.value.length >= 0) + message.value = object.value; + return message; + }; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Any + * @static + * @param {google.protobuf.Any} message Any + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Any.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.type_url = ""; + if (options.bytes === String) + object.value = ""; + else { + object.value = []; + if (options.bytes !== Array) + object.value = $util.newBuffer(object.value); + } + } + if (message.type_url != null && message.hasOwnProperty("type_url")) + object.type_url = message.type_url; + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; + return object; + }; + + /** + * Converts this Any to JSON. + * @function toJSON + * @memberof google.protobuf.Any + * @instance + * @returns {Object.} JSON object + */ + Any.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Any + * @function getTypeUrl + * @memberof google.protobuf.Any + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Any.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Any"; + }; + + return Any; + })(); + + protobuf.Duration = (function() { + + /** + * Properties of a Duration. + * @memberof google.protobuf + * @interface IDuration + * @property {number|string|null} [seconds] Duration seconds + * @property {number|null} [nanos] Duration nanos + */ + + /** + * Constructs a new Duration. + * @memberof google.protobuf + * @classdesc Represents a Duration. + * @implements IDuration + * @constructor + * @param {google.protobuf.IDuration=} [properties] Properties to set + */ + function Duration(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Duration seconds. + * @member {number|string} seconds + * @memberof google.protobuf.Duration + * @instance + */ + Duration.prototype.seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Duration nanos. + * @member {number} nanos + * @memberof google.protobuf.Duration + * @instance + */ + Duration.prototype.nanos = 0; + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Duration + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Duration} Duration + */ + Duration.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Duration) + return object; + var message = new $root.google.protobuf.Duration(); + if (object.seconds != null) + if ($util.Long) + (message.seconds = $util.Long.fromValue(object.seconds)).unsigned = false; + else if (typeof object.seconds === "string") + message.seconds = parseInt(object.seconds, 10); + else if (typeof object.seconds === "number") + message.seconds = object.seconds; + else if (typeof object.seconds === "object") + message.seconds = new $util.LongBits(object.seconds.low >>> 0, object.seconds.high >>> 0).toNumber(); + if (object.nanos != null) + message.nanos = object.nanos | 0; + return message; + }; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Duration + * @static + * @param {google.protobuf.Duration} message Duration + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Duration.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.seconds = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.seconds = options.longs === String ? "0" : 0; + object.nanos = 0; + } + if (message.seconds != null && message.hasOwnProperty("seconds")) + if (typeof message.seconds === "number") + object.seconds = options.longs === String ? String(message.seconds) : message.seconds; + else + object.seconds = options.longs === String ? $util.Long.prototype.toString.call(message.seconds) : options.longs === Number ? new $util.LongBits(message.seconds.low >>> 0, message.seconds.high >>> 0).toNumber() : message.seconds; + if (message.nanos != null && message.hasOwnProperty("nanos")) + object.nanos = message.nanos; + return object; + }; + + /** + * Converts this Duration to JSON. + * @function toJSON + * @memberof google.protobuf.Duration + * @instance + * @returns {Object.} JSON object + */ + Duration.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Duration + * @function getTypeUrl + * @memberof google.protobuf.Duration + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Duration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Duration"; + }; + + return Duration; + })(); + + protobuf.DoubleValue = (function() { + + /** + * Properties of a DoubleValue. + * @memberof google.protobuf + * @interface IDoubleValue + * @property {number|null} [value] DoubleValue value + */ + + /** + * Constructs a new DoubleValue. + * @memberof google.protobuf + * @classdesc Represents a DoubleValue. + * @implements IDoubleValue + * @constructor + * @param {google.protobuf.IDoubleValue=} [properties] Properties to set + */ + function DoubleValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DoubleValue value. + * @member {number} value + * @memberof google.protobuf.DoubleValue + * @instance + */ + DoubleValue.prototype.value = 0; + + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DoubleValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DoubleValue} DoubleValue + */ + DoubleValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DoubleValue) + return object; + var message = new $root.google.protobuf.DoubleValue(); + if (object.value != null) + message.value = Number(object.value); + return message; + }; + + /** + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.DoubleValue + * @static + * @param {google.protobuf.DoubleValue} message DoubleValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DoubleValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = 0; + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value; + return object; + }; + + /** + * Converts this DoubleValue to JSON. + * @function toJSON + * @memberof google.protobuf.DoubleValue + * @instance + * @returns {Object.} JSON object + */ + DoubleValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DoubleValue + * @function getTypeUrl + * @memberof google.protobuf.DoubleValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DoubleValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.DoubleValue"; + }; + + return DoubleValue; + })(); + + protobuf.FloatValue = (function() { + + /** + * Properties of a FloatValue. + * @memberof google.protobuf + * @interface IFloatValue + * @property {number|null} [value] FloatValue value + */ + + /** + * Constructs a new FloatValue. + * @memberof google.protobuf + * @classdesc Represents a FloatValue. + * @implements IFloatValue + * @constructor + * @param {google.protobuf.IFloatValue=} [properties] Properties to set + */ + function FloatValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FloatValue value. + * @member {number} value + * @memberof google.protobuf.FloatValue + * @instance + */ + FloatValue.prototype.value = 0; + + /** + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FloatValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FloatValue} FloatValue + */ + FloatValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FloatValue) + return object; + var message = new $root.google.protobuf.FloatValue(); + if (object.value != null) + message.value = Number(object.value); + return message; + }; + + /** + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FloatValue + * @static + * @param {google.protobuf.FloatValue} message FloatValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FloatValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = 0; + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value; + return object; + }; + + /** + * Converts this FloatValue to JSON. + * @function toJSON + * @memberof google.protobuf.FloatValue + * @instance + * @returns {Object.} JSON object + */ + FloatValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FloatValue + * @function getTypeUrl + * @memberof google.protobuf.FloatValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FloatValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FloatValue"; + }; + + return FloatValue; + })(); + + protobuf.Int64Value = (function() { + + /** + * Properties of an Int64Value. + * @memberof google.protobuf + * @interface IInt64Value + * @property {number|string|null} [value] Int64Value value + */ + + /** + * Constructs a new Int64Value. + * @memberof google.protobuf + * @classdesc Represents an Int64Value. + * @implements IInt64Value + * @constructor + * @param {google.protobuf.IInt64Value=} [properties] Properties to set + */ + function Int64Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Int64Value value. + * @member {number|string} value + * @memberof google.protobuf.Int64Value + * @instance + */ + Int64Value.prototype.value = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Int64Value + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Int64Value} Int64Value + */ + Int64Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Int64Value) + return object; + var message = new $root.google.protobuf.Int64Value(); + if (object.value != null) + if ($util.Long) + (message.value = $util.Long.fromValue(object.value)).unsigned = false; + else if (typeof object.value === "string") + message.value = parseInt(object.value, 10); + else if (typeof object.value === "number") + message.value = object.value; + else if (typeof object.value === "object") + message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Int64Value + * @static + * @param {google.protobuf.Int64Value} message Int64Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Int64Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.value = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.value = options.longs === String ? "0" : 0; + if (message.value != null && message.hasOwnProperty("value")) + if (typeof message.value === "number") + object.value = options.longs === String ? String(message.value) : message.value; + else + object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber() : message.value; + return object; + }; + + /** + * Converts this Int64Value to JSON. + * @function toJSON + * @memberof google.protobuf.Int64Value + * @instance + * @returns {Object.} JSON object + */ + Int64Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Int64Value + * @function getTypeUrl + * @memberof google.protobuf.Int64Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Int64Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Int64Value"; + }; + + return Int64Value; + })(); + + protobuf.UInt64Value = (function() { + + /** + * Properties of a UInt64Value. + * @memberof google.protobuf + * @interface IUInt64Value + * @property {number|string|null} [value] UInt64Value value + */ + + /** + * Constructs a new UInt64Value. + * @memberof google.protobuf + * @classdesc Represents a UInt64Value. + * @implements IUInt64Value + * @constructor + * @param {google.protobuf.IUInt64Value=} [properties] Properties to set + */ + function UInt64Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UInt64Value value. + * @member {number|string} value + * @memberof google.protobuf.UInt64Value + * @instance + */ + UInt64Value.prototype.value = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.UInt64Value + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.UInt64Value} UInt64Value + */ + UInt64Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UInt64Value) + return object; + var message = new $root.google.protobuf.UInt64Value(); + if (object.value != null) + if ($util.Long) + (message.value = $util.Long.fromValue(object.value)).unsigned = true; + else if (typeof object.value === "string") + message.value = parseInt(object.value, 10); + else if (typeof object.value === "number") + message.value = object.value; + else if (typeof object.value === "object") + message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(true); + return message; + }; + + /** + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.UInt64Value + * @static + * @param {google.protobuf.UInt64Value} message UInt64Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UInt64Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.value = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.value = options.longs === String ? "0" : 0; + if (message.value != null && message.hasOwnProperty("value")) + if (typeof message.value === "number") + object.value = options.longs === String ? String(message.value) : message.value; + else + object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber(true) : message.value; + return object; + }; + + /** + * Converts this UInt64Value to JSON. + * @function toJSON + * @memberof google.protobuf.UInt64Value + * @instance + * @returns {Object.} JSON object + */ + UInt64Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UInt64Value + * @function getTypeUrl + * @memberof google.protobuf.UInt64Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UInt64Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.UInt64Value"; + }; + + return UInt64Value; + })(); + + protobuf.Int32Value = (function() { + + /** + * Properties of an Int32Value. + * @memberof google.protobuf + * @interface IInt32Value + * @property {number|null} [value] Int32Value value + */ + + /** + * Constructs a new Int32Value. + * @memberof google.protobuf + * @classdesc Represents an Int32Value. + * @implements IInt32Value + * @constructor + * @param {google.protobuf.IInt32Value=} [properties] Properties to set + */ + function Int32Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Int32Value value. + * @member {number} value + * @memberof google.protobuf.Int32Value + * @instance + */ + Int32Value.prototype.value = 0; + + /** + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Int32Value + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Int32Value} Int32Value + */ + Int32Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Int32Value) + return object; + var message = new $root.google.protobuf.Int32Value(); + if (object.value != null) + message.value = object.value | 0; + return message; + }; + + /** + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Int32Value + * @static + * @param {google.protobuf.Int32Value} message Int32Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Int32Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = 0; + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + return object; + }; + + /** + * Converts this Int32Value to JSON. + * @function toJSON + * @memberof google.protobuf.Int32Value + * @instance + * @returns {Object.} JSON object + */ + Int32Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Int32Value + * @function getTypeUrl + * @memberof google.protobuf.Int32Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Int32Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Int32Value"; + }; + + return Int32Value; + })(); + + protobuf.UInt32Value = (function() { + + /** + * Properties of a UInt32Value. + * @memberof google.protobuf + * @interface IUInt32Value + * @property {number|null} [value] UInt32Value value + */ + + /** + * Constructs a new UInt32Value. + * @memberof google.protobuf + * @classdesc Represents a UInt32Value. + * @implements IUInt32Value + * @constructor + * @param {google.protobuf.IUInt32Value=} [properties] Properties to set + */ + function UInt32Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UInt32Value value. + * @member {number} value + * @memberof google.protobuf.UInt32Value + * @instance + */ + UInt32Value.prototype.value = 0; + + /** + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.UInt32Value + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.UInt32Value} UInt32Value + */ + UInt32Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UInt32Value) + return object; + var message = new $root.google.protobuf.UInt32Value(); + if (object.value != null) + message.value = object.value >>> 0; + return message; + }; + + /** + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.UInt32Value + * @static + * @param {google.protobuf.UInt32Value} message UInt32Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UInt32Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = 0; + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + return object; + }; + + /** + * Converts this UInt32Value to JSON. + * @function toJSON + * @memberof google.protobuf.UInt32Value + * @instance + * @returns {Object.} JSON object + */ + UInt32Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UInt32Value + * @function getTypeUrl + * @memberof google.protobuf.UInt32Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UInt32Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.UInt32Value"; + }; + + return UInt32Value; + })(); + + protobuf.BoolValue = (function() { + + /** + * Properties of a BoolValue. + * @memberof google.protobuf + * @interface IBoolValue + * @property {boolean|null} [value] BoolValue value + */ + + /** + * Constructs a new BoolValue. + * @memberof google.protobuf + * @classdesc Represents a BoolValue. + * @implements IBoolValue + * @constructor + * @param {google.protobuf.IBoolValue=} [properties] Properties to set + */ + function BoolValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BoolValue value. + * @member {boolean} value + * @memberof google.protobuf.BoolValue + * @instance + */ + BoolValue.prototype.value = false; + + /** + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.BoolValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.BoolValue} BoolValue + */ + BoolValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.BoolValue) + return object; + var message = new $root.google.protobuf.BoolValue(); + if (object.value != null) + message.value = Boolean(object.value); + return message; + }; + + /** + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.BoolValue + * @static + * @param {google.protobuf.BoolValue} message BoolValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BoolValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = false; + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + return object; + }; + + /** + * Converts this BoolValue to JSON. + * @function toJSON + * @memberof google.protobuf.BoolValue + * @instance + * @returns {Object.} JSON object + */ + BoolValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BoolValue + * @function getTypeUrl + * @memberof google.protobuf.BoolValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BoolValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.BoolValue"; + }; + + return BoolValue; + })(); + + protobuf.StringValue = (function() { + + /** + * Properties of a StringValue. + * @memberof google.protobuf + * @interface IStringValue + * @property {string|null} [value] StringValue value + */ + + /** + * Constructs a new StringValue. + * @memberof google.protobuf + * @classdesc Represents a StringValue. + * @implements IStringValue + * @constructor + * @param {google.protobuf.IStringValue=} [properties] Properties to set + */ + function StringValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * StringValue value. + * @member {string} value + * @memberof google.protobuf.StringValue + * @instance + */ + StringValue.prototype.value = ""; + + /** + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.StringValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.StringValue} StringValue + */ + StringValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.StringValue) + return object; + var message = new $root.google.protobuf.StringValue(); + if (object.value != null) + message.value = String(object.value); + return message; + }; + + /** + * Creates a plain object from a StringValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.StringValue + * @static + * @param {google.protobuf.StringValue} message StringValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + StringValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = ""; + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + return object; + }; + + /** + * Converts this StringValue to JSON. + * @function toJSON + * @memberof google.protobuf.StringValue + * @instance + * @returns {Object.} JSON object + */ + StringValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for StringValue + * @function getTypeUrl + * @memberof google.protobuf.StringValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + StringValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.StringValue"; + }; + + return StringValue; + })(); + + protobuf.BytesValue = (function() { + + /** + * Properties of a BytesValue. + * @memberof google.protobuf + * @interface IBytesValue + * @property {Uint8Array|null} [value] BytesValue value + */ + + /** + * Constructs a new BytesValue. + * @memberof google.protobuf + * @classdesc Represents a BytesValue. + * @implements IBytesValue + * @constructor + * @param {google.protobuf.IBytesValue=} [properties] Properties to set + */ + function BytesValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BytesValue value. + * @member {Uint8Array} value + * @memberof google.protobuf.BytesValue + * @instance + */ + BytesValue.prototype.value = $util.newBuffer([]); + + /** + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.BytesValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.BytesValue} BytesValue + */ + BytesValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.BytesValue) + return object; + var message = new $root.google.protobuf.BytesValue(); + if (object.value != null) + if (typeof object.value === "string") + $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0); + else if (object.value.length >= 0) + message.value = object.value; + return message; + }; + + /** + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.BytesValue + * @static + * @param {google.protobuf.BytesValue} message BytesValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BytesValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if (options.bytes === String) + object.value = ""; + else { + object.value = []; + if (options.bytes !== Array) + object.value = $util.newBuffer(object.value); + } + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; + return object; + }; + + /** + * Converts this BytesValue to JSON. + * @function toJSON + * @memberof google.protobuf.BytesValue + * @instance + * @returns {Object.} JSON object + */ + BytesValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BytesValue + * @function getTypeUrl + * @memberof google.protobuf.BytesValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BytesValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.BytesValue"; + }; + + return BytesValue; + })(); + + protobuf.Empty = (function() { + + /** + * Properties of an Empty. + * @memberof google.protobuf + * @interface IEmpty + */ + + /** + * Constructs a new Empty. + * @memberof google.protobuf + * @classdesc Represents an Empty. + * @implements IEmpty + * @constructor + * @param {google.protobuf.IEmpty=} [properties] Properties to set + */ + function Empty(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Empty + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Empty} Empty + */ + Empty.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Empty) + return object; + return new $root.google.protobuf.Empty(); + }; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Empty + * @static + * @param {google.protobuf.Empty} message Empty + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Empty.toObject = function toObject() { + return {}; + }; + + /** + * Converts this Empty to JSON. + * @function toJSON + * @memberof google.protobuf.Empty + * @instance + * @returns {Object.} JSON object + */ + Empty.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Empty + * @function getTypeUrl + * @memberof google.protobuf.Empty + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Empty.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Empty"; + }; + + return Empty; + })(); + + protobuf.FieldMask = (function() { + + /** + * Properties of a FieldMask. + * @memberof google.protobuf + * @interface IFieldMask + * @property {Array.|null} [paths] FieldMask paths + */ + + /** + * Constructs a new FieldMask. + * @memberof google.protobuf + * @classdesc Represents a FieldMask. + * @implements IFieldMask + * @constructor + * @param {google.protobuf.IFieldMask=} [properties] Properties to set + */ + function FieldMask(properties) { + this.paths = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldMask paths. + * @member {Array.} paths + * @memberof google.protobuf.FieldMask + * @instance + */ + FieldMask.prototype.paths = $util.emptyArray; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldMask + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldMask} FieldMask + */ + FieldMask.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldMask) + return object; + var message = new $root.google.protobuf.FieldMask(); + if (object.paths) { + if (!Array.isArray(object.paths)) + throw TypeError(".google.protobuf.FieldMask.paths: array expected"); + message.paths = []; + for (var i = 0; i < object.paths.length; ++i) + message.paths[i] = String(object.paths[i]); + } + return message; + }; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldMask + * @static + * @param {google.protobuf.FieldMask} message FieldMask + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldMask.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.paths = []; + if (message.paths && message.paths.length) { + object.paths = []; + for (var j = 0; j < message.paths.length; ++j) + object.paths[j] = message.paths[j]; + } + return object; + }; + + /** + * Converts this FieldMask to JSON. + * @function toJSON + * @memberof google.protobuf.FieldMask + * @instance + * @returns {Object.} JSON object + */ + FieldMask.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldMask + * @function getTypeUrl + * @memberof google.protobuf.FieldMask + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldMask.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldMask"; + }; + + return FieldMask; + })(); + + return protobuf; + })(); + + google.type = (function() { + + /** + * Namespace type. + * @memberof google + * @namespace + */ + var type = {}; + + type.LatLng = (function() { + + /** + * Properties of a LatLng. + * @memberof google.type + * @interface ILatLng + * @property {number|null} [latitude] LatLng latitude + * @property {number|null} [longitude] LatLng longitude + */ + + /** + * Constructs a new LatLng. + * @memberof google.type + * @classdesc Represents a LatLng. + * @implements ILatLng + * @constructor + * @param {google.type.ILatLng=} [properties] Properties to set + */ + function LatLng(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * LatLng latitude. + * @member {number} latitude + * @memberof google.type.LatLng + * @instance + */ + LatLng.prototype.latitude = 0; + + /** + * LatLng longitude. + * @member {number} longitude + * @memberof google.type.LatLng + * @instance + */ + LatLng.prototype.longitude = 0; + + /** + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.type.LatLng + * @static + * @param {Object.} object Plain object + * @returns {google.type.LatLng} LatLng + */ + LatLng.fromObject = function fromObject(object) { + if (object instanceof $root.google.type.LatLng) + return object; + var message = new $root.google.type.LatLng(); + if (object.latitude != null) + message.latitude = Number(object.latitude); + if (object.longitude != null) + message.longitude = Number(object.longitude); + return message; + }; + + /** + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @function toObject + * @memberof google.type.LatLng + * @static + * @param {google.type.LatLng} message LatLng + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + LatLng.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.latitude = 0; + object.longitude = 0; + } + if (message.latitude != null && message.hasOwnProperty("latitude")) + object.latitude = options.json && !isFinite(message.latitude) ? String(message.latitude) : message.latitude; + if (message.longitude != null && message.hasOwnProperty("longitude")) + object.longitude = options.json && !isFinite(message.longitude) ? String(message.longitude) : message.longitude; + return object; + }; + + /** + * Converts this LatLng to JSON. + * @function toJSON + * @memberof google.type.LatLng + * @instance + * @returns {Object.} JSON object + */ + LatLng.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for LatLng + * @function getTypeUrl + * @memberof google.type.LatLng + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + LatLng.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.type.LatLng"; + }; + + return LatLng; + })(); + + /** + * DayOfWeek enum. + * @name google.type.DayOfWeek + * @enum {string} + * @property {string} DAY_OF_WEEK_UNSPECIFIED=DAY_OF_WEEK_UNSPECIFIED DAY_OF_WEEK_UNSPECIFIED value + * @property {string} MONDAY=MONDAY MONDAY value + * @property {string} TUESDAY=TUESDAY TUESDAY value + * @property {string} WEDNESDAY=WEDNESDAY WEDNESDAY value + * @property {string} THURSDAY=THURSDAY THURSDAY value + * @property {string} FRIDAY=FRIDAY FRIDAY value + * @property {string} SATURDAY=SATURDAY SATURDAY value + * @property {string} SUNDAY=SUNDAY SUNDAY value + */ + type.DayOfWeek = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DAY_OF_WEEK_UNSPECIFIED"] = "DAY_OF_WEEK_UNSPECIFIED"; + values[valuesById[1] = "MONDAY"] = "MONDAY"; + values[valuesById[2] = "TUESDAY"] = "TUESDAY"; + values[valuesById[3] = "WEDNESDAY"] = "WEDNESDAY"; + values[valuesById[4] = "THURSDAY"] = "THURSDAY"; + values[valuesById[5] = "FRIDAY"] = "FRIDAY"; + values[valuesById[6] = "SATURDAY"] = "SATURDAY"; + values[valuesById[7] = "SUNDAY"] = "SUNDAY"; + return values; + })(); + + return type; + })(); + + google.rpc = (function() { + + /** + * Namespace rpc. + * @memberof google + * @namespace + */ + var rpc = {}; + + rpc.Status = (function() { + + /** + * Properties of a Status. + * @memberof google.rpc + * @interface IStatus + * @property {number|null} [code] Status code + * @property {string|null} [message] Status message + * @property {Array.|null} [details] Status details + */ + + /** + * Constructs a new Status. + * @memberof google.rpc + * @classdesc Represents a Status. + * @implements IStatus + * @constructor + * @param {google.rpc.IStatus=} [properties] Properties to set + */ + function Status(properties) { + this.details = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Status code. + * @member {number} code + * @memberof google.rpc.Status + * @instance + */ + Status.prototype.code = 0; + + /** + * Status message. + * @member {string} message + * @memberof google.rpc.Status + * @instance + */ + Status.prototype.message = ""; + + /** + * Status details. + * @member {Array.} details + * @memberof google.rpc.Status + * @instance + */ + Status.prototype.details = $util.emptyArray; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.Status + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.Status} Status + */ + Status.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.Status) + return object; + var message = new $root.google.rpc.Status(); + if (object.code != null) + message.code = object.code | 0; + if (object.message != null) + message.message = String(object.message); + if (object.details) { + if (!Array.isArray(object.details)) + throw TypeError(".google.rpc.Status.details: array expected"); + message.details = []; + for (var i = 0; i < object.details.length; ++i) { + if (typeof object.details[i] !== "object") + throw TypeError(".google.rpc.Status.details: object expected"); + message.details[i] = $root.google.protobuf.Any.fromObject(object.details[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.Status + * @static + * @param {google.rpc.Status} message Status + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Status.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.details = []; + if (options.defaults) { + object.code = 0; + object.message = ""; + } + if (message.code != null && message.hasOwnProperty("code")) + object.code = message.code; + if (message.message != null && message.hasOwnProperty("message")) + object.message = message.message; + if (message.details && message.details.length) { + object.details = []; + for (var j = 0; j < message.details.length; ++j) + object.details[j] = $root.google.protobuf.Any.toObject(message.details[j], options); + } + return object; + }; + + /** + * Converts this Status to JSON. + * @function toJSON + * @memberof google.rpc.Status + * @instance + * @returns {Object.} JSON object + */ + Status.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Status + * @function getTypeUrl + * @memberof google.rpc.Status + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Status.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.Status"; + }; + + return Status; + })(); + + return rpc; + })(); + + google.longrunning = (function() { + + /** + * Namespace longrunning. + * @memberof google + * @namespace + */ + var longrunning = {}; + + longrunning.Operations = (function() { + + /** + * Constructs a new Operations service. + * @memberof google.longrunning + * @classdesc Represents an Operations + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function Operations(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (Operations.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = Operations; + + /** + * Callback as used by {@link google.longrunning.Operations#listOperations}. + * @memberof google.longrunning.Operations + * @typedef ListOperationsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.ListOperationsResponse} [response] ListOperationsResponse + */ + + /** + * Calls ListOperations. + * @function listOperations + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IListOperationsRequest} request ListOperationsRequest message or plain object + * @param {google.longrunning.Operations.ListOperationsCallback} callback Node-style callback called with the error, if any, and ListOperationsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.listOperations = function listOperations(request, callback) { + return this.rpcCall(listOperations, $root.google.longrunning.ListOperationsRequest, $root.google.longrunning.ListOperationsResponse, request, callback); + }, "name", { value: "ListOperations" }); + + /** + * Calls ListOperations. + * @function listOperations + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IListOperationsRequest} request ListOperationsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.longrunning.Operations#getOperation}. + * @memberof google.longrunning.Operations + * @typedef GetOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls GetOperation. + * @function getOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IGetOperationRequest} request GetOperationRequest message or plain object + * @param {google.longrunning.Operations.GetOperationCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.getOperation = function getOperation(request, callback) { + return this.rpcCall(getOperation, $root.google.longrunning.GetOperationRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "GetOperation" }); + + /** + * Calls GetOperation. + * @function getOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IGetOperationRequest} request GetOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.longrunning.Operations#deleteOperation}. + * @memberof google.longrunning.Operations + * @typedef DeleteOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteOperation. + * @function deleteOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IDeleteOperationRequest} request DeleteOperationRequest message or plain object + * @param {google.longrunning.Operations.DeleteOperationCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.deleteOperation = function deleteOperation(request, callback) { + return this.rpcCall(deleteOperation, $root.google.longrunning.DeleteOperationRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteOperation" }); + + /** + * Calls DeleteOperation. + * @function deleteOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IDeleteOperationRequest} request DeleteOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.longrunning.Operations#cancelOperation}. + * @memberof google.longrunning.Operations + * @typedef CancelOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls CancelOperation. + * @function cancelOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.ICancelOperationRequest} request CancelOperationRequest message or plain object + * @param {google.longrunning.Operations.CancelOperationCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.cancelOperation = function cancelOperation(request, callback) { + return this.rpcCall(cancelOperation, $root.google.longrunning.CancelOperationRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "CancelOperation" }); + + /** + * Calls CancelOperation. + * @function cancelOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.ICancelOperationRequest} request CancelOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.longrunning.Operations#waitOperation}. + * @memberof google.longrunning.Operations + * @typedef WaitOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls WaitOperation. + * @function waitOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IWaitOperationRequest} request WaitOperationRequest message or plain object + * @param {google.longrunning.Operations.WaitOperationCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.waitOperation = function waitOperation(request, callback) { + return this.rpcCall(waitOperation, $root.google.longrunning.WaitOperationRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "WaitOperation" }); + + /** + * Calls WaitOperation. + * @function waitOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IWaitOperationRequest} request WaitOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return Operations; + })(); + + longrunning.Operation = (function() { + + /** + * Properties of an Operation. + * @memberof google.longrunning + * @interface IOperation + * @property {string|null} [name] Operation name + * @property {google.protobuf.IAny|null} [metadata] Operation metadata + * @property {boolean|null} [done] Operation done + * @property {google.rpc.IStatus|null} [error] Operation error + * @property {google.protobuf.IAny|null} [response] Operation response + */ + + /** + * Constructs a new Operation. + * @memberof google.longrunning + * @classdesc Represents an Operation. + * @implements IOperation + * @constructor + * @param {google.longrunning.IOperation=} [properties] Properties to set + */ + function Operation(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Operation name. + * @member {string} name + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.name = ""; + + /** + * Operation metadata. + * @member {google.protobuf.IAny|null|undefined} metadata + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.metadata = null; + + /** + * Operation done. + * @member {boolean} done + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.done = false; + + /** + * Operation error. + * @member {google.rpc.IStatus|null|undefined} error + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.error = null; + + /** + * Operation response. + * @member {google.protobuf.IAny|null|undefined} response + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.response = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Operation result. + * @member {"error"|"response"|undefined} result + * @memberof google.longrunning.Operation + * @instance + */ + Object.defineProperty(Operation.prototype, "result", { + get: $util.oneOfGetter($oneOfFields = ["error", "response"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.Operation + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.Operation} Operation + */ + Operation.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.Operation) + return object; + var message = new $root.google.longrunning.Operation(); + if (object.name != null) + message.name = String(object.name); + if (object.metadata != null) { + if (typeof object.metadata !== "object") + throw TypeError(".google.longrunning.Operation.metadata: object expected"); + message.metadata = $root.google.protobuf.Any.fromObject(object.metadata); + } + if (object.done != null) + message.done = Boolean(object.done); + if (object.error != null) { + if (typeof object.error !== "object") + throw TypeError(".google.longrunning.Operation.error: object expected"); + message.error = $root.google.rpc.Status.fromObject(object.error); + } + if (object.response != null) { + if (typeof object.response !== "object") + throw TypeError(".google.longrunning.Operation.response: object expected"); + message.response = $root.google.protobuf.Any.fromObject(object.response); + } + return message; + }; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.Operation + * @static + * @param {google.longrunning.Operation} message Operation + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Operation.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.metadata = null; + object.done = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.metadata != null && message.hasOwnProperty("metadata")) + object.metadata = $root.google.protobuf.Any.toObject(message.metadata, options); + if (message.done != null && message.hasOwnProperty("done")) + object.done = message.done; + if (message.error != null && message.hasOwnProperty("error")) { + object.error = $root.google.rpc.Status.toObject(message.error, options); + if (options.oneofs) + object.result = "error"; + } + if (message.response != null && message.hasOwnProperty("response")) { + object.response = $root.google.protobuf.Any.toObject(message.response, options); + if (options.oneofs) + object.result = "response"; + } + return object; + }; + + /** + * Converts this Operation to JSON. + * @function toJSON + * @memberof google.longrunning.Operation + * @instance + * @returns {Object.} JSON object + */ + Operation.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Operation + * @function getTypeUrl + * @memberof google.longrunning.Operation + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Operation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.Operation"; + }; + + return Operation; + })(); + + longrunning.GetOperationRequest = (function() { + + /** + * Properties of a GetOperationRequest. + * @memberof google.longrunning + * @interface IGetOperationRequest + * @property {string|null} [name] GetOperationRequest name + */ + + /** + * Constructs a new GetOperationRequest. + * @memberof google.longrunning + * @classdesc Represents a GetOperationRequest. + * @implements IGetOperationRequest + * @constructor + * @param {google.longrunning.IGetOperationRequest=} [properties] Properties to set + */ + function GetOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetOperationRequest name. + * @member {string} name + * @memberof google.longrunning.GetOperationRequest + * @instance + */ + GetOperationRequest.prototype.name = ""; + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.GetOperationRequest} GetOperationRequest + */ + GetOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.GetOperationRequest) + return object; + var message = new $root.google.longrunning.GetOperationRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {google.longrunning.GetOperationRequest} message GetOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetOperationRequest to JSON. + * @function toJSON + * @memberof google.longrunning.GetOperationRequest + * @instance + * @returns {Object.} JSON object + */ + GetOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetOperationRequest + * @function getTypeUrl + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.GetOperationRequest"; + }; + + return GetOperationRequest; + })(); + + longrunning.ListOperationsRequest = (function() { + + /** + * Properties of a ListOperationsRequest. + * @memberof google.longrunning + * @interface IListOperationsRequest + * @property {string|null} [name] ListOperationsRequest name + * @property {string|null} [filter] ListOperationsRequest filter + * @property {number|null} [pageSize] ListOperationsRequest pageSize + * @property {string|null} [pageToken] ListOperationsRequest pageToken + * @property {boolean|null} [returnPartialSuccess] ListOperationsRequest returnPartialSuccess + */ + + /** + * Constructs a new ListOperationsRequest. + * @memberof google.longrunning + * @classdesc Represents a ListOperationsRequest. + * @implements IListOperationsRequest + * @constructor + * @param {google.longrunning.IListOperationsRequest=} [properties] Properties to set + */ + function ListOperationsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListOperationsRequest name. + * @member {string} name + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.name = ""; + + /** + * ListOperationsRequest filter. + * @member {string} filter + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.filter = ""; + + /** + * ListOperationsRequest pageSize. + * @member {number} pageSize + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.pageSize = 0; + + /** + * ListOperationsRequest pageToken. + * @member {string} pageToken + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.pageToken = ""; + + /** + * ListOperationsRequest returnPartialSuccess. + * @member {boolean} returnPartialSuccess + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.returnPartialSuccess = false; + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.ListOperationsRequest} ListOperationsRequest + */ + ListOperationsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.ListOperationsRequest) + return object; + var message = new $root.google.longrunning.ListOperationsRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.returnPartialSuccess != null) + message.returnPartialSuccess = Boolean(object.returnPartialSuccess); + return message; + }; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {google.longrunning.ListOperationsRequest} message ListOperationsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListOperationsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + object.name = ""; + object.returnPartialSuccess = false; + } + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) + object.returnPartialSuccess = message.returnPartialSuccess; + return object; + }; + + /** + * Converts this ListOperationsRequest to JSON. + * @function toJSON + * @memberof google.longrunning.ListOperationsRequest + * @instance + * @returns {Object.} JSON object + */ + ListOperationsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListOperationsRequest + * @function getTypeUrl + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListOperationsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.ListOperationsRequest"; + }; + + return ListOperationsRequest; + })(); + + longrunning.ListOperationsResponse = (function() { + + /** + * Properties of a ListOperationsResponse. + * @memberof google.longrunning + * @interface IListOperationsResponse + * @property {Array.|null} [operations] ListOperationsResponse operations + * @property {string|null} [nextPageToken] ListOperationsResponse nextPageToken + * @property {Array.|null} [unreachable] ListOperationsResponse unreachable + */ + + /** + * Constructs a new ListOperationsResponse. + * @memberof google.longrunning + * @classdesc Represents a ListOperationsResponse. + * @implements IListOperationsResponse + * @constructor + * @param {google.longrunning.IListOperationsResponse=} [properties] Properties to set + */ + function ListOperationsResponse(properties) { + this.operations = []; + this.unreachable = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListOperationsResponse operations. + * @member {Array.} operations + * @memberof google.longrunning.ListOperationsResponse + * @instance + */ + ListOperationsResponse.prototype.operations = $util.emptyArray; + + /** + * ListOperationsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.longrunning.ListOperationsResponse + * @instance + */ + ListOperationsResponse.prototype.nextPageToken = ""; + + /** + * ListOperationsResponse unreachable. + * @member {Array.} unreachable + * @memberof google.longrunning.ListOperationsResponse + * @instance + */ + ListOperationsResponse.prototype.unreachable = $util.emptyArray; + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.ListOperationsResponse} ListOperationsResponse + */ + ListOperationsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.ListOperationsResponse) + return object; + var message = new $root.google.longrunning.ListOperationsResponse(); + if (object.operations) { + if (!Array.isArray(object.operations)) + throw TypeError(".google.longrunning.ListOperationsResponse.operations: array expected"); + message.operations = []; + for (var i = 0; i < object.operations.length; ++i) { + if (typeof object.operations[i] !== "object") + throw TypeError(".google.longrunning.ListOperationsResponse.operations: object expected"); + message.operations[i] = $root.google.longrunning.Operation.fromObject(object.operations[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + if (object.unreachable) { + if (!Array.isArray(object.unreachable)) + throw TypeError(".google.longrunning.ListOperationsResponse.unreachable: array expected"); + message.unreachable = []; + for (var i = 0; i < object.unreachable.length; ++i) + message.unreachable[i] = String(object.unreachable[i]); + } + return message; + }; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {google.longrunning.ListOperationsResponse} message ListOperationsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListOperationsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.operations = []; + object.unreachable = []; + } + if (options.defaults) + object.nextPageToken = ""; + if (message.operations && message.operations.length) { + object.operations = []; + for (var j = 0; j < message.operations.length; ++j) + object.operations[j] = $root.google.longrunning.Operation.toObject(message.operations[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + if (message.unreachable && message.unreachable.length) { + object.unreachable = []; + for (var j = 0; j < message.unreachable.length; ++j) + object.unreachable[j] = message.unreachable[j]; + } + return object; + }; + + /** + * Converts this ListOperationsResponse to JSON. + * @function toJSON + * @memberof google.longrunning.ListOperationsResponse + * @instance + * @returns {Object.} JSON object + */ + ListOperationsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListOperationsResponse + * @function getTypeUrl + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListOperationsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.ListOperationsResponse"; + }; + + return ListOperationsResponse; + })(); + + longrunning.CancelOperationRequest = (function() { + + /** + * Properties of a CancelOperationRequest. + * @memberof google.longrunning + * @interface ICancelOperationRequest + * @property {string|null} [name] CancelOperationRequest name + */ + + /** + * Constructs a new CancelOperationRequest. + * @memberof google.longrunning + * @classdesc Represents a CancelOperationRequest. + * @implements ICancelOperationRequest + * @constructor + * @param {google.longrunning.ICancelOperationRequest=} [properties] Properties to set + */ + function CancelOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CancelOperationRequest name. + * @member {string} name + * @memberof google.longrunning.CancelOperationRequest + * @instance + */ + CancelOperationRequest.prototype.name = ""; + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.CancelOperationRequest} CancelOperationRequest + */ + CancelOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.CancelOperationRequest) + return object; + var message = new $root.google.longrunning.CancelOperationRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {google.longrunning.CancelOperationRequest} message CancelOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CancelOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this CancelOperationRequest to JSON. + * @function toJSON + * @memberof google.longrunning.CancelOperationRequest + * @instance + * @returns {Object.} JSON object + */ + CancelOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CancelOperationRequest + * @function getTypeUrl + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CancelOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.CancelOperationRequest"; + }; + + return CancelOperationRequest; + })(); + + longrunning.DeleteOperationRequest = (function() { + + /** + * Properties of a DeleteOperationRequest. + * @memberof google.longrunning + * @interface IDeleteOperationRequest + * @property {string|null} [name] DeleteOperationRequest name + */ + + /** + * Constructs a new DeleteOperationRequest. + * @memberof google.longrunning + * @classdesc Represents a DeleteOperationRequest. + * @implements IDeleteOperationRequest + * @constructor + * @param {google.longrunning.IDeleteOperationRequest=} [properties] Properties to set + */ + function DeleteOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteOperationRequest name. + * @member {string} name + * @memberof google.longrunning.DeleteOperationRequest + * @instance + */ + DeleteOperationRequest.prototype.name = ""; + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.DeleteOperationRequest} DeleteOperationRequest + */ + DeleteOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.DeleteOperationRequest) + return object; + var message = new $root.google.longrunning.DeleteOperationRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {google.longrunning.DeleteOperationRequest} message DeleteOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @function toJSON + * @memberof google.longrunning.DeleteOperationRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteOperationRequest + * @function getTypeUrl + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.DeleteOperationRequest"; + }; + + return DeleteOperationRequest; + })(); + + longrunning.WaitOperationRequest = (function() { + + /** + * Properties of a WaitOperationRequest. + * @memberof google.longrunning + * @interface IWaitOperationRequest + * @property {string|null} [name] WaitOperationRequest name + * @property {google.protobuf.IDuration|null} [timeout] WaitOperationRequest timeout + */ + + /** + * Constructs a new WaitOperationRequest. + * @memberof google.longrunning + * @classdesc Represents a WaitOperationRequest. + * @implements IWaitOperationRequest + * @constructor + * @param {google.longrunning.IWaitOperationRequest=} [properties] Properties to set + */ + function WaitOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * WaitOperationRequest name. + * @member {string} name + * @memberof google.longrunning.WaitOperationRequest + * @instance + */ + WaitOperationRequest.prototype.name = ""; + + /** + * WaitOperationRequest timeout. + * @member {google.protobuf.IDuration|null|undefined} timeout + * @memberof google.longrunning.WaitOperationRequest + * @instance + */ + WaitOperationRequest.prototype.timeout = null; + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.WaitOperationRequest} WaitOperationRequest + */ + WaitOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.WaitOperationRequest) + return object; + var message = new $root.google.longrunning.WaitOperationRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.timeout != null) { + if (typeof object.timeout !== "object") + throw TypeError(".google.longrunning.WaitOperationRequest.timeout: object expected"); + message.timeout = $root.google.protobuf.Duration.fromObject(object.timeout); + } + return message; + }; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {google.longrunning.WaitOperationRequest} message WaitOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WaitOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.timeout = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.timeout != null && message.hasOwnProperty("timeout")) + object.timeout = $root.google.protobuf.Duration.toObject(message.timeout, options); + return object; + }; + + /** + * Converts this WaitOperationRequest to JSON. + * @function toJSON + * @memberof google.longrunning.WaitOperationRequest + * @instance + * @returns {Object.} JSON object + */ + WaitOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for WaitOperationRequest + * @function getTypeUrl + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WaitOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.WaitOperationRequest"; + }; + + return WaitOperationRequest; + })(); + + longrunning.OperationInfo = (function() { + + /** + * Properties of an OperationInfo. + * @memberof google.longrunning + * @interface IOperationInfo + * @property {string|null} [responseType] OperationInfo responseType + * @property {string|null} [metadataType] OperationInfo metadataType + */ + + /** + * Constructs a new OperationInfo. + * @memberof google.longrunning + * @classdesc Represents an OperationInfo. + * @implements IOperationInfo + * @constructor + * @param {google.longrunning.IOperationInfo=} [properties] Properties to set + */ + function OperationInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OperationInfo responseType. + * @member {string} responseType + * @memberof google.longrunning.OperationInfo + * @instance + */ + OperationInfo.prototype.responseType = ""; + + /** + * OperationInfo metadataType. + * @member {string} metadataType + * @memberof google.longrunning.OperationInfo + * @instance + */ + OperationInfo.prototype.metadataType = ""; + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.OperationInfo + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.OperationInfo} OperationInfo + */ + OperationInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.OperationInfo) + return object; + var message = new $root.google.longrunning.OperationInfo(); + if (object.responseType != null) + message.responseType = String(object.responseType); + if (object.metadataType != null) + message.metadataType = String(object.metadataType); + return message; + }; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.OperationInfo + * @static + * @param {google.longrunning.OperationInfo} message OperationInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OperationInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.responseType = ""; + object.metadataType = ""; + } + if (message.responseType != null && message.hasOwnProperty("responseType")) + object.responseType = message.responseType; + if (message.metadataType != null && message.hasOwnProperty("metadataType")) + object.metadataType = message.metadataType; + return object; + }; + + /** + * Converts this OperationInfo to JSON. + * @function toJSON + * @memberof google.longrunning.OperationInfo + * @instance + * @returns {Object.} JSON object + */ + OperationInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OperationInfo + * @function getTypeUrl + * @memberof google.longrunning.OperationInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OperationInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.OperationInfo"; + }; + + return OperationInfo; + })(); + + return longrunning; + })(); + + return google; + })(); + + return $root; +}); diff --git a/handwritten/firestore/dev/protos/firestore_v1beta1_proto_api.d.ts b/handwritten/firestore/dev/protos/firestore_v1beta1_proto_api.d.ts new file mode 100644 index 00000000000..5068bb13915 --- /dev/null +++ b/handwritten/firestore/dev/protos/firestore_v1beta1_proto_api.d.ts @@ -0,0 +1,9487 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as $protobuf from "protobufjs"; +import Long = require("long"); +/** Namespace google. */ +export namespace google { + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a Timestamp. */ + interface ITimestamp { + + /** Timestamp seconds */ + seconds?: (number|string|null); + + /** Timestamp nanos */ + nanos?: (number|null); + } + + /** Represents a Timestamp. */ + class Timestamp implements ITimestamp { + + /** + * Constructs a new Timestamp. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ITimestamp); + + /** Timestamp seconds. */ + public seconds: (number|string); + + /** Timestamp nanos. */ + public nanos: number; + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Timestamp + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @param message Timestamp + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Timestamp to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Timestamp + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Struct. */ + interface IStruct { + + /** Struct fields */ + fields?: ({ [k: string]: google.protobuf.IValue }|null); + } + + /** Represents a Struct. */ + class Struct implements IStruct { + + /** + * Constructs a new Struct. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStruct); + + /** Struct fields. */ + public fields: { [k: string]: google.protobuf.IValue }; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Struct + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @param message Struct + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Struct to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Struct + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue */ + numberValue?: (number|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value boolValue */ + boolValue?: (boolean|null); + + /** Value structValue */ + structValue?: (google.protobuf.IStruct|null); + + /** Value listValue */ + listValue?: (google.protobuf.IListValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue. */ + public numberValue?: (number|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value boolValue. */ + public boolValue?: (boolean|null); + + /** Value structValue. */ + public structValue?: (google.protobuf.IStruct|null); + + /** Value listValue. */ + public listValue?: (google.protobuf.IListValue|null); + + /** Value kind. */ + public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** NullValue enum. */ + type NullValue = + "NULL_VALUE"; + + /** Properties of a ListValue. */ + interface IListValue { + + /** ListValue values */ + values?: (google.protobuf.IValue[]|null); + } + + /** Represents a ListValue. */ + class ListValue implements IListValue { + + /** + * Constructs a new ListValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IListValue); + + /** ListValue values. */ + public values: google.protobuf.IValue[]; + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @param message ListValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); + + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Edition enum. */ + type Edition = + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; + + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { + + /** FileDescriptorProto name */ + name?: (string|null); + + /** FileDescriptorProto package */ + "package"?: (string|null); + + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); + + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); + + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); + + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); + + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); + + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax */ + syntax?: (string|null); + + /** FileDescriptorProto edition */ + edition?: (google.protobuf.Edition|null); + } + + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { + + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); + + /** FileDescriptorProto name. */ + public name: string; + + /** FileDescriptorProto package. */ + public package: string; + + /** FileDescriptorProto dependency. */ + public dependency: string[]; + + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; + + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; + + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; + + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; + + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax. */ + public syntax: string; + + /** FileDescriptorProto edition. */ + public edition: google.protobuf.Edition; + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { + + /** DescriptorProto name */ + name?: (string|null); + + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { + + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); + + /** DescriptorProto name. */ + public name: string; + + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; + + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + + /** DescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DescriptorProto { + + /** Properties of an ExtensionRange. */ + interface IExtensionRange { + + /** ExtensionRange start */ + start?: (number|null); + + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); + } + + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { + + /** + * Constructs a new ExtensionRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + + /** ExtensionRange start. */ + public start: number; + + /** ExtensionRange end. */ + public end: number; + + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReservedRange. */ + interface IReservedRange { + + /** ReservedRange start */ + start?: (number|null); + + /** ReservedRange end */ + end?: (number|null); + } + + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { + + /** + * Constructs a new ReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + + /** ReservedRange start. */ + public start: number; + + /** ReservedRange end. */ + public end: number; + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ExtensionRangeOptions declaration */ + declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); + + /** ExtensionRangeOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification */ + verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** ExtensionRangeOptions declaration. */ + public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; + + /** ExtensionRangeOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification. */ + public verification: google.protobuf.ExtensionRangeOptions.VerificationState; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExtensionRangeOptions { + + /** Properties of a Declaration. */ + interface IDeclaration { + + /** Declaration number */ + number?: (number|null); + + /** Declaration fullName */ + fullName?: (string|null); + + /** Declaration type */ + type?: (string|null); + + /** Declaration reserved */ + reserved?: (boolean|null); + + /** Declaration repeated */ + repeated?: (boolean|null); + } + + /** Represents a Declaration. */ + class Declaration implements IDeclaration { + + /** + * Constructs a new Declaration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); + + /** Declaration number. */ + public number: number; + + /** Declaration fullName. */ + public fullName: string; + + /** Declaration type. */ + public type: string; + + /** Declaration reserved. */ + public reserved: boolean; + + /** Declaration repeated. */ + public repeated: boolean; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Declaration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @param message Declaration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Declaration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Declaration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** VerificationState enum. */ + type VerificationState = + "DECLARATION"| "UNVERIFIED"; + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; + + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldDescriptorProto { + + /** Type enum. */ + type Type = + "TYPE_DOUBLE"| "TYPE_FLOAT"| "TYPE_INT64"| "TYPE_UINT64"| "TYPE_INT32"| "TYPE_FIXED64"| "TYPE_FIXED32"| "TYPE_BOOL"| "TYPE_STRING"| "TYPE_GROUP"| "TYPE_MESSAGE"| "TYPE_BYTES"| "TYPE_UINT32"| "TYPE_ENUM"| "TYPE_SFIXED32"| "TYPE_SFIXED64"| "TYPE_SINT32"| "TYPE_SINT64"; + + /** Label enum. */ + type Label = + "LABEL_OPTIONAL"| "LABEL_REPEATED"| "LABEL_REQUIRED"; + } + + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { + + /** OneofDescriptorProto name */ + name?: (string|null); + + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } + + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { + + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); + + /** OneofDescriptorProto name. */ + public name: string; + + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { + + /** EnumDescriptorProto name */ + name?: (string|null); + + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { + + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); + + /** EnumDescriptorProto name. */ + public name: string; + + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; + + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { + + /** EnumValueDescriptorProto name */ + name?: (string|null); + + /** EnumValueDescriptorProto number */ + number?: (number|null); + + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } + + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + + /** EnumValueDescriptorProto name. */ + public name: string; + + /** EnumValueDescriptorProto number. */ + public number: number; + + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { + + /** ServiceDescriptorProto name */ + name?: (string|null); + + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); + + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } + + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { + + /** FileOptions javaPackage */ + javaPackage?: (string|null); + + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); + + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); + + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); + + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); + + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + + /** FileOptions goPackage */ + goPackage?: (string|null); + + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); + + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); + + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); + + /** FileOptions deprecated */ + deprecated?: (boolean|null); + + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); + + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); + + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); + + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); + } + + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { + + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); + + /** FileOptions javaPackage. */ + public javaPackage: string; + + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; + + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; + + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; + + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; + + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + + /** FileOptions goPackage. */ + public goPackage: string; + + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; + + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; + + /** FileOptions deprecated. */ + public deprecated: boolean; + + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; + + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; + + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + type OptimizeMode = + "SPEED"| "CODE_SIZE"| "LITE_RUNTIME"; + } + + /** Properties of a MessageOptions. */ + interface IMessageOptions { + + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); + + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); + + /** MessageOptions deprecated */ + deprecated?: (boolean|null); + + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); + + /** MessageOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** MessageOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MessageOptions .google.api.resource */ + ".google.api.resource"?: (google.api.IResourceDescriptor|null); + } + + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { + + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); + + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; + + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; + + /** MessageOptions deprecated. */ + public deprecated: boolean; + + /** MessageOptions mapEntry. */ + public mapEntry: boolean; + + /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** MessageOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MessageOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldOptions. */ + interface IFieldOptions { + + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); + + /** FieldOptions packed */ + packed?: (boolean|null); + + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); + + /** FieldOptions lazy */ + lazy?: (boolean|null); + + /** FieldOptions unverifiedLazy */ + unverifiedLazy?: (boolean|null); + + /** FieldOptions deprecated */ + deprecated?: (boolean|null); + + /** FieldOptions weak */ + weak?: (boolean|null); + + /** FieldOptions debugRedact */ + debugRedact?: (boolean|null); + + /** FieldOptions retention */ + retention?: (google.protobuf.FieldOptions.OptionRetention|null); + + /** FieldOptions targets */ + targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); + + /** FieldOptions editionDefaults */ + editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); + + /** FieldOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FieldOptions .google.api.fieldBehavior */ + ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); + + /** FieldOptions .google.api.resourceReference */ + ".google.api.resourceReference"?: (google.api.IResourceReference|null); + } + + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { + + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); + + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; + + /** FieldOptions packed. */ + public packed: boolean; + + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; + + /** FieldOptions lazy. */ + public lazy: boolean; + + /** FieldOptions unverifiedLazy. */ + public unverifiedLazy: boolean; + + /** FieldOptions deprecated. */ + public deprecated: boolean; + + /** FieldOptions weak. */ + public weak: boolean; + + /** FieldOptions debugRedact. */ + public debugRedact: boolean; + + /** FieldOptions retention. */ + public retention: google.protobuf.FieldOptions.OptionRetention; + + /** FieldOptions targets. */ + public targets: google.protobuf.FieldOptions.OptionTargetType[]; + + /** FieldOptions editionDefaults. */ + public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; + + /** FieldOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldOptions { + + /** CType enum. */ + type CType = + "STRING"| "CORD"| "STRING_PIECE"; + + /** JSType enum. */ + type JSType = + "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; + + /** OptionRetention enum. */ + type OptionRetention = + "RETENTION_UNKNOWN"| "RETENTION_RUNTIME"| "RETENTION_SOURCE"; + + /** OptionTargetType enum. */ + type OptionTargetType = + "TARGET_TYPE_UNKNOWN"| "TARGET_TYPE_FILE"| "TARGET_TYPE_EXTENSION_RANGE"| "TARGET_TYPE_MESSAGE"| "TARGET_TYPE_FIELD"| "TARGET_TYPE_ONEOF"| "TARGET_TYPE_ENUM"| "TARGET_TYPE_ENUM_ENTRY"| "TARGET_TYPE_SERVICE"| "TARGET_TYPE_METHOD"; + + /** Properties of an EditionDefault. */ + interface IEditionDefault { + + /** EditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** EditionDefault value */ + value?: (string|null); + } + + /** Represents an EditionDefault. */ + class EditionDefault implements IEditionDefault { + + /** + * Constructs a new EditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); + + /** EditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** EditionDefault value. */ + public value: string; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @param message EditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an OneofOptions. */ + interface IOneofOptions { + + /** OneofOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { + + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); + + /** OneofOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumOptions. */ + interface IEnumOptions { + + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); + + /** EnumOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** EnumOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { + + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** EnumOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact */ + debugRedact?: (boolean|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { + + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); + + /** EnumValueOptions deprecated. */ + public deprecated: boolean; + + /** EnumValueOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact. */ + public debugRedact: boolean; + + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceOptions. */ + interface IServiceOptions { + + /** ServiceOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); + + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); + + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); + + /** ServiceOptions .google.api.apiVersion */ + ".google.api.apiVersion"?: (string|null); + } + + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { + + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); + + /** ServiceOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated. */ + public deprecated: boolean; + + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodOptions. */ + interface IMethodOptions { + + /** MethodOptions deprecated */ + deprecated?: (boolean|null); + + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); + + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); + + /** MethodOptions .google.api.routing */ + ".google.api.routing"?: (google.api.IRoutingRule|null); + + /** MethodOptions .google.longrunning.operationInfo */ + ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); + } + + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { + + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); + + /** MethodOptions deprecated. */ + public deprecated: boolean; + + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + type IdempotencyLevel = + "IDEMPOTENCY_UNKNOWN"| "NO_SIDE_EFFECTS"| "IDEMPOTENT"; + } + + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { + + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); + + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|string|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|string|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|string); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|string); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UninterpretedOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamePart + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a FeatureSet. */ + interface IFeatureSet { + + /** FeatureSet fieldPresence */ + fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|null); + + /** FeatureSet enumType */ + enumType?: (google.protobuf.FeatureSet.EnumType|null); + + /** FeatureSet repeatedFieldEncoding */ + repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|null); + + /** FeatureSet utf8Validation */ + utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|null); + + /** FeatureSet messageEncoding */ + messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|null); + + /** FeatureSet jsonFormat */ + jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|null); + } + + /** Represents a FeatureSet. */ + class FeatureSet implements IFeatureSet { + + /** + * Constructs a new FeatureSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSet); + + /** FeatureSet fieldPresence. */ + public fieldPresence: google.protobuf.FeatureSet.FieldPresence; + + /** FeatureSet enumType. */ + public enumType: google.protobuf.FeatureSet.EnumType; + + /** FeatureSet repeatedFieldEncoding. */ + public repeatedFieldEncoding: google.protobuf.FeatureSet.RepeatedFieldEncoding; + + /** FeatureSet utf8Validation. */ + public utf8Validation: google.protobuf.FeatureSet.Utf8Validation; + + /** FeatureSet messageEncoding. */ + public messageEncoding: google.protobuf.FeatureSet.MessageEncoding; + + /** FeatureSet jsonFormat. */ + public jsonFormat: google.protobuf.FeatureSet.JsonFormat; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @param message FeatureSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSet { + + /** FieldPresence enum. */ + type FieldPresence = + "FIELD_PRESENCE_UNKNOWN"| "EXPLICIT"| "IMPLICIT"| "LEGACY_REQUIRED"; + + /** EnumType enum. */ + type EnumType = + "ENUM_TYPE_UNKNOWN"| "OPEN"| "CLOSED"; + + /** RepeatedFieldEncoding enum. */ + type RepeatedFieldEncoding = + "REPEATED_FIELD_ENCODING_UNKNOWN"| "PACKED"| "EXPANDED"; + + /** Utf8Validation enum. */ + type Utf8Validation = + "UTF8_VALIDATION_UNKNOWN"| "VERIFY"| "NONE"; + + /** MessageEncoding enum. */ + type MessageEncoding = + "MESSAGE_ENCODING_UNKNOWN"| "LENGTH_PREFIXED"| "DELIMITED"; + + /** JsonFormat enum. */ + type JsonFormat = + "JSON_FORMAT_UNKNOWN"| "ALLOW"| "LEGACY_BEST_EFFORT"; + } + + /** Properties of a FeatureSetDefaults. */ + interface IFeatureSetDefaults { + + /** FeatureSetDefaults defaults */ + defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); + + /** FeatureSetDefaults minimumEdition */ + minimumEdition?: (google.protobuf.Edition|null); + + /** FeatureSetDefaults maximumEdition */ + maximumEdition?: (google.protobuf.Edition|null); + } + + /** Represents a FeatureSetDefaults. */ + class FeatureSetDefaults implements IFeatureSetDefaults { + + /** + * Constructs a new FeatureSetDefaults. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSetDefaults); + + /** FeatureSetDefaults defaults. */ + public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; + + /** FeatureSetDefaults minimumEdition. */ + public minimumEdition: google.protobuf.Edition; + + /** FeatureSetDefaults maximumEdition. */ + public maximumEdition: google.protobuf.Edition; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetDefaults + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @param message FeatureSetDefaults + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetDefaults + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSetDefaults { + + /** Properties of a FeatureSetEditionDefault. */ + interface IFeatureSetEditionDefault { + + /** FeatureSetEditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); + } + + /** Represents a FeatureSetEditionDefault. */ + class FeatureSetEditionDefault implements IFeatureSetEditionDefault { + + /** + * Constructs a new FeatureSetEditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); + + /** FeatureSetEditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetEditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @param message FeatureSetEditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { + + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } + + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { + + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); + + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SourceCodeInfo { + + /** Properties of a Location. */ + interface ILocation { + + /** Location path */ + path?: (number[]|null); + + /** Location span */ + span?: (number[]|null); + + /** Location leadingComments */ + leadingComments?: (string|null); + + /** Location trailingComments */ + trailingComments?: (string|null); + + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + + /** Location path. */ + public path: number[]; + + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Location + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { + + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } + + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { + + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); + + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + + /** Annotation semantic */ + semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); + } + + /** Represents an Annotation. */ + class Annotation implements IAnnotation { + + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); + + /** Annotation path. */ + public path: number[]; + + /** Annotation sourceFile. */ + public sourceFile: string; + + /** Annotation begin. */ + public begin: number; + + /** Annotation end. */ + public end: number; + + /** Annotation semantic. */ + public semantic: google.protobuf.GeneratedCodeInfo.Annotation.Semantic; + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Annotation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Annotation { + + /** Semantic enum. */ + type Semantic = + "NONE"| "SET"| "ALIAS"; + } + } + + /** Properties of a Duration. */ + interface IDuration { + + /** Duration seconds */ + seconds?: (number|string|null); + + /** Duration nanos */ + nanos?: (number|null); + } + + /** Represents a Duration. */ + class Duration implements IDuration { + + /** + * Constructs a new Duration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDuration); + + /** Duration seconds. */ + public seconds: (number|string); + + /** Duration nanos. */ + public nanos: number; + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Duration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Duration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Duration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DoubleValue. */ + interface IDoubleValue { + + /** DoubleValue value */ + value?: (number|null); + } + + /** Represents a DoubleValue. */ + class DoubleValue implements IDoubleValue { + + /** + * Constructs a new DoubleValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDoubleValue); + + /** DoubleValue value. */ + public value: number; + + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DoubleValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; + + /** + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @param message DoubleValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DoubleValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DoubleValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FloatValue. */ + interface IFloatValue { + + /** FloatValue value */ + value?: (number|null); + } + + /** Represents a FloatValue. */ + class FloatValue implements IFloatValue { + + /** + * Constructs a new FloatValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFloatValue); + + /** FloatValue value. */ + public value: number; + + /** + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FloatValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; + + /** + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. + * @param message FloatValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FloatValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FloatValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int64Value. */ + interface IInt64Value { + + /** Int64Value value */ + value?: (number|string|null); + } + + /** Represents an Int64Value. */ + class Int64Value implements IInt64Value { + + /** + * Constructs a new Int64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt64Value); + + /** Int64Value value. */ + public value: (number|string); + + /** + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; + + /** + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. + * @param message Int64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt64Value. */ + interface IUInt64Value { + + /** UInt64Value value */ + value?: (number|string|null); + } + + /** Represents a UInt64Value. */ + class UInt64Value implements IUInt64Value { + + /** + * Constructs a new UInt64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt64Value); + + /** UInt64Value value. */ + public value: (number|string); + + /** + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; + + /** + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. + * @param message UInt64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int32Value. */ + interface IInt32Value { + + /** Int32Value value */ + value?: (number|null); + } + + /** Represents an Int32Value. */ + class Int32Value implements IInt32Value { + + /** + * Constructs a new Int32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt32Value); + + /** Int32Value value. */ + public value: number; + + /** + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; + + /** + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. + * @param message Int32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt32Value. */ + interface IUInt32Value { + + /** UInt32Value value */ + value?: (number|null); + } + + /** Represents a UInt32Value. */ + class UInt32Value implements IUInt32Value { + + /** + * Constructs a new UInt32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt32Value); + + /** UInt32Value value. */ + public value: number; + + /** + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; + + /** + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. + * @param message UInt32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BoolValue. */ + interface IBoolValue { + + /** BoolValue value */ + value?: (boolean|null); + } + + /** Represents a BoolValue. */ + class BoolValue implements IBoolValue { + + /** + * Constructs a new BoolValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBoolValue); + + /** BoolValue value. */ + public value: boolean; + + /** + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BoolValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; + + /** + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. + * @param message BoolValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BoolValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BoolValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StringValue. */ + interface IStringValue { + + /** StringValue value */ + value?: (string|null); + } + + /** Represents a StringValue. */ + class StringValue implements IStringValue { + + /** + * Constructs a new StringValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStringValue); + + /** StringValue value. */ + public value: string; + + /** + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StringValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; + + /** + * Creates a plain object from a StringValue message. Also converts values to other types if specified. + * @param message StringValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StringValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StringValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BytesValue. */ + interface IBytesValue { + + /** BytesValue value */ + value?: (Uint8Array|null); + } + + /** Represents a BytesValue. */ + class BytesValue implements IBytesValue { + + /** + * Constructs a new BytesValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBytesValue); + + /** BytesValue value. */ + public value: Uint8Array; + + /** + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BytesValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; + + /** + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. + * @param message BytesValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BytesValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BytesValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Empty. */ + interface IEmpty { + } + + /** Represents an Empty. */ + class Empty implements IEmpty { + + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Empty + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Any. */ + interface IAny { + + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|null); + } + + /** Represents an Any. */ + class Any implements IAny { + + /** + * Constructs a new Any. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IAny); + + /** Any type_url. */ + public type_url: string; + + /** Any value. */ + public value: Uint8Array; + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Any + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Any to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Any + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldMask. */ + interface IFieldMask { + + /** FieldMask paths */ + paths?: (string[]|null); + } + + /** Represents a FieldMask. */ + class FieldMask implements IFieldMask { + + /** + * Constructs a new FieldMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldMask); + + /** FieldMask paths. */ + public paths: string[]; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldMask + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @param message FieldMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace firestore. */ + namespace firestore { + + /** Namespace v1beta1. */ + namespace v1beta1 { + + /** Properties of a DocumentMask. */ + interface IDocumentMask { + + /** DocumentMask fieldPaths */ + fieldPaths?: (string[]|null); + } + + /** Represents a DocumentMask. */ + class DocumentMask implements IDocumentMask { + + /** + * Constructs a new DocumentMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentMask); + + /** DocumentMask fieldPaths. */ + public fieldPaths: string[]; + + /** + * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentMask + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentMask; + + /** + * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. + * @param message DocumentMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Precondition. */ + interface IPrecondition { + + /** Precondition exists */ + exists?: (boolean|null); + + /** Precondition updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a Precondition. */ + class Precondition implements IPrecondition { + + /** + * Constructs a new Precondition. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IPrecondition); + + /** Precondition exists. */ + public exists?: (boolean|null); + + /** Precondition updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** Precondition conditionType. */ + public conditionType?: ("exists"|"updateTime"); + + /** + * Creates a Precondition message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Precondition + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Precondition; + + /** + * Creates a plain object from a Precondition message. Also converts values to other types if specified. + * @param message Precondition + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Precondition, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Precondition to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Precondition + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TransactionOptions. */ + interface ITransactionOptions { + + /** TransactionOptions readOnly */ + readOnly?: (google.firestore.v1beta1.TransactionOptions.IReadOnly|null); + + /** TransactionOptions readWrite */ + readWrite?: (google.firestore.v1beta1.TransactionOptions.IReadWrite|null); + } + + /** Represents a TransactionOptions. */ + class TransactionOptions implements ITransactionOptions { + + /** + * Constructs a new TransactionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ITransactionOptions); + + /** TransactionOptions readOnly. */ + public readOnly?: (google.firestore.v1beta1.TransactionOptions.IReadOnly|null); + + /** TransactionOptions readWrite. */ + public readWrite?: (google.firestore.v1beta1.TransactionOptions.IReadWrite|null); + + /** TransactionOptions mode. */ + public mode?: ("readOnly"|"readWrite"); + + /** + * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TransactionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TransactionOptions; + + /** + * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. + * @param message TransactionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.TransactionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TransactionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TransactionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TransactionOptions { + + /** Properties of a ReadWrite. */ + interface IReadWrite { + + /** ReadWrite retryTransaction */ + retryTransaction?: (Uint8Array|null); + } + + /** Represents a ReadWrite. */ + class ReadWrite implements IReadWrite { + + /** + * Constructs a new ReadWrite. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.TransactionOptions.IReadWrite); + + /** ReadWrite retryTransaction. */ + public retryTransaction: Uint8Array; + + /** + * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadWrite + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TransactionOptions.ReadWrite; + + /** + * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. + * @param message ReadWrite + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.TransactionOptions.ReadWrite, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadWrite to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadWrite + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReadOnly. */ + interface IReadOnly { + + /** ReadOnly readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a ReadOnly. */ + class ReadOnly implements IReadOnly { + + /** + * Constructs a new ReadOnly. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.TransactionOptions.IReadOnly); + + /** ReadOnly readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ReadOnly consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadOnly + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TransactionOptions.ReadOnly; + + /** + * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. + * @param message ReadOnly + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.TransactionOptions.ReadOnly, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadOnly to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadOnly + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a Document. */ + interface IDocument { + + /** Document name */ + name?: (string|null); + + /** Document fields */ + fields?: ({ [k: string]: google.firestore.v1beta1.IValue }|null); + + /** Document createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** Document updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a Document. */ + class Document implements IDocument { + + /** + * Constructs a new Document. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocument); + + /** Document name. */ + public name: string; + + /** Document fields. */ + public fields: { [k: string]: google.firestore.v1beta1.IValue }; + + /** Document createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** Document updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a Document message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Document + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Document; + + /** + * Creates a plain object from a Document message. Also converts values to other types if specified. + * @param message Document + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Document, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Document to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Document + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value booleanValue */ + booleanValue?: (boolean|null); + + /** Value integerValue */ + integerValue?: (number|string|null); + + /** Value doubleValue */ + doubleValue?: (number|null); + + /** Value timestampValue */ + timestampValue?: (google.protobuf.ITimestamp|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value bytesValue */ + bytesValue?: (Uint8Array|null); + + /** Value referenceValue */ + referenceValue?: (string|null); + + /** Value geoPointValue */ + geoPointValue?: (google.type.ILatLng|null); + + /** Value arrayValue */ + arrayValue?: (google.firestore.v1beta1.IArrayValue|null); + + /** Value mapValue */ + mapValue?: (google.firestore.v1beta1.IMapValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value booleanValue. */ + public booleanValue?: (boolean|null); + + /** Value integerValue. */ + public integerValue?: (number|string|null); + + /** Value doubleValue. */ + public doubleValue?: (number|null); + + /** Value timestampValue. */ + public timestampValue?: (google.protobuf.ITimestamp|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value bytesValue. */ + public bytesValue?: (Uint8Array|null); + + /** Value referenceValue. */ + public referenceValue?: (string|null); + + /** Value geoPointValue. */ + public geoPointValue?: (google.type.ILatLng|null); + + /** Value arrayValue. */ + public arrayValue?: (google.firestore.v1beta1.IArrayValue|null); + + /** Value mapValue. */ + public mapValue?: (google.firestore.v1beta1.IMapValue|null); + + /** Value valueType. */ + public valueType?: ("nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ArrayValue. */ + interface IArrayValue { + + /** ArrayValue values */ + values?: (google.firestore.v1beta1.IValue[]|null); + } + + /** Represents an ArrayValue. */ + class ArrayValue implements IArrayValue { + + /** + * Constructs a new ArrayValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IArrayValue); + + /** ArrayValue values. */ + public values: google.firestore.v1beta1.IValue[]; + + /** + * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ArrayValue + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ArrayValue; + + /** + * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. + * @param message ArrayValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ArrayValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ArrayValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ArrayValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MapValue. */ + interface IMapValue { + + /** MapValue fields */ + fields?: ({ [k: string]: google.firestore.v1beta1.IValue }|null); + } + + /** Represents a MapValue. */ + class MapValue implements IMapValue { + + /** + * Constructs a new MapValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IMapValue); + + /** MapValue fields. */ + public fields: { [k: string]: google.firestore.v1beta1.IValue }; + + /** + * Creates a MapValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MapValue + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.MapValue; + + /** + * Creates a plain object from a MapValue message. Also converts values to other types if specified. + * @param message MapValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.MapValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MapValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MapValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Represents a Firestore */ + class Firestore extends $protobuf.rpc.Service { + + /** + * Constructs a new Firestore service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls GetDocument. + * @param request GetDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public getDocument(request: google.firestore.v1beta1.IGetDocumentRequest, callback: google.firestore.v1beta1.Firestore.GetDocumentCallback): void; + + /** + * Calls GetDocument. + * @param request GetDocumentRequest message or plain object + * @returns Promise + */ + public getDocument(request: google.firestore.v1beta1.IGetDocumentRequest): Promise; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDocumentsResponse + */ + public listDocuments(request: google.firestore.v1beta1.IListDocumentsRequest, callback: google.firestore.v1beta1.Firestore.ListDocumentsCallback): void; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @returns Promise + */ + public listDocuments(request: google.firestore.v1beta1.IListDocumentsRequest): Promise; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public updateDocument(request: google.firestore.v1beta1.IUpdateDocumentRequest, callback: google.firestore.v1beta1.Firestore.UpdateDocumentCallback): void; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @returns Promise + */ + public updateDocument(request: google.firestore.v1beta1.IUpdateDocumentRequest): Promise; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteDocument(request: google.firestore.v1beta1.IDeleteDocumentRequest, callback: google.firestore.v1beta1.Firestore.DeleteDocumentCallback): void; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @returns Promise + */ + public deleteDocument(request: google.firestore.v1beta1.IDeleteDocumentRequest): Promise; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse + */ + public batchGetDocuments(request: google.firestore.v1beta1.IBatchGetDocumentsRequest, callback: google.firestore.v1beta1.Firestore.BatchGetDocumentsCallback): void; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @returns Promise + */ + public batchGetDocuments(request: google.firestore.v1beta1.IBatchGetDocumentsRequest): Promise; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BeginTransactionResponse + */ + public beginTransaction(request: google.firestore.v1beta1.IBeginTransactionRequest, callback: google.firestore.v1beta1.Firestore.BeginTransactionCallback): void; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @returns Promise + */ + public beginTransaction(request: google.firestore.v1beta1.IBeginTransactionRequest): Promise; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @param callback Node-style callback called with the error, if any, and CommitResponse + */ + public commit(request: google.firestore.v1beta1.ICommitRequest, callback: google.firestore.v1beta1.Firestore.CommitCallback): void; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @returns Promise + */ + public commit(request: google.firestore.v1beta1.ICommitRequest): Promise; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public rollback(request: google.firestore.v1beta1.IRollbackRequest, callback: google.firestore.v1beta1.Firestore.RollbackCallback): void; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @returns Promise + */ + public rollback(request: google.firestore.v1beta1.IRollbackRequest): Promise; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RunQueryResponse + */ + public runQuery(request: google.firestore.v1beta1.IRunQueryRequest, callback: google.firestore.v1beta1.Firestore.RunQueryCallback): void; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @returns Promise + */ + public runQuery(request: google.firestore.v1beta1.IRunQueryRequest): Promise; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and PartitionQueryResponse + */ + public partitionQuery(request: google.firestore.v1beta1.IPartitionQueryRequest, callback: google.firestore.v1beta1.Firestore.PartitionQueryCallback): void; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @returns Promise + */ + public partitionQuery(request: google.firestore.v1beta1.IPartitionQueryRequest): Promise; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and WriteResponse + */ + public write(request: google.firestore.v1beta1.IWriteRequest, callback: google.firestore.v1beta1.Firestore.WriteCallback): void; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @returns Promise + */ + public write(request: google.firestore.v1beta1.IWriteRequest): Promise; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListenResponse + */ + public listen(request: google.firestore.v1beta1.IListenRequest, callback: google.firestore.v1beta1.Firestore.ListenCallback): void; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @returns Promise + */ + public listen(request: google.firestore.v1beta1.IListenRequest): Promise; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListCollectionIdsResponse + */ + public listCollectionIds(request: google.firestore.v1beta1.IListCollectionIdsRequest, callback: google.firestore.v1beta1.Firestore.ListCollectionIdsCallback): void; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @returns Promise + */ + public listCollectionIds(request: google.firestore.v1beta1.IListCollectionIdsRequest): Promise; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchWriteResponse + */ + public batchWrite(request: google.firestore.v1beta1.IBatchWriteRequest, callback: google.firestore.v1beta1.Firestore.BatchWriteCallback): void; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @returns Promise + */ + public batchWrite(request: google.firestore.v1beta1.IBatchWriteRequest): Promise; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public createDocument(request: google.firestore.v1beta1.ICreateDocumentRequest, callback: google.firestore.v1beta1.Firestore.CreateDocumentCallback): void; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @returns Promise + */ + public createDocument(request: google.firestore.v1beta1.ICreateDocumentRequest): Promise; + } + + namespace Firestore { + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#getDocument}. + * @param error Error, if any + * @param [response] Document + */ + type GetDocumentCallback = (error: (Error|null), response?: google.firestore.v1beta1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#listDocuments}. + * @param error Error, if any + * @param [response] ListDocumentsResponse + */ + type ListDocumentsCallback = (error: (Error|null), response?: google.firestore.v1beta1.ListDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#updateDocument}. + * @param error Error, if any + * @param [response] Document + */ + type UpdateDocumentCallback = (error: (Error|null), response?: google.firestore.v1beta1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#deleteDocument}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteDocumentCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#batchGetDocuments}. + * @param error Error, if any + * @param [response] BatchGetDocumentsResponse + */ + type BatchGetDocumentsCallback = (error: (Error|null), response?: google.firestore.v1beta1.BatchGetDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#beginTransaction}. + * @param error Error, if any + * @param [response] BeginTransactionResponse + */ + type BeginTransactionCallback = (error: (Error|null), response?: google.firestore.v1beta1.BeginTransactionResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#commit}. + * @param error Error, if any + * @param [response] CommitResponse + */ + type CommitCallback = (error: (Error|null), response?: google.firestore.v1beta1.CommitResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#rollback}. + * @param error Error, if any + * @param [response] Empty + */ + type RollbackCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#runQuery}. + * @param error Error, if any + * @param [response] RunQueryResponse + */ + type RunQueryCallback = (error: (Error|null), response?: google.firestore.v1beta1.RunQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#partitionQuery}. + * @param error Error, if any + * @param [response] PartitionQueryResponse + */ + type PartitionQueryCallback = (error: (Error|null), response?: google.firestore.v1beta1.PartitionQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#write}. + * @param error Error, if any + * @param [response] WriteResponse + */ + type WriteCallback = (error: (Error|null), response?: google.firestore.v1beta1.WriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#listen}. + * @param error Error, if any + * @param [response] ListenResponse + */ + type ListenCallback = (error: (Error|null), response?: google.firestore.v1beta1.ListenResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#listCollectionIds}. + * @param error Error, if any + * @param [response] ListCollectionIdsResponse + */ + type ListCollectionIdsCallback = (error: (Error|null), response?: google.firestore.v1beta1.ListCollectionIdsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#batchWrite}. + * @param error Error, if any + * @param [response] BatchWriteResponse + */ + type BatchWriteCallback = (error: (Error|null), response?: google.firestore.v1beta1.BatchWriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#createDocument}. + * @param error Error, if any + * @param [response] Document + */ + type CreateDocumentCallback = (error: (Error|null), response?: google.firestore.v1beta1.Document) => void; + } + + /** Properties of a GetDocumentRequest. */ + interface IGetDocumentRequest { + + /** GetDocumentRequest name */ + name?: (string|null); + + /** GetDocumentRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** GetDocumentRequest transaction */ + transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a GetDocumentRequest. */ + class GetDocumentRequest implements IGetDocumentRequest { + + /** + * Constructs a new GetDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IGetDocumentRequest); + + /** GetDocumentRequest name. */ + public name: string; + + /** GetDocumentRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** GetDocumentRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** GetDocumentRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.GetDocumentRequest; + + /** + * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. + * @param message GetDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.GetDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsRequest. */ + interface IListDocumentsRequest { + + /** ListDocumentsRequest parent */ + parent?: (string|null); + + /** ListDocumentsRequest collectionId */ + collectionId?: (string|null); + + /** ListDocumentsRequest pageSize */ + pageSize?: (number|null); + + /** ListDocumentsRequest pageToken */ + pageToken?: (string|null); + + /** ListDocumentsRequest orderBy */ + orderBy?: (string|null); + + /** ListDocumentsRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** ListDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing */ + showMissing?: (boolean|null); + } + + /** Represents a ListDocumentsRequest. */ + class ListDocumentsRequest implements IListDocumentsRequest { + + /** + * Constructs a new ListDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListDocumentsRequest); + + /** ListDocumentsRequest parent. */ + public parent: string; + + /** ListDocumentsRequest collectionId. */ + public collectionId: string; + + /** ListDocumentsRequest pageSize. */ + public pageSize: number; + + /** ListDocumentsRequest pageToken. */ + public pageToken: string; + + /** ListDocumentsRequest orderBy. */ + public orderBy: string; + + /** ListDocumentsRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** ListDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing. */ + public showMissing: boolean; + + /** ListDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListDocumentsRequest; + + /** + * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. + * @param message ListDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsResponse. */ + interface IListDocumentsResponse { + + /** ListDocumentsResponse documents */ + documents?: (google.firestore.v1beta1.IDocument[]|null); + + /** ListDocumentsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListDocumentsResponse. */ + class ListDocumentsResponse implements IListDocumentsResponse { + + /** + * Constructs a new ListDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListDocumentsResponse); + + /** ListDocumentsResponse documents. */ + public documents: google.firestore.v1beta1.IDocument[]; + + /** ListDocumentsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListDocumentsResponse; + + /** + * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. + * @param message ListDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDocumentRequest. */ + interface ICreateDocumentRequest { + + /** CreateDocumentRequest parent */ + parent?: (string|null); + + /** CreateDocumentRequest collectionId */ + collectionId?: (string|null); + + /** CreateDocumentRequest documentId */ + documentId?: (string|null); + + /** CreateDocumentRequest document */ + document?: (google.firestore.v1beta1.IDocument|null); + + /** CreateDocumentRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + } + + /** Represents a CreateDocumentRequest. */ + class CreateDocumentRequest implements ICreateDocumentRequest { + + /** + * Constructs a new CreateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ICreateDocumentRequest); + + /** CreateDocumentRequest parent. */ + public parent: string; + + /** CreateDocumentRequest collectionId. */ + public collectionId: string; + + /** CreateDocumentRequest documentId. */ + public documentId: string; + + /** CreateDocumentRequest document. */ + public document?: (google.firestore.v1beta1.IDocument|null); + + /** CreateDocumentRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** + * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.CreateDocumentRequest; + + /** + * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. + * @param message CreateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.CreateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDocumentRequest. */ + interface IUpdateDocumentRequest { + + /** UpdateDocumentRequest document */ + document?: (google.firestore.v1beta1.IDocument|null); + + /** UpdateDocumentRequest updateMask */ + updateMask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** UpdateDocumentRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + } + + /** Represents an UpdateDocumentRequest. */ + class UpdateDocumentRequest implements IUpdateDocumentRequest { + + /** + * Constructs a new UpdateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IUpdateDocumentRequest); + + /** UpdateDocumentRequest document. */ + public document?: (google.firestore.v1beta1.IDocument|null); + + /** UpdateDocumentRequest updateMask. */ + public updateMask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** UpdateDocumentRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + + /** + * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.UpdateDocumentRequest; + + /** + * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. + * @param message UpdateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.UpdateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDocumentRequest. */ + interface IDeleteDocumentRequest { + + /** DeleteDocumentRequest name */ + name?: (string|null); + + /** DeleteDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + } + + /** Represents a DeleteDocumentRequest. */ + class DeleteDocumentRequest implements IDeleteDocumentRequest { + + /** + * Constructs a new DeleteDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDeleteDocumentRequest); + + /** DeleteDocumentRequest name. */ + public name: string; + + /** DeleteDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + + /** + * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DeleteDocumentRequest; + + /** + * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. + * @param message DeleteDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DeleteDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsRequest. */ + interface IBatchGetDocumentsRequest { + + /** BatchGetDocumentsRequest database */ + database?: (string|null); + + /** BatchGetDocumentsRequest documents */ + documents?: (string[]|null); + + /** BatchGetDocumentsRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction */ + newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsRequest. */ + class BatchGetDocumentsRequest implements IBatchGetDocumentsRequest { + + /** + * Constructs a new BatchGetDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBatchGetDocumentsRequest); + + /** BatchGetDocumentsRequest database. */ + public database: string; + + /** BatchGetDocumentsRequest documents. */ + public documents: string[]; + + /** BatchGetDocumentsRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction. */ + public newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchGetDocumentsRequest; + + /** + * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. + * @param message BatchGetDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BatchGetDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsResponse. */ + interface IBatchGetDocumentsResponse { + + /** BatchGetDocumentsResponse found */ + found?: (google.firestore.v1beta1.IDocument|null); + + /** BatchGetDocumentsResponse missing */ + missing?: (string|null); + + /** BatchGetDocumentsResponse transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsResponse. */ + class BatchGetDocumentsResponse implements IBatchGetDocumentsResponse { + + /** + * Constructs a new BatchGetDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBatchGetDocumentsResponse); + + /** BatchGetDocumentsResponse found. */ + public found?: (google.firestore.v1beta1.IDocument|null); + + /** BatchGetDocumentsResponse missing. */ + public missing?: (string|null); + + /** BatchGetDocumentsResponse transaction. */ + public transaction: Uint8Array; + + /** BatchGetDocumentsResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsResponse result. */ + public result?: ("found"|"missing"); + + /** + * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchGetDocumentsResponse; + + /** + * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. + * @param message BatchGetDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BatchGetDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionRequest. */ + interface IBeginTransactionRequest { + + /** BeginTransactionRequest database */ + database?: (string|null); + + /** BeginTransactionRequest options */ + options?: (google.firestore.v1beta1.ITransactionOptions|null); + } + + /** Represents a BeginTransactionRequest. */ + class BeginTransactionRequest implements IBeginTransactionRequest { + + /** + * Constructs a new BeginTransactionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBeginTransactionRequest); + + /** BeginTransactionRequest database. */ + public database: string; + + /** BeginTransactionRequest options. */ + public options?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** + * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BeginTransactionRequest; + + /** + * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. + * @param message BeginTransactionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BeginTransactionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionResponse. */ + interface IBeginTransactionResponse { + + /** BeginTransactionResponse transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a BeginTransactionResponse. */ + class BeginTransactionResponse implements IBeginTransactionResponse { + + /** + * Constructs a new BeginTransactionResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBeginTransactionResponse); + + /** BeginTransactionResponse transaction. */ + public transaction: Uint8Array; + + /** + * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BeginTransactionResponse; + + /** + * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. + * @param message BeginTransactionResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BeginTransactionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitRequest. */ + interface ICommitRequest { + + /** CommitRequest database */ + database?: (string|null); + + /** CommitRequest writes */ + writes?: (google.firestore.v1beta1.IWrite[]|null); + + /** CommitRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a CommitRequest. */ + class CommitRequest implements ICommitRequest { + + /** + * Constructs a new CommitRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ICommitRequest); + + /** CommitRequest database. */ + public database: string; + + /** CommitRequest writes. */ + public writes: google.firestore.v1beta1.IWrite[]; + + /** CommitRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.CommitRequest; + + /** + * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. + * @param message CommitRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.CommitRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitResponse. */ + interface ICommitResponse { + + /** CommitResponse writeResults */ + writeResults?: (google.firestore.v1beta1.IWriteResult[]|null); + + /** CommitResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a CommitResponse. */ + class CommitResponse implements ICommitResponse { + + /** + * Constructs a new CommitResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ICommitResponse); + + /** CommitResponse writeResults. */ + public writeResults: google.firestore.v1beta1.IWriteResult[]; + + /** CommitResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.CommitResponse; + + /** + * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. + * @param message CommitResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.CommitResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RollbackRequest. */ + interface IRollbackRequest { + + /** RollbackRequest database */ + database?: (string|null); + + /** RollbackRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a RollbackRequest. */ + class RollbackRequest implements IRollbackRequest { + + /** + * Constructs a new RollbackRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IRollbackRequest); + + /** RollbackRequest database. */ + public database: string; + + /** RollbackRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RollbackRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.RollbackRequest; + + /** + * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. + * @param message RollbackRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.RollbackRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RollbackRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RollbackRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryRequest. */ + interface IRunQueryRequest { + + /** RunQueryRequest parent */ + parent?: (string|null); + + /** RunQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** RunQueryRequest transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction */ + newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** RunQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a RunQueryRequest. */ + class RunQueryRequest implements IRunQueryRequest { + + /** + * Constructs a new RunQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IRunQueryRequest); + + /** RunQueryRequest parent. */ + public parent: string; + + /** RunQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** RunQueryRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction. */ + public newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** RunQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** RunQueryRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.RunQueryRequest; + + /** + * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. + * @param message RunQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.RunQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryResponse. */ + interface IRunQueryResponse { + + /** RunQueryResponse transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryResponse document */ + document?: (google.firestore.v1beta1.IDocument|null); + + /** RunQueryResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults */ + skippedResults?: (number|null); + } + + /** Represents a RunQueryResponse. */ + class RunQueryResponse implements IRunQueryResponse { + + /** + * Constructs a new RunQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IRunQueryResponse); + + /** RunQueryResponse transaction. */ + public transaction: Uint8Array; + + /** RunQueryResponse document. */ + public document?: (google.firestore.v1beta1.IDocument|null); + + /** RunQueryResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults. */ + public skippedResults: number; + + /** + * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.RunQueryResponse; + + /** + * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. + * @param message RunQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.RunQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryRequest. */ + interface IPartitionQueryRequest { + + /** PartitionQueryRequest parent */ + parent?: (string|null); + + /** PartitionQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount */ + partitionCount?: (number|string|null); + + /** PartitionQueryRequest pageToken */ + pageToken?: (string|null); + + /** PartitionQueryRequest pageSize */ + pageSize?: (number|null); + } + + /** Represents a PartitionQueryRequest. */ + class PartitionQueryRequest implements IPartitionQueryRequest { + + /** + * Constructs a new PartitionQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IPartitionQueryRequest); + + /** PartitionQueryRequest parent. */ + public parent: string; + + /** PartitionQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount. */ + public partitionCount: (number|string); + + /** PartitionQueryRequest pageToken. */ + public pageToken: string; + + /** PartitionQueryRequest pageSize. */ + public pageSize: number; + + /** PartitionQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.PartitionQueryRequest; + + /** + * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. + * @param message PartitionQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.PartitionQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryResponse. */ + interface IPartitionQueryResponse { + + /** PartitionQueryResponse partitions */ + partitions?: (google.firestore.v1beta1.ICursor[]|null); + + /** PartitionQueryResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a PartitionQueryResponse. */ + class PartitionQueryResponse implements IPartitionQueryResponse { + + /** + * Constructs a new PartitionQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IPartitionQueryResponse); + + /** PartitionQueryResponse partitions. */ + public partitions: google.firestore.v1beta1.ICursor[]; + + /** PartitionQueryResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.PartitionQueryResponse; + + /** + * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. + * @param message PartitionQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.PartitionQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteRequest. */ + interface IWriteRequest { + + /** WriteRequest database */ + database?: (string|null); + + /** WriteRequest streamId */ + streamId?: (string|null); + + /** WriteRequest writes */ + writes?: (google.firestore.v1beta1.IWrite[]|null); + + /** WriteRequest streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a WriteRequest. */ + class WriteRequest implements IWriteRequest { + + /** + * Constructs a new WriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IWriteRequest); + + /** WriteRequest database. */ + public database: string; + + /** WriteRequest streamId. */ + public streamId: string; + + /** WriteRequest writes. */ + public writes: google.firestore.v1beta1.IWrite[]; + + /** WriteRequest streamToken. */ + public streamToken: Uint8Array; + + /** WriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.WriteRequest; + + /** + * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. + * @param message WriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.WriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteResponse. */ + interface IWriteResponse { + + /** WriteResponse streamId */ + streamId?: (string|null); + + /** WriteResponse streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteResponse writeResults */ + writeResults?: (google.firestore.v1beta1.IWriteResult[]|null); + + /** WriteResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a WriteResponse. */ + class WriteResponse implements IWriteResponse { + + /** + * Constructs a new WriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IWriteResponse); + + /** WriteResponse streamId. */ + public streamId: string; + + /** WriteResponse streamToken. */ + public streamToken: Uint8Array; + + /** WriteResponse writeResults. */ + public writeResults: google.firestore.v1beta1.IWriteResult[]; + + /** WriteResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.WriteResponse; + + /** + * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. + * @param message WriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.WriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenRequest. */ + interface IListenRequest { + + /** ListenRequest database */ + database?: (string|null); + + /** ListenRequest addTarget */ + addTarget?: (google.firestore.v1beta1.ITarget|null); + + /** ListenRequest removeTarget */ + removeTarget?: (number|null); + + /** ListenRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a ListenRequest. */ + class ListenRequest implements IListenRequest { + + /** + * Constructs a new ListenRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListenRequest); + + /** ListenRequest database. */ + public database: string; + + /** ListenRequest addTarget. */ + public addTarget?: (google.firestore.v1beta1.ITarget|null); + + /** ListenRequest removeTarget. */ + public removeTarget?: (number|null); + + /** ListenRequest labels. */ + public labels: { [k: string]: string }; + + /** ListenRequest targetChange. */ + public targetChange?: ("addTarget"|"removeTarget"); + + /** + * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListenRequest; + + /** + * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. + * @param message ListenRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListenRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenResponse. */ + interface IListenResponse { + + /** ListenResponse targetChange */ + targetChange?: (google.firestore.v1beta1.ITargetChange|null); + + /** ListenResponse documentChange */ + documentChange?: (google.firestore.v1beta1.IDocumentChange|null); + + /** ListenResponse documentDelete */ + documentDelete?: (google.firestore.v1beta1.IDocumentDelete|null); + + /** ListenResponse documentRemove */ + documentRemove?: (google.firestore.v1beta1.IDocumentRemove|null); + + /** ListenResponse filter */ + filter?: (google.firestore.v1beta1.IExistenceFilter|null); + } + + /** Represents a ListenResponse. */ + class ListenResponse implements IListenResponse { + + /** + * Constructs a new ListenResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListenResponse); + + /** ListenResponse targetChange. */ + public targetChange?: (google.firestore.v1beta1.ITargetChange|null); + + /** ListenResponse documentChange. */ + public documentChange?: (google.firestore.v1beta1.IDocumentChange|null); + + /** ListenResponse documentDelete. */ + public documentDelete?: (google.firestore.v1beta1.IDocumentDelete|null); + + /** ListenResponse documentRemove. */ + public documentRemove?: (google.firestore.v1beta1.IDocumentRemove|null); + + /** ListenResponse filter. */ + public filter?: (google.firestore.v1beta1.IExistenceFilter|null); + + /** ListenResponse responseType. */ + public responseType?: ("targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"); + + /** + * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListenResponse; + + /** + * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. + * @param message ListenResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListenResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Target. */ + interface ITarget { + + /** Target query */ + query?: (google.firestore.v1beta1.Target.IQueryTarget|null); + + /** Target documents */ + documents?: (google.firestore.v1beta1.Target.IDocumentsTarget|null); + + /** Target resumeToken */ + resumeToken?: (Uint8Array|null); + + /** Target readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId */ + targetId?: (number|null); + + /** Target once */ + once?: (boolean|null); + } + + /** Represents a Target. */ + class Target implements ITarget { + + /** + * Constructs a new Target. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ITarget); + + /** Target query. */ + public query?: (google.firestore.v1beta1.Target.IQueryTarget|null); + + /** Target documents. */ + public documents?: (google.firestore.v1beta1.Target.IDocumentsTarget|null); + + /** Target resumeToken. */ + public resumeToken?: (Uint8Array|null); + + /** Target readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId. */ + public targetId: number; + + /** Target once. */ + public once: boolean; + + /** Target targetType. */ + public targetType?: ("query"|"documents"); + + /** Target resumeType. */ + public resumeType?: ("resumeToken"|"readTime"); + + /** + * Creates a Target message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Target + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Target; + + /** + * Creates a plain object from a Target message. Also converts values to other types if specified. + * @param message Target + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Target, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Target to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Target + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Target { + + /** Properties of a DocumentsTarget. */ + interface IDocumentsTarget { + + /** DocumentsTarget documents */ + documents?: (string[]|null); + } + + /** Represents a DocumentsTarget. */ + class DocumentsTarget implements IDocumentsTarget { + + /** + * Constructs a new DocumentsTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.Target.IDocumentsTarget); + + /** DocumentsTarget documents. */ + public documents: string[]; + + /** + * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentsTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Target.DocumentsTarget; + + /** + * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. + * @param message DocumentsTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Target.DocumentsTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentsTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentsTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a QueryTarget. */ + interface IQueryTarget { + + /** QueryTarget parent */ + parent?: (string|null); + + /** QueryTarget structuredQuery */ + structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + } + + /** Represents a QueryTarget. */ + class QueryTarget implements IQueryTarget { + + /** + * Constructs a new QueryTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.Target.IQueryTarget); + + /** QueryTarget parent. */ + public parent: string; + + /** QueryTarget structuredQuery. */ + public structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** QueryTarget queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QueryTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Target.QueryTarget; + + /** + * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. + * @param message QueryTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Target.QueryTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this QueryTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QueryTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a TargetChange. */ + interface ITargetChange { + + /** TargetChange targetChangeType */ + targetChangeType?: (google.firestore.v1beta1.TargetChange.TargetChangeType|null); + + /** TargetChange targetIds */ + targetIds?: (number[]|null); + + /** TargetChange cause */ + cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken */ + resumeToken?: (Uint8Array|null); + + /** TargetChange readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a TargetChange. */ + class TargetChange implements ITargetChange { + + /** + * Constructs a new TargetChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ITargetChange); + + /** TargetChange targetChangeType. */ + public targetChangeType: google.firestore.v1beta1.TargetChange.TargetChangeType; + + /** TargetChange targetIds. */ + public targetIds: number[]; + + /** TargetChange cause. */ + public cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken. */ + public resumeToken: Uint8Array; + + /** TargetChange readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TargetChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TargetChange; + + /** + * Creates a plain object from a TargetChange message. Also converts values to other types if specified. + * @param message TargetChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.TargetChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TargetChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TargetChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TargetChange { + + /** TargetChangeType enum. */ + type TargetChangeType = + "NO_CHANGE"| "ADD"| "REMOVE"| "CURRENT"| "RESET"; + } + + /** Properties of a ListCollectionIdsRequest. */ + interface IListCollectionIdsRequest { + + /** ListCollectionIdsRequest parent */ + parent?: (string|null); + + /** ListCollectionIdsRequest pageSize */ + pageSize?: (number|null); + + /** ListCollectionIdsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListCollectionIdsRequest. */ + class ListCollectionIdsRequest implements IListCollectionIdsRequest { + + /** + * Constructs a new ListCollectionIdsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListCollectionIdsRequest); + + /** ListCollectionIdsRequest parent. */ + public parent: string; + + /** ListCollectionIdsRequest pageSize. */ + public pageSize: number; + + /** ListCollectionIdsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListCollectionIdsRequest; + + /** + * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. + * @param message ListCollectionIdsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListCollectionIdsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListCollectionIdsResponse. */ + interface IListCollectionIdsResponse { + + /** ListCollectionIdsResponse collectionIds */ + collectionIds?: (string[]|null); + + /** ListCollectionIdsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListCollectionIdsResponse. */ + class ListCollectionIdsResponse implements IListCollectionIdsResponse { + + /** + * Constructs a new ListCollectionIdsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListCollectionIdsResponse); + + /** ListCollectionIdsResponse collectionIds. */ + public collectionIds: string[]; + + /** ListCollectionIdsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListCollectionIdsResponse; + + /** + * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. + * @param message ListCollectionIdsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListCollectionIdsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteRequest. */ + interface IBatchWriteRequest { + + /** BatchWriteRequest database */ + database?: (string|null); + + /** BatchWriteRequest writes */ + writes?: (google.firestore.v1beta1.IWrite[]|null); + + /** BatchWriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a BatchWriteRequest. */ + class BatchWriteRequest implements IBatchWriteRequest { + + /** + * Constructs a new BatchWriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBatchWriteRequest); + + /** BatchWriteRequest database. */ + public database: string; + + /** BatchWriteRequest writes. */ + public writes: google.firestore.v1beta1.IWrite[]; + + /** BatchWriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchWriteRequest; + + /** + * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. + * @param message BatchWriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BatchWriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteResponse. */ + interface IBatchWriteResponse { + + /** BatchWriteResponse writeResults */ + writeResults?: (google.firestore.v1beta1.IWriteResult[]|null); + + /** BatchWriteResponse status */ + status?: (google.rpc.IStatus[]|null); + } + + /** Represents a BatchWriteResponse. */ + class BatchWriteResponse implements IBatchWriteResponse { + + /** + * Constructs a new BatchWriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBatchWriteResponse); + + /** BatchWriteResponse writeResults. */ + public writeResults: google.firestore.v1beta1.IWriteResult[]; + + /** BatchWriteResponse status. */ + public status: google.rpc.IStatus[]; + + /** + * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchWriteResponse; + + /** + * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. + * @param message BatchWriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BatchWriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StructuredQuery. */ + interface IStructuredQuery { + + /** StructuredQuery select */ + select?: (google.firestore.v1beta1.StructuredQuery.IProjection|null); + + /** StructuredQuery from */ + from?: (google.firestore.v1beta1.StructuredQuery.ICollectionSelector[]|null); + + /** StructuredQuery where */ + where?: (google.firestore.v1beta1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy */ + orderBy?: (google.firestore.v1beta1.StructuredQuery.IOrder[]|null); + + /** StructuredQuery startAt */ + startAt?: (google.firestore.v1beta1.ICursor|null); + + /** StructuredQuery endAt */ + endAt?: (google.firestore.v1beta1.ICursor|null); + + /** StructuredQuery offset */ + offset?: (number|null); + + /** StructuredQuery limit */ + limit?: (google.protobuf.IInt32Value|null); + } + + /** Represents a StructuredQuery. */ + class StructuredQuery implements IStructuredQuery { + + /** + * Constructs a new StructuredQuery. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IStructuredQuery); + + /** StructuredQuery select. */ + public select?: (google.firestore.v1beta1.StructuredQuery.IProjection|null); + + /** StructuredQuery from. */ + public from: google.firestore.v1beta1.StructuredQuery.ICollectionSelector[]; + + /** StructuredQuery where. */ + public where?: (google.firestore.v1beta1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy. */ + public orderBy: google.firestore.v1beta1.StructuredQuery.IOrder[]; + + /** StructuredQuery startAt. */ + public startAt?: (google.firestore.v1beta1.ICursor|null); + + /** StructuredQuery endAt. */ + public endAt?: (google.firestore.v1beta1.ICursor|null); + + /** StructuredQuery offset. */ + public offset: number; + + /** StructuredQuery limit. */ + public limit?: (google.protobuf.IInt32Value|null); + + /** + * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredQuery + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery; + + /** + * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. + * @param message StructuredQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructuredQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace StructuredQuery { + + /** Properties of a CollectionSelector. */ + interface ICollectionSelector { + + /** CollectionSelector collectionId */ + collectionId?: (string|null); + + /** CollectionSelector allDescendants */ + allDescendants?: (boolean|null); + } + + /** Represents a CollectionSelector. */ + class CollectionSelector implements ICollectionSelector { + + /** + * Constructs a new CollectionSelector. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.ICollectionSelector); + + /** CollectionSelector collectionId. */ + public collectionId: string; + + /** CollectionSelector allDescendants. */ + public allDescendants: boolean; + + /** + * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CollectionSelector + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.CollectionSelector; + + /** + * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. + * @param message CollectionSelector + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.CollectionSelector, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CollectionSelector to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CollectionSelector + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Filter. */ + interface IFilter { + + /** Filter compositeFilter */ + compositeFilter?: (google.firestore.v1beta1.StructuredQuery.ICompositeFilter|null); + + /** Filter fieldFilter */ + fieldFilter?: (google.firestore.v1beta1.StructuredQuery.IFieldFilter|null); + + /** Filter unaryFilter */ + unaryFilter?: (google.firestore.v1beta1.StructuredQuery.IUnaryFilter|null); + } + + /** Represents a Filter. */ + class Filter implements IFilter { + + /** + * Constructs a new Filter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IFilter); + + /** Filter compositeFilter. */ + public compositeFilter?: (google.firestore.v1beta1.StructuredQuery.ICompositeFilter|null); + + /** Filter fieldFilter. */ + public fieldFilter?: (google.firestore.v1beta1.StructuredQuery.IFieldFilter|null); + + /** Filter unaryFilter. */ + public unaryFilter?: (google.firestore.v1beta1.StructuredQuery.IUnaryFilter|null); + + /** Filter filterType. */ + public filterType?: ("compositeFilter"|"fieldFilter"|"unaryFilter"); + + /** + * Creates a Filter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Filter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.Filter; + + /** + * Creates a plain object from a Filter message. Also converts values to other types if specified. + * @param message Filter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.Filter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Filter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Filter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CompositeFilter. */ + interface ICompositeFilter { + + /** CompositeFilter op */ + op?: (google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator|null); + + /** CompositeFilter filters */ + filters?: (google.firestore.v1beta1.StructuredQuery.IFilter[]|null); + } + + /** Represents a CompositeFilter. */ + class CompositeFilter implements ICompositeFilter { + + /** + * Constructs a new CompositeFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.ICompositeFilter); + + /** CompositeFilter op. */ + public op: google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator; + + /** CompositeFilter filters. */ + public filters: google.firestore.v1beta1.StructuredQuery.IFilter[]; + + /** + * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CompositeFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.CompositeFilter; + + /** + * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. + * @param message CompositeFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.CompositeFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CompositeFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CompositeFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace CompositeFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "AND"; + } + + /** Properties of a FieldFilter. */ + interface IFieldFilter { + + /** FieldFilter field */ + field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op */ + op?: (google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator|null); + + /** FieldFilter value */ + value?: (google.firestore.v1beta1.IValue|null); + } + + /** Represents a FieldFilter. */ + class FieldFilter implements IFieldFilter { + + /** + * Constructs a new FieldFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IFieldFilter); + + /** FieldFilter field. */ + public field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op. */ + public op: google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator; + + /** FieldFilter value. */ + public value?: (google.firestore.v1beta1.IValue|null); + + /** + * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.FieldFilter; + + /** + * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. + * @param message FieldFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.FieldFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "LESS_THAN"| "LESS_THAN_OR_EQUAL"| "GREATER_THAN"| "GREATER_THAN_OR_EQUAL"| "EQUAL"| "NOT_EQUAL"| "ARRAY_CONTAINS"| "IN"| "ARRAY_CONTAINS_ANY"| "NOT_IN"; + } + + /** Properties of an UnaryFilter. */ + interface IUnaryFilter { + + /** UnaryFilter op */ + op?: (google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator|null); + + /** UnaryFilter field */ + field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + } + + /** Represents an UnaryFilter. */ + class UnaryFilter implements IUnaryFilter { + + /** + * Constructs a new UnaryFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IUnaryFilter); + + /** UnaryFilter op. */ + public op: google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator; + + /** UnaryFilter field. */ + public field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** UnaryFilter operandType. */ + public operandType?: "field"; + + /** + * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UnaryFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.UnaryFilter; + + /** + * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. + * @param message UnaryFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.UnaryFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UnaryFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UnaryFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UnaryFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "IS_NAN"| "IS_NULL"| "IS_NOT_NAN"| "IS_NOT_NULL"; + } + + /** Properties of a FieldReference. */ + interface IFieldReference { + + /** FieldReference fieldPath */ + fieldPath?: (string|null); + } + + /** Represents a FieldReference. */ + class FieldReference implements IFieldReference { + + /** + * Constructs a new FieldReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IFieldReference); + + /** FieldReference fieldPath. */ + public fieldPath: string; + + /** + * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldReference + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.FieldReference; + + /** + * Creates a plain object from a FieldReference message. Also converts values to other types if specified. + * @param message FieldReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.FieldReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Order. */ + interface IOrder { + + /** Order field */ + field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** Order direction */ + direction?: (google.firestore.v1beta1.StructuredQuery.Direction|null); + } + + /** Represents an Order. */ + class Order implements IOrder { + + /** + * Constructs a new Order. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IOrder); + + /** Order field. */ + public field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** Order direction. */ + public direction: google.firestore.v1beta1.StructuredQuery.Direction; + + /** + * Creates an Order message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Order + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.Order; + + /** + * Creates a plain object from an Order message. Also converts values to other types if specified. + * @param message Order + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.Order, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Order to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Order + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Projection. */ + interface IProjection { + + /** Projection fields */ + fields?: (google.firestore.v1beta1.StructuredQuery.IFieldReference[]|null); + } + + /** Represents a Projection. */ + class Projection implements IProjection { + + /** + * Constructs a new Projection. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IProjection); + + /** Projection fields. */ + public fields: google.firestore.v1beta1.StructuredQuery.IFieldReference[]; + + /** + * Creates a Projection message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Projection + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.Projection; + + /** + * Creates a plain object from a Projection message. Also converts values to other types if specified. + * @param message Projection + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.Projection, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Projection to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Projection + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Direction enum. */ + type Direction = + "DIRECTION_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; + } + + /** Properties of a Cursor. */ + interface ICursor { + + /** Cursor values */ + values?: (google.firestore.v1beta1.IValue[]|null); + + /** Cursor before */ + before?: (boolean|null); + } + + /** Represents a Cursor. */ + class Cursor implements ICursor { + + /** + * Constructs a new Cursor. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ICursor); + + /** Cursor values. */ + public values: google.firestore.v1beta1.IValue[]; + + /** Cursor before. */ + public before: boolean; + + /** + * Creates a Cursor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Cursor + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Cursor; + + /** + * Creates a plain object from a Cursor message. Also converts values to other types if specified. + * @param message Cursor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Cursor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Cursor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Cursor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Write. */ + interface IWrite { + + /** Write update */ + update?: (google.firestore.v1beta1.IDocument|null); + + /** Write delete */ + "delete"?: (string|null); + + /** Write transform */ + transform?: (google.firestore.v1beta1.IDocumentTransform|null); + + /** Write updateMask */ + updateMask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** Write updateTransforms */ + updateTransforms?: (google.firestore.v1beta1.DocumentTransform.IFieldTransform[]|null); + + /** Write currentDocument */ + currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + } + + /** Represents a Write. */ + class Write implements IWrite { + + /** + * Constructs a new Write. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IWrite); + + /** Write update. */ + public update?: (google.firestore.v1beta1.IDocument|null); + + /** Write delete. */ + public delete?: (string|null); + + /** Write transform. */ + public transform?: (google.firestore.v1beta1.IDocumentTransform|null); + + /** Write updateMask. */ + public updateMask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** Write updateTransforms. */ + public updateTransforms: google.firestore.v1beta1.DocumentTransform.IFieldTransform[]; + + /** Write currentDocument. */ + public currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + + /** Write operation. */ + public operation?: ("update"|"delete"|"transform"); + + /** + * Creates a Write message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Write + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Write; + + /** + * Creates a plain object from a Write message. Also converts values to other types if specified. + * @param message Write + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Write, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Write to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Write + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentTransform. */ + interface IDocumentTransform { + + /** DocumentTransform document */ + document?: (string|null); + + /** DocumentTransform fieldTransforms */ + fieldTransforms?: (google.firestore.v1beta1.DocumentTransform.IFieldTransform[]|null); + } + + /** Represents a DocumentTransform. */ + class DocumentTransform implements IDocumentTransform { + + /** + * Constructs a new DocumentTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentTransform); + + /** DocumentTransform document. */ + public document: string; + + /** DocumentTransform fieldTransforms. */ + public fieldTransforms: google.firestore.v1beta1.DocumentTransform.IFieldTransform[]; + + /** + * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentTransform; + + /** + * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. + * @param message DocumentTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DocumentTransform { + + /** Properties of a FieldTransform. */ + interface IFieldTransform { + + /** FieldTransform fieldPath */ + fieldPath?: (string|null); + + /** FieldTransform setToServerValue */ + setToServerValue?: (google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment */ + increment?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform maximum */ + maximum?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform minimum */ + minimum?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform appendMissingElements */ + appendMissingElements?: (google.firestore.v1beta1.IArrayValue|null); + + /** FieldTransform removeAllFromArray */ + removeAllFromArray?: (google.firestore.v1beta1.IArrayValue|null); + } + + /** Represents a FieldTransform. */ + class FieldTransform implements IFieldTransform { + + /** + * Constructs a new FieldTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.DocumentTransform.IFieldTransform); + + /** FieldTransform fieldPath. */ + public fieldPath: string; + + /** FieldTransform setToServerValue. */ + public setToServerValue?: (google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment. */ + public increment?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform maximum. */ + public maximum?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform minimum. */ + public minimum?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform appendMissingElements. */ + public appendMissingElements?: (google.firestore.v1beta1.IArrayValue|null); + + /** FieldTransform removeAllFromArray. */ + public removeAllFromArray?: (google.firestore.v1beta1.IArrayValue|null); + + /** FieldTransform transformType. */ + public transformType?: ("setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"); + + /** + * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentTransform.FieldTransform; + + /** + * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. + * @param message FieldTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentTransform.FieldTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldTransform { + + /** ServerValue enum. */ + type ServerValue = + "SERVER_VALUE_UNSPECIFIED"| "REQUEST_TIME"; + } + } + + /** Properties of a WriteResult. */ + interface IWriteResult { + + /** WriteResult updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** WriteResult transformResults */ + transformResults?: (google.firestore.v1beta1.IValue[]|null); + } + + /** Represents a WriteResult. */ + class WriteResult implements IWriteResult { + + /** + * Constructs a new WriteResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IWriteResult); + + /** WriteResult updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** WriteResult transformResults. */ + public transformResults: google.firestore.v1beta1.IValue[]; + + /** + * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResult + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.WriteResult; + + /** + * Creates a plain object from a WriteResult message. Also converts values to other types if specified. + * @param message WriteResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.WriteResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentChange. */ + interface IDocumentChange { + + /** DocumentChange document */ + document?: (google.firestore.v1beta1.IDocument|null); + + /** DocumentChange targetIds */ + targetIds?: (number[]|null); + + /** DocumentChange removedTargetIds */ + removedTargetIds?: (number[]|null); + } + + /** Represents a DocumentChange. */ + class DocumentChange implements IDocumentChange { + + /** + * Constructs a new DocumentChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentChange); + + /** DocumentChange document. */ + public document?: (google.firestore.v1beta1.IDocument|null); + + /** DocumentChange targetIds. */ + public targetIds: number[]; + + /** DocumentChange removedTargetIds. */ + public removedTargetIds: number[]; + + /** + * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentChange; + + /** + * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. + * @param message DocumentChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentDelete. */ + interface IDocumentDelete { + + /** DocumentDelete document */ + document?: (string|null); + + /** DocumentDelete removedTargetIds */ + removedTargetIds?: (number[]|null); + + /** DocumentDelete readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a DocumentDelete. */ + class DocumentDelete implements IDocumentDelete { + + /** + * Constructs a new DocumentDelete. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentDelete); + + /** DocumentDelete document. */ + public document: string; + + /** DocumentDelete removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentDelete readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentDelete + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentDelete; + + /** + * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. + * @param message DocumentDelete + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentDelete, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentDelete to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentDelete + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentRemove. */ + interface IDocumentRemove { + + /** DocumentRemove document */ + document?: (string|null); + + /** DocumentRemove removedTargetIds */ + removedTargetIds?: (number[]|null); + + /** DocumentRemove readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a DocumentRemove. */ + class DocumentRemove implements IDocumentRemove { + + /** + * Constructs a new DocumentRemove. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentRemove); + + /** DocumentRemove document. */ + public document: string; + + /** DocumentRemove removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentRemove readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentRemove + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentRemove; + + /** + * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. + * @param message DocumentRemove + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentRemove, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentRemove to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentRemove + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExistenceFilter. */ + interface IExistenceFilter { + + /** ExistenceFilter targetId */ + targetId?: (number|null); + + /** ExistenceFilter count */ + count?: (number|null); + } + + /** Represents an ExistenceFilter. */ + class ExistenceFilter implements IExistenceFilter { + + /** + * Constructs a new ExistenceFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IExistenceFilter); + + /** ExistenceFilter targetId. */ + public targetId: number; + + /** ExistenceFilter count. */ + public count: number; + + /** + * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExistenceFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ExistenceFilter; + + /** + * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. + * @param message ExistenceFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ExistenceFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExistenceFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExistenceFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UndeliverableFirstGenEvent. */ + interface IUndeliverableFirstGenEvent { + + /** UndeliverableFirstGenEvent message */ + message?: (string|null); + + /** UndeliverableFirstGenEvent reason */ + reason?: (google.firestore.v1beta1.UndeliverableFirstGenEvent.Reason|null); + + /** UndeliverableFirstGenEvent documentName */ + documentName?: (string|null); + + /** UndeliverableFirstGenEvent documentChangeType */ + documentChangeType?: (google.firestore.v1beta1.UndeliverableFirstGenEvent.DocumentChangeType|null); + + /** UndeliverableFirstGenEvent functionName */ + functionName?: (string[]|null); + + /** UndeliverableFirstGenEvent triggeredTime */ + triggeredTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an UndeliverableFirstGenEvent. */ + class UndeliverableFirstGenEvent implements IUndeliverableFirstGenEvent { + + /** + * Constructs a new UndeliverableFirstGenEvent. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IUndeliverableFirstGenEvent); + + /** UndeliverableFirstGenEvent message. */ + public message: string; + + /** UndeliverableFirstGenEvent reason. */ + public reason: google.firestore.v1beta1.UndeliverableFirstGenEvent.Reason; + + /** UndeliverableFirstGenEvent documentName. */ + public documentName: string; + + /** UndeliverableFirstGenEvent documentChangeType. */ + public documentChangeType: google.firestore.v1beta1.UndeliverableFirstGenEvent.DocumentChangeType; + + /** UndeliverableFirstGenEvent functionName. */ + public functionName: string[]; + + /** UndeliverableFirstGenEvent triggeredTime. */ + public triggeredTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates an UndeliverableFirstGenEvent message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UndeliverableFirstGenEvent + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.UndeliverableFirstGenEvent; + + /** + * Creates a plain object from an UndeliverableFirstGenEvent message. Also converts values to other types if specified. + * @param message UndeliverableFirstGenEvent + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.UndeliverableFirstGenEvent, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UndeliverableFirstGenEvent to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UndeliverableFirstGenEvent + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UndeliverableFirstGenEvent { + + /** Reason enum. */ + type Reason = + "REASON_UNSPECIFIED"| "EXCEEDING_SIZE_LIMIT"; + + /** DocumentChangeType enum. */ + type DocumentChangeType = + "DOCUMENT_CHANGE_TYPE_UNSPECIFIED"| "CREATE"| "DELETE"| "UPDATE"; + } + } + } + + /** Namespace type. */ + namespace type { + + /** Properties of a LatLng. */ + interface ILatLng { + + /** LatLng latitude */ + latitude?: (number|null); + + /** LatLng longitude */ + longitude?: (number|null); + } + + /** Represents a LatLng. */ + class LatLng implements ILatLng { + + /** + * Constructs a new LatLng. + * @param [properties] Properties to set + */ + constructor(properties?: google.type.ILatLng); + + /** LatLng latitude. */ + public latitude: number; + + /** LatLng longitude. */ + public longitude: number; + + /** + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LatLng + */ + public static fromObject(object: { [k: string]: any }): google.type.LatLng; + + /** + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @param message LatLng + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LatLng to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LatLng + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** DayOfWeek enum. */ + type DayOfWeek = + "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; + } + + /** Namespace api. */ + namespace api { + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { + + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); + + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + } + + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { + + /** + * Constructs a new CommonLanguageSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICommonLanguageSettings); + + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; + + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; + + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommonLanguageSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { + + /** ClientLibrarySettings version */ + version?: (string|null); + + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|null); + + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); + + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } + + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { + + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); + + /** ClientLibrarySettings version. */ + public version: string; + + /** ClientLibrarySettings launchStage. */ + public launchStage: google.api.LaunchStage; + + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; + + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Publishing. */ + interface IPublishing { + + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); + + /** Publishing newIssueUri */ + newIssueUri?: (string|null); + + /** Publishing documentationUri */ + documentationUri?: (string|null); + + /** Publishing apiShortName */ + apiShortName?: (string|null); + + /** Publishing githubLabel */ + githubLabel?: (string|null); + + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); + + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); + + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|null); + + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); + + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); + + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } + + /** Represents a Publishing. */ + class Publishing implements IPublishing { + + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); + + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; + + /** Publishing newIssueUri. */ + public newIssueUri: string; + + /** Publishing documentationUri. */ + public documentationUri: string; + + /** Publishing apiShortName. */ + public apiShortName: string; + + /** Publishing githubLabel. */ + public githubLabel: string; + + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; + + /** Publishing docTagPrefix. */ + public docTagPrefix: string; + + /** Publishing organization. */ + public organization: google.api.ClientLibraryOrganization; + + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; + + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; + + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a JavaSettings. */ + interface IJavaSettings { + + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); + + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); + + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { + + /** + * Constructs a new JavaSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IJavaSettings); + + /** JavaSettings libraryPackage. */ + public libraryPackage: string; + + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; + + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns JavaSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this JavaSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CppSettings. */ + interface ICppSettings { + + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { + + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); + + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PhpSettings. */ + interface IPhpSettings { + + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { + + /** + * Constructs a new PhpSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPhpSettings); + + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PythonSettings. */ + interface IPythonSettings { + + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + } + + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { + + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); + + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PythonSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PythonSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PythonSettings { + + /** Properties of an ExperimentalFeatures. */ + interface IExperimentalFeatures { + + /** ExperimentalFeatures restAsyncIoEnabled */ + restAsyncIoEnabled?: (boolean|null); + + /** ExperimentalFeatures protobufPythonicTypesEnabled */ + protobufPythonicTypesEnabled?: (boolean|null); + + /** ExperimentalFeatures unversionedPackageDisabled */ + unversionedPackageDisabled?: (boolean|null); + } + + /** Represents an ExperimentalFeatures. */ + class ExperimentalFeatures implements IExperimentalFeatures { + + /** + * Constructs a new ExperimentalFeatures. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.PythonSettings.IExperimentalFeatures); + + /** ExperimentalFeatures restAsyncIoEnabled. */ + public restAsyncIoEnabled: boolean; + + /** ExperimentalFeatures protobufPythonicTypesEnabled. */ + public protobufPythonicTypesEnabled: boolean; + + /** ExperimentalFeatures unversionedPackageDisabled. */ + public unversionedPackageDisabled: boolean; + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExperimentalFeatures + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @param message ExperimentalFeatures + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings.ExperimentalFeatures, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExperimentalFeatures + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a NodeSettings. */ + interface INodeSettings { + + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { + + /** + * Constructs a new NodeSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.INodeSettings); + + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NodeSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NodeSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { + + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); + + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); + + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); + + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); + } + + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { + + /** + * Constructs a new DotnetSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IDotnetSettings); + + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; + + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; + + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; + + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DotnetSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DotnetSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RubySettings. */ + interface IRubySettings { + + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { + + /** + * Constructs a new RubySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRubySettings); + + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GoSettings. */ + interface IGoSettings { + + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + } + + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { + + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); + + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodSettings. */ + interface IMethodSettings { + + /** MethodSettings selector */ + selector?: (string|null); + + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); + } + + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { + + /** + * Constructs a new MethodSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IMethodSettings); + + /** MethodSettings selector. */ + public selector: string; + + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodSettings { + + /** Properties of a LongRunning. */ + interface ILongRunning { + + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); + + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); + } + + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { + + /** + * Constructs a new LongRunning. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.MethodSettings.ILongRunning); + + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; + + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LongRunning + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LongRunning to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LongRunning + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** ClientLibraryOrganization enum. */ + type ClientLibraryOrganization = + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; + + /** ClientLibraryDestination enum. */ + type ClientLibraryDestination = + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; + + /** Properties of a SelectiveGapicGeneration. */ + interface ISelectiveGapicGeneration { + + /** SelectiveGapicGeneration methods */ + methods?: (string[]|null); + + /** SelectiveGapicGeneration generateOmittedAsInternal */ + generateOmittedAsInternal?: (boolean|null); + } + + /** Represents a SelectiveGapicGeneration. */ + class SelectiveGapicGeneration implements ISelectiveGapicGeneration { + + /** + * Constructs a new SelectiveGapicGeneration. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ISelectiveGapicGeneration); + + /** SelectiveGapicGeneration methods. */ + public methods: string[]; + + /** SelectiveGapicGeneration generateOmittedAsInternal. */ + public generateOmittedAsInternal: boolean; + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SelectiveGapicGeneration + */ + public static fromObject(object: { [k: string]: any }): google.api.SelectiveGapicGeneration; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @param message SelectiveGapicGeneration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.SelectiveGapicGeneration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; + + /** FieldBehavior enum. */ + type FieldBehavior = + "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; + + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { + + /** ResourceDescriptor type */ + type?: (string|null); + + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); + + /** ResourceDescriptor nameField */ + nameField?: (string|null); + + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|null); + + /** ResourceDescriptor plural */ + plural?: (string|null); + + /** ResourceDescriptor singular */ + singular?: (string|null); + + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } + + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { + + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); + + /** ResourceDescriptor type. */ + public type: string; + + /** ResourceDescriptor pattern. */ + public pattern: string[]; + + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: google.api.ResourceDescriptor.History; + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ResourceDescriptor { + + /** History enum. */ + type History = + "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; + + /** Style enum. */ + type Style = + "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + } + + /** Properties of a ResourceReference. */ + interface IResourceReference { + + /** ResourceReference type */ + type?: (string|null); + + /** ResourceReference childType */ + childType?: (string|null); + } + + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { + + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); + + /** ResourceReference type. */ + public type: string; + + /** ResourceReference childType. */ + public childType: string; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RoutingRule. */ + interface IRoutingRule { + + /** RoutingRule routingParameters */ + routingParameters?: (google.api.IRoutingParameter[]|null); + } + + /** Represents a RoutingRule. */ + class RoutingRule implements IRoutingRule { + + /** + * Constructs a new RoutingRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRoutingRule); + + /** RoutingRule routingParameters. */ + public routingParameters: google.api.IRoutingParameter[]; + + /** + * Creates a RoutingRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingRule + */ + public static fromObject(object: { [k: string]: any }): google.api.RoutingRule; + + /** + * Creates a plain object from a RoutingRule message. Also converts values to other types if specified. + * @param message RoutingRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RoutingRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RoutingParameter. */ + interface IRoutingParameter { + + /** RoutingParameter field */ + field?: (string|null); + + /** RoutingParameter pathTemplate */ + pathTemplate?: (string|null); + } + + /** Represents a RoutingParameter. */ + class RoutingParameter implements IRoutingParameter { + + /** + * Constructs a new RoutingParameter. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRoutingParameter); + + /** RoutingParameter field. */ + public field: string; + + /** RoutingParameter pathTemplate. */ + public pathTemplate: string; + + /** + * Creates a RoutingParameter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingParameter + */ + public static fromObject(object: { [k: string]: any }): google.api.RoutingParameter; + + /** + * Creates a plain object from a RoutingParameter message. Also converts values to other types if specified. + * @param message RoutingParameter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RoutingParameter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingParameter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingParameter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace rpc. */ + namespace rpc { + + /** Properties of a Status. */ + interface IStatus { + + /** Status code */ + code?: (number|null); + + /** Status message */ + message?: (string|null); + + /** Status details */ + details?: (google.protobuf.IAny[]|null); + } + + /** Represents a Status. */ + class Status implements IStatus { + + /** + * Constructs a new Status. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IStatus); + + /** Status code. */ + public code: number; + + /** Status message. */ + public message: string; + + /** Status details. */ + public details: google.protobuf.IAny[]; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Status + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Status; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @param message Status + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Status to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Status + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace longrunning. */ + namespace longrunning { + + /** Represents an Operations */ + class Operations extends $protobuf.rpc.Service { + + /** + * Constructs a new Operations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListOperationsResponse + */ + public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void; + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @returns Promise + */ + public listOperations(request: google.longrunning.IListOperationsRequest): Promise; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @returns Promise + */ + public getOperation(request: google.longrunning.IGetOperationRequest): Promise; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @returns Promise + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @returns Promise + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @returns Promise + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise; + } + + namespace Operations { + + /** + * Callback as used by {@link google.longrunning.Operations#listOperations}. + * @param error Error, if any + * @param [response] ListOperationsResponse + */ + type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#getOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#deleteOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#cancelOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#waitOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of an Operation. */ + interface IOperation { + + /** Operation name */ + name?: (string|null); + + /** Operation metadata */ + metadata?: (google.protobuf.IAny|null); + + /** Operation done */ + done?: (boolean|null); + + /** Operation error */ + error?: (google.rpc.IStatus|null); + + /** Operation response */ + response?: (google.protobuf.IAny|null); + } + + /** Represents an Operation. */ + class Operation implements IOperation { + + /** + * Constructs a new Operation. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperation); + + /** Operation name. */ + public name: string; + + /** Operation metadata. */ + public metadata?: (google.protobuf.IAny|null); + + /** Operation done. */ + public done: boolean; + + /** Operation error. */ + public error?: (google.rpc.IStatus|null); + + /** Operation response. */ + public response?: (google.protobuf.IAny|null); + + /** Operation result. */ + public result?: ("error"|"response"); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Operation + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.Operation; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @param message Operation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Operation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Operation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetOperationRequest. */ + interface IGetOperationRequest { + + /** GetOperationRequest name */ + name?: (string|null); + } + + /** Represents a GetOperationRequest. */ + class GetOperationRequest implements IGetOperationRequest { + + /** + * Constructs a new GetOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IGetOperationRequest); + + /** GetOperationRequest name. */ + public name: string; + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @param message GetOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsRequest. */ + interface IListOperationsRequest { + + /** ListOperationsRequest name */ + name?: (string|null); + + /** ListOperationsRequest filter */ + filter?: (string|null); + + /** ListOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListOperationsRequest pageToken */ + pageToken?: (string|null); + + /** ListOperationsRequest returnPartialSuccess */ + returnPartialSuccess?: (boolean|null); + } + + /** Represents a ListOperationsRequest. */ + class ListOperationsRequest implements IListOperationsRequest { + + /** + * Constructs a new ListOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsRequest); + + /** ListOperationsRequest name. */ + public name: string; + + /** ListOperationsRequest filter. */ + public filter: string; + + /** ListOperationsRequest pageSize. */ + public pageSize: number; + + /** ListOperationsRequest pageToken. */ + public pageToken: string; + + /** ListOperationsRequest returnPartialSuccess. */ + public returnPartialSuccess: boolean; + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @param message ListOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsResponse. */ + interface IListOperationsResponse { + + /** ListOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + + /** ListOperationsResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListOperationsResponse. */ + class ListOperationsResponse implements IListOperationsResponse { + + /** + * Constructs a new ListOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsResponse); + + /** ListOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** ListOperationsResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @param message ListOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CancelOperationRequest. */ + interface ICancelOperationRequest { + + /** CancelOperationRequest name */ + name?: (string|null); + } + + /** Represents a CancelOperationRequest. */ + class CancelOperationRequest implements ICancelOperationRequest { + + /** + * Constructs a new CancelOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.ICancelOperationRequest); + + /** CancelOperationRequest name. */ + public name: string; + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CancelOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @param message CancelOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CancelOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteOperationRequest. */ + interface IDeleteOperationRequest { + + /** DeleteOperationRequest name */ + name?: (string|null); + } + + /** Represents a DeleteOperationRequest. */ + class DeleteOperationRequest implements IDeleteOperationRequest { + + /** + * Constructs a new DeleteOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IDeleteOperationRequest); + + /** DeleteOperationRequest name. */ + public name: string; + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @param message DeleteOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WaitOperationRequest. */ + interface IWaitOperationRequest { + + /** WaitOperationRequest name */ + name?: (string|null); + + /** WaitOperationRequest timeout */ + timeout?: (google.protobuf.IDuration|null); + } + + /** Represents a WaitOperationRequest. */ + class WaitOperationRequest implements IWaitOperationRequest { + + /** + * Constructs a new WaitOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IWaitOperationRequest); + + /** WaitOperationRequest name. */ + public name: string; + + /** WaitOperationRequest timeout. */ + public timeout?: (google.protobuf.IDuration|null); + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @param message WaitOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WaitOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an OperationInfo. */ + interface IOperationInfo { + + /** OperationInfo responseType */ + responseType?: (string|null); + + /** OperationInfo metadataType */ + metadataType?: (string|null); + } + + /** Represents an OperationInfo. */ + class OperationInfo implements IOperationInfo { + + /** + * Constructs a new OperationInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperationInfo); + + /** OperationInfo responseType. */ + public responseType: string; + + /** OperationInfo metadataType. */ + public metadataType: string; + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationInfo + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @param message OperationInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } +} diff --git a/handwritten/firestore/dev/protos/firestore_v1beta1_proto_api.js b/handwritten/firestore/dev/protos/firestore_v1beta1_proto_api.js new file mode 100644 index 00000000000..0b957aa0555 --- /dev/null +++ b/handwritten/firestore/dev/protos/firestore_v1beta1_proto_api.js @@ -0,0 +1,23235 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/ +(function(global, factory) { /* global define, require, module */ + + /* AMD */ if (typeof define === 'function' && define.amd) + define(["protobufjs/minimal"], factory); + + /* CommonJS */ else if (typeof require === 'function' && typeof module === 'object' && module && module.exports) + module.exports = factory(require("protobufjs/minimal")); + +})(this, function($protobuf) { + "use strict"; + + // Common aliases + var $util = $protobuf.util; + + // Exported root namespace + var $root = $protobuf.roots.firestore_v1beta1 || ($protobuf.roots.firestore_v1beta1 = {}); + + $root.google = (function() { + + /** + * Namespace google. + * @exports google + * @namespace + */ + var google = {}; + + google.protobuf = (function() { + + /** + * Namespace protobuf. + * @memberof google + * @namespace + */ + var protobuf = {}; + + protobuf.Timestamp = (function() { + + /** + * Properties of a Timestamp. + * @memberof google.protobuf + * @interface ITimestamp + * @property {number|string|null} [seconds] Timestamp seconds + * @property {number|null} [nanos] Timestamp nanos + */ + + /** + * Constructs a new Timestamp. + * @memberof google.protobuf + * @classdesc Represents a Timestamp. + * @implements ITimestamp + * @constructor + * @param {google.protobuf.ITimestamp=} [properties] Properties to set + */ + function Timestamp(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Timestamp seconds. + * @member {number|string} seconds + * @memberof google.protobuf.Timestamp + * @instance + */ + Timestamp.prototype.seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Timestamp nanos. + * @member {number} nanos + * @memberof google.protobuf.Timestamp + * @instance + */ + Timestamp.prototype.nanos = 0; + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Timestamp + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Timestamp} Timestamp + */ + Timestamp.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Timestamp) + return object; + var message = new $root.google.protobuf.Timestamp(); + if (object.seconds != null) + if ($util.Long) + (message.seconds = $util.Long.fromValue(object.seconds)).unsigned = false; + else if (typeof object.seconds === "string") + message.seconds = parseInt(object.seconds, 10); + else if (typeof object.seconds === "number") + message.seconds = object.seconds; + else if (typeof object.seconds === "object") + message.seconds = new $util.LongBits(object.seconds.low >>> 0, object.seconds.high >>> 0).toNumber(); + if (object.nanos != null) + message.nanos = object.nanos | 0; + return message; + }; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Timestamp + * @static + * @param {google.protobuf.Timestamp} message Timestamp + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Timestamp.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.seconds = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.seconds = options.longs === String ? "0" : 0; + object.nanos = 0; + } + if (message.seconds != null && message.hasOwnProperty("seconds")) + if (typeof message.seconds === "number") + object.seconds = options.longs === String ? String(message.seconds) : message.seconds; + else + object.seconds = options.longs === String ? $util.Long.prototype.toString.call(message.seconds) : options.longs === Number ? new $util.LongBits(message.seconds.low >>> 0, message.seconds.high >>> 0).toNumber() : message.seconds; + if (message.nanos != null && message.hasOwnProperty("nanos")) + object.nanos = message.nanos; + return object; + }; + + /** + * Converts this Timestamp to JSON. + * @function toJSON + * @memberof google.protobuf.Timestamp + * @instance + * @returns {Object.} JSON object + */ + Timestamp.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Timestamp + * @function getTypeUrl + * @memberof google.protobuf.Timestamp + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Timestamp.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Timestamp"; + }; + + return Timestamp; + })(); + + protobuf.Struct = (function() { + + /** + * Properties of a Struct. + * @memberof google.protobuf + * @interface IStruct + * @property {Object.|null} [fields] Struct fields + */ + + /** + * Constructs a new Struct. + * @memberof google.protobuf + * @classdesc Represents a Struct. + * @implements IStruct + * @constructor + * @param {google.protobuf.IStruct=} [properties] Properties to set + */ + function Struct(properties) { + this.fields = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Struct fields. + * @member {Object.} fields + * @memberof google.protobuf.Struct + * @instance + */ + Struct.prototype.fields = $util.emptyObject; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Struct + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Struct} Struct + */ + Struct.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Struct) + return object; + var message = new $root.google.protobuf.Struct(); + if (object.fields) { + if (typeof object.fields !== "object") + throw TypeError(".google.protobuf.Struct.fields: object expected"); + message.fields = {}; + for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { + if (typeof object.fields[keys[i]] !== "object") + throw TypeError(".google.protobuf.Struct.fields: object expected"); + message.fields[keys[i]] = $root.google.protobuf.Value.fromObject(object.fields[keys[i]]); + } + } + return message; + }; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Struct + * @static + * @param {google.protobuf.Struct} message Struct + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Struct.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.fields = {}; + var keys2; + if (message.fields && (keys2 = Object.keys(message.fields)).length) { + object.fields = {}; + for (var j = 0; j < keys2.length; ++j) + object.fields[keys2[j]] = $root.google.protobuf.Value.toObject(message.fields[keys2[j]], options); + } + return object; + }; + + /** + * Converts this Struct to JSON. + * @function toJSON + * @memberof google.protobuf.Struct + * @instance + * @returns {Object.} JSON object + */ + Struct.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Struct + * @function getTypeUrl + * @memberof google.protobuf.Struct + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Struct.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Struct"; + }; + + return Struct; + })(); + + protobuf.Value = (function() { + + /** + * Properties of a Value. + * @memberof google.protobuf + * @interface IValue + * @property {google.protobuf.NullValue|null} [nullValue] Value nullValue + * @property {number|null} [numberValue] Value numberValue + * @property {string|null} [stringValue] Value stringValue + * @property {boolean|null} [boolValue] Value boolValue + * @property {google.protobuf.IStruct|null} [structValue] Value structValue + * @property {google.protobuf.IListValue|null} [listValue] Value listValue + */ + + /** + * Constructs a new Value. + * @memberof google.protobuf + * @classdesc Represents a Value. + * @implements IValue + * @constructor + * @param {google.protobuf.IValue=} [properties] Properties to set + */ + function Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Value nullValue. + * @member {google.protobuf.NullValue|null|undefined} nullValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.nullValue = null; + + /** + * Value numberValue. + * @member {number|null|undefined} numberValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.numberValue = null; + + /** + * Value stringValue. + * @member {string|null|undefined} stringValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.stringValue = null; + + /** + * Value boolValue. + * @member {boolean|null|undefined} boolValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.boolValue = null; + + /** + * Value structValue. + * @member {google.protobuf.IStruct|null|undefined} structValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.structValue = null; + + /** + * Value listValue. + * @member {google.protobuf.IListValue|null|undefined} listValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.listValue = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Value kind. + * @member {"nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"|undefined} kind + * @memberof google.protobuf.Value + * @instance + */ + Object.defineProperty(Value.prototype, "kind", { + get: $util.oneOfGetter($oneOfFields = ["nullValue", "numberValue", "stringValue", "boolValue", "structValue", "listValue"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Value + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Value} Value + */ + Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Value) + return object; + var message = new $root.google.protobuf.Value(); + switch (object.nullValue) { + default: + if (typeof object.nullValue === "number") { + message.nullValue = object.nullValue; + break; + } + break; + case "NULL_VALUE": + case 0: + message.nullValue = 0; + break; + } + if (object.numberValue != null) + message.numberValue = Number(object.numberValue); + if (object.stringValue != null) + message.stringValue = String(object.stringValue); + if (object.boolValue != null) + message.boolValue = Boolean(object.boolValue); + if (object.structValue != null) { + if (typeof object.structValue !== "object") + throw TypeError(".google.protobuf.Value.structValue: object expected"); + message.structValue = $root.google.protobuf.Struct.fromObject(object.structValue); + } + if (object.listValue != null) { + if (typeof object.listValue !== "object") + throw TypeError(".google.protobuf.Value.listValue: object expected"); + message.listValue = $root.google.protobuf.ListValue.fromObject(object.listValue); + } + return message; + }; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Value + * @static + * @param {google.protobuf.Value} message Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.nullValue != null && message.hasOwnProperty("nullValue")) { + object.nullValue = options.enums === String ? $root.google.protobuf.NullValue[message.nullValue] === undefined ? message.nullValue : $root.google.protobuf.NullValue[message.nullValue] : message.nullValue; + if (options.oneofs) + object.kind = "nullValue"; + } + if (message.numberValue != null && message.hasOwnProperty("numberValue")) { + object.numberValue = options.json && !isFinite(message.numberValue) ? String(message.numberValue) : message.numberValue; + if (options.oneofs) + object.kind = "numberValue"; + } + if (message.stringValue != null && message.hasOwnProperty("stringValue")) { + object.stringValue = message.stringValue; + if (options.oneofs) + object.kind = "stringValue"; + } + if (message.boolValue != null && message.hasOwnProperty("boolValue")) { + object.boolValue = message.boolValue; + if (options.oneofs) + object.kind = "boolValue"; + } + if (message.structValue != null && message.hasOwnProperty("structValue")) { + object.structValue = $root.google.protobuf.Struct.toObject(message.structValue, options); + if (options.oneofs) + object.kind = "structValue"; + } + if (message.listValue != null && message.hasOwnProperty("listValue")) { + object.listValue = $root.google.protobuf.ListValue.toObject(message.listValue, options); + if (options.oneofs) + object.kind = "listValue"; + } + return object; + }; + + /** + * Converts this Value to JSON. + * @function toJSON + * @memberof google.protobuf.Value + * @instance + * @returns {Object.} JSON object + */ + Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Value + * @function getTypeUrl + * @memberof google.protobuf.Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Value"; + }; + + return Value; + })(); + + /** + * NullValue enum. + * @name google.protobuf.NullValue + * @enum {string} + * @property {string} NULL_VALUE=NULL_VALUE NULL_VALUE value + */ + protobuf.NullValue = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "NULL_VALUE"] = "NULL_VALUE"; + return values; + })(); + + protobuf.ListValue = (function() { + + /** + * Properties of a ListValue. + * @memberof google.protobuf + * @interface IListValue + * @property {Array.|null} [values] ListValue values + */ + + /** + * Constructs a new ListValue. + * @memberof google.protobuf + * @classdesc Represents a ListValue. + * @implements IListValue + * @constructor + * @param {google.protobuf.IListValue=} [properties] Properties to set + */ + function ListValue(properties) { + this.values = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListValue values. + * @member {Array.} values + * @memberof google.protobuf.ListValue + * @instance + */ + ListValue.prototype.values = $util.emptyArray; + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ListValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ListValue} ListValue + */ + ListValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ListValue) + return object; + var message = new $root.google.protobuf.ListValue(); + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".google.protobuf.ListValue.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".google.protobuf.ListValue.values: object expected"); + message.values[i] = $root.google.protobuf.Value.fromObject(object.values[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ListValue + * @static + * @param {google.protobuf.ListValue} message ListValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.values = []; + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.google.protobuf.Value.toObject(message.values[j], options); + } + return object; + }; + + /** + * Converts this ListValue to JSON. + * @function toJSON + * @memberof google.protobuf.ListValue + * @instance + * @returns {Object.} JSON object + */ + ListValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListValue + * @function getTypeUrl + * @memberof google.protobuf.ListValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ListValue"; + }; + + return ListValue; + })(); + + protobuf.FileDescriptorSet = (function() { + + /** + * Properties of a FileDescriptorSet. + * @memberof google.protobuf + * @interface IFileDescriptorSet + * @property {Array.|null} [file] FileDescriptorSet file + */ + + /** + * Constructs a new FileDescriptorSet. + * @memberof google.protobuf + * @classdesc Represents a FileDescriptorSet. + * @implements IFileDescriptorSet + * @constructor + * @param {google.protobuf.IFileDescriptorSet=} [properties] Properties to set + */ + function FileDescriptorSet(properties) { + this.file = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FileDescriptorSet file. + * @member {Array.} file + * @memberof google.protobuf.FileDescriptorSet + * @instance + */ + FileDescriptorSet.prototype.file = $util.emptyArray; + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FileDescriptorSet} FileDescriptorSet + */ + FileDescriptorSet.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FileDescriptorSet) + return object; + var message = new $root.google.protobuf.FileDescriptorSet(); + if (object.file) { + if (!Array.isArray(object.file)) + throw TypeError(".google.protobuf.FileDescriptorSet.file: array expected"); + message.file = []; + for (var i = 0; i < object.file.length; ++i) { + if (typeof object.file[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorSet.file: object expected"); + message.file[i] = $root.google.protobuf.FileDescriptorProto.fromObject(object.file[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {google.protobuf.FileDescriptorSet} message FileDescriptorSet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FileDescriptorSet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.file = []; + if (message.file && message.file.length) { + object.file = []; + for (var j = 0; j < message.file.length; ++j) + object.file[j] = $root.google.protobuf.FileDescriptorProto.toObject(message.file[j], options); + } + return object; + }; + + /** + * Converts this FileDescriptorSet to JSON. + * @function toJSON + * @memberof google.protobuf.FileDescriptorSet + * @instance + * @returns {Object.} JSON object + */ + FileDescriptorSet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FileDescriptorSet + * @function getTypeUrl + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FileDescriptorSet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FileDescriptorSet"; + }; + + return FileDescriptorSet; + })(); + + /** + * Edition enum. + * @name google.protobuf.Edition + * @enum {string} + * @property {string} EDITION_UNKNOWN=EDITION_UNKNOWN EDITION_UNKNOWN value + * @property {string} EDITION_PROTO2=EDITION_PROTO2 EDITION_PROTO2 value + * @property {string} EDITION_PROTO3=EDITION_PROTO3 EDITION_PROTO3 value + * @property {string} EDITION_2023=EDITION_2023 EDITION_2023 value + * @property {string} EDITION_2024=EDITION_2024 EDITION_2024 value + * @property {string} EDITION_1_TEST_ONLY=EDITION_1_TEST_ONLY EDITION_1_TEST_ONLY value + * @property {string} EDITION_2_TEST_ONLY=EDITION_2_TEST_ONLY EDITION_2_TEST_ONLY value + * @property {string} EDITION_99997_TEST_ONLY=EDITION_99997_TEST_ONLY EDITION_99997_TEST_ONLY value + * @property {string} EDITION_99998_TEST_ONLY=EDITION_99998_TEST_ONLY EDITION_99998_TEST_ONLY value + * @property {string} EDITION_99999_TEST_ONLY=EDITION_99999_TEST_ONLY EDITION_99999_TEST_ONLY value + * @property {string} EDITION_MAX=EDITION_MAX EDITION_MAX value + */ + protobuf.Edition = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "EDITION_UNKNOWN"] = "EDITION_UNKNOWN"; + values[valuesById[998] = "EDITION_PROTO2"] = "EDITION_PROTO2"; + values[valuesById[999] = "EDITION_PROTO3"] = "EDITION_PROTO3"; + values[valuesById[1000] = "EDITION_2023"] = "EDITION_2023"; + values[valuesById[1001] = "EDITION_2024"] = "EDITION_2024"; + values[valuesById[1] = "EDITION_1_TEST_ONLY"] = "EDITION_1_TEST_ONLY"; + values[valuesById[2] = "EDITION_2_TEST_ONLY"] = "EDITION_2_TEST_ONLY"; + values[valuesById[99997] = "EDITION_99997_TEST_ONLY"] = "EDITION_99997_TEST_ONLY"; + values[valuesById[99998] = "EDITION_99998_TEST_ONLY"] = "EDITION_99998_TEST_ONLY"; + values[valuesById[99999] = "EDITION_99999_TEST_ONLY"] = "EDITION_99999_TEST_ONLY"; + values[valuesById[2147483647] = "EDITION_MAX"] = "EDITION_MAX"; + return values; + })(); + + protobuf.FileDescriptorProto = (function() { + + /** + * Properties of a FileDescriptorProto. + * @memberof google.protobuf + * @interface IFileDescriptorProto + * @property {string|null} [name] FileDescriptorProto name + * @property {string|null} ["package"] FileDescriptorProto package + * @property {Array.|null} [dependency] FileDescriptorProto dependency + * @property {Array.|null} [publicDependency] FileDescriptorProto publicDependency + * @property {Array.|null} [weakDependency] FileDescriptorProto weakDependency + * @property {Array.|null} [messageType] FileDescriptorProto messageType + * @property {Array.|null} [enumType] FileDescriptorProto enumType + * @property {Array.|null} [service] FileDescriptorProto service + * @property {Array.|null} [extension] FileDescriptorProto extension + * @property {google.protobuf.IFileOptions|null} [options] FileDescriptorProto options + * @property {google.protobuf.ISourceCodeInfo|null} [sourceCodeInfo] FileDescriptorProto sourceCodeInfo + * @property {string|null} [syntax] FileDescriptorProto syntax + * @property {google.protobuf.Edition|null} [edition] FileDescriptorProto edition + */ + + /** + * Constructs a new FileDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a FileDescriptorProto. + * @implements IFileDescriptorProto + * @constructor + * @param {google.protobuf.IFileDescriptorProto=} [properties] Properties to set + */ + function FileDescriptorProto(properties) { + this.dependency = []; + this.publicDependency = []; + this.weakDependency = []; + this.messageType = []; + this.enumType = []; + this.service = []; + this.extension = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FileDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.name = ""; + + /** + * FileDescriptorProto package. + * @member {string} package + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype["package"] = ""; + + /** + * FileDescriptorProto dependency. + * @member {Array.} dependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.dependency = $util.emptyArray; + + /** + * FileDescriptorProto publicDependency. + * @member {Array.} publicDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.publicDependency = $util.emptyArray; + + /** + * FileDescriptorProto weakDependency. + * @member {Array.} weakDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.weakDependency = $util.emptyArray; + + /** + * FileDescriptorProto messageType. + * @member {Array.} messageType + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.messageType = $util.emptyArray; + + /** + * FileDescriptorProto enumType. + * @member {Array.} enumType + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.enumType = $util.emptyArray; + + /** + * FileDescriptorProto service. + * @member {Array.} service + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.service = $util.emptyArray; + + /** + * FileDescriptorProto extension. + * @member {Array.} extension + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.extension = $util.emptyArray; + + /** + * FileDescriptorProto options. + * @member {google.protobuf.IFileOptions|null|undefined} options + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.options = null; + + /** + * FileDescriptorProto sourceCodeInfo. + * @member {google.protobuf.ISourceCodeInfo|null|undefined} sourceCodeInfo + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.sourceCodeInfo = null; + + /** + * FileDescriptorProto syntax. + * @member {string} syntax + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.syntax = ""; + + /** + * FileDescriptorProto edition. + * @member {google.protobuf.Edition} edition + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.edition = 0; + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FileDescriptorProto} FileDescriptorProto + */ + FileDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FileDescriptorProto) + return object; + var message = new $root.google.protobuf.FileDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object["package"] != null) + message["package"] = String(object["package"]); + if (object.dependency) { + if (!Array.isArray(object.dependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.dependency: array expected"); + message.dependency = []; + for (var i = 0; i < object.dependency.length; ++i) + message.dependency[i] = String(object.dependency[i]); + } + if (object.publicDependency) { + if (!Array.isArray(object.publicDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.publicDependency: array expected"); + message.publicDependency = []; + for (var i = 0; i < object.publicDependency.length; ++i) + message.publicDependency[i] = object.publicDependency[i] | 0; + } + if (object.weakDependency) { + if (!Array.isArray(object.weakDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.weakDependency: array expected"); + message.weakDependency = []; + for (var i = 0; i < object.weakDependency.length; ++i) + message.weakDependency[i] = object.weakDependency[i] | 0; + } + if (object.messageType) { + if (!Array.isArray(object.messageType)) + throw TypeError(".google.protobuf.FileDescriptorProto.messageType: array expected"); + message.messageType = []; + for (var i = 0; i < object.messageType.length; ++i) { + if (typeof object.messageType[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.messageType: object expected"); + message.messageType[i] = $root.google.protobuf.DescriptorProto.fromObject(object.messageType[i]); + } + } + if (object.enumType) { + if (!Array.isArray(object.enumType)) + throw TypeError(".google.protobuf.FileDescriptorProto.enumType: array expected"); + message.enumType = []; + for (var i = 0; i < object.enumType.length; ++i) { + if (typeof object.enumType[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.enumType: object expected"); + message.enumType[i] = $root.google.protobuf.EnumDescriptorProto.fromObject(object.enumType[i]); + } + } + if (object.service) { + if (!Array.isArray(object.service)) + throw TypeError(".google.protobuf.FileDescriptorProto.service: array expected"); + message.service = []; + for (var i = 0; i < object.service.length; ++i) { + if (typeof object.service[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.service: object expected"); + message.service[i] = $root.google.protobuf.ServiceDescriptorProto.fromObject(object.service[i]); + } + } + if (object.extension) { + if (!Array.isArray(object.extension)) + throw TypeError(".google.protobuf.FileDescriptorProto.extension: array expected"); + message.extension = []; + for (var i = 0; i < object.extension.length; ++i) { + if (typeof object.extension[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.extension: object expected"); + message.extension[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.extension[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.FileOptions.fromObject(object.options); + } + if (object.sourceCodeInfo != null) { + if (typeof object.sourceCodeInfo !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.sourceCodeInfo: object expected"); + message.sourceCodeInfo = $root.google.protobuf.SourceCodeInfo.fromObject(object.sourceCodeInfo); + } + if (object.syntax != null) + message.syntax = String(object.syntax); + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.edition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.edition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.edition = 999; + break; + case "EDITION_2023": + case 1000: + message.edition = 1000; + break; + case "EDITION_2024": + case 1001: + message.edition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.edition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.edition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.edition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.edition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.edition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.edition = 2147483647; + break; + } + return message; + }; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {google.protobuf.FileDescriptorProto} message FileDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FileDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.dependency = []; + object.messageType = []; + object.enumType = []; + object.service = []; + object.extension = []; + object.publicDependency = []; + object.weakDependency = []; + } + if (options.defaults) { + object.name = ""; + object["package"] = ""; + object.options = null; + object.sourceCodeInfo = null; + object.syntax = ""; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message["package"] != null && message.hasOwnProperty("package")) + object["package"] = message["package"]; + if (message.dependency && message.dependency.length) { + object.dependency = []; + for (var j = 0; j < message.dependency.length; ++j) + object.dependency[j] = message.dependency[j]; + } + if (message.messageType && message.messageType.length) { + object.messageType = []; + for (var j = 0; j < message.messageType.length; ++j) + object.messageType[j] = $root.google.protobuf.DescriptorProto.toObject(message.messageType[j], options); + } + if (message.enumType && message.enumType.length) { + object.enumType = []; + for (var j = 0; j < message.enumType.length; ++j) + object.enumType[j] = $root.google.protobuf.EnumDescriptorProto.toObject(message.enumType[j], options); + } + if (message.service && message.service.length) { + object.service = []; + for (var j = 0; j < message.service.length; ++j) + object.service[j] = $root.google.protobuf.ServiceDescriptorProto.toObject(message.service[j], options); + } + if (message.extension && message.extension.length) { + object.extension = []; + for (var j = 0; j < message.extension.length; ++j) + object.extension[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.extension[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.FileOptions.toObject(message.options, options); + if (message.sourceCodeInfo != null && message.hasOwnProperty("sourceCodeInfo")) + object.sourceCodeInfo = $root.google.protobuf.SourceCodeInfo.toObject(message.sourceCodeInfo, options); + if (message.publicDependency && message.publicDependency.length) { + object.publicDependency = []; + for (var j = 0; j < message.publicDependency.length; ++j) + object.publicDependency[j] = message.publicDependency[j]; + } + if (message.weakDependency && message.weakDependency.length) { + object.weakDependency = []; + for (var j = 0; j < message.weakDependency.length; ++j) + object.weakDependency[j] = message.weakDependency[j]; + } + if (message.syntax != null && message.hasOwnProperty("syntax")) + object.syntax = message.syntax; + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; + return object; + }; + + /** + * Converts this FileDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.FileDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + FileDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FileDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FileDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FileDescriptorProto"; + }; + + return FileDescriptorProto; + })(); + + protobuf.DescriptorProto = (function() { + + /** + * Properties of a DescriptorProto. + * @memberof google.protobuf + * @interface IDescriptorProto + * @property {string|null} [name] DescriptorProto name + * @property {Array.|null} [field] DescriptorProto field + * @property {Array.|null} [extension] DescriptorProto extension + * @property {Array.|null} [nestedType] DescriptorProto nestedType + * @property {Array.|null} [enumType] DescriptorProto enumType + * @property {Array.|null} [extensionRange] DescriptorProto extensionRange + * @property {Array.|null} [oneofDecl] DescriptorProto oneofDecl + * @property {google.protobuf.IMessageOptions|null} [options] DescriptorProto options + * @property {Array.|null} [reservedRange] DescriptorProto reservedRange + * @property {Array.|null} [reservedName] DescriptorProto reservedName + */ + + /** + * Constructs a new DescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a DescriptorProto. + * @implements IDescriptorProto + * @constructor + * @param {google.protobuf.IDescriptorProto=} [properties] Properties to set + */ + function DescriptorProto(properties) { + this.field = []; + this.extension = []; + this.nestedType = []; + this.enumType = []; + this.extensionRange = []; + this.oneofDecl = []; + this.reservedRange = []; + this.reservedName = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DescriptorProto name. + * @member {string} name + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.name = ""; + + /** + * DescriptorProto field. + * @member {Array.} field + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.field = $util.emptyArray; + + /** + * DescriptorProto extension. + * @member {Array.} extension + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.extension = $util.emptyArray; + + /** + * DescriptorProto nestedType. + * @member {Array.} nestedType + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.nestedType = $util.emptyArray; + + /** + * DescriptorProto enumType. + * @member {Array.} enumType + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.enumType = $util.emptyArray; + + /** + * DescriptorProto extensionRange. + * @member {Array.} extensionRange + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.extensionRange = $util.emptyArray; + + /** + * DescriptorProto oneofDecl. + * @member {Array.} oneofDecl + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.oneofDecl = $util.emptyArray; + + /** + * DescriptorProto options. + * @member {google.protobuf.IMessageOptions|null|undefined} options + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.options = null; + + /** + * DescriptorProto reservedRange. + * @member {Array.} reservedRange + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.reservedRange = $util.emptyArray; + + /** + * DescriptorProto reservedName. + * @member {Array.} reservedName + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.reservedName = $util.emptyArray; + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DescriptorProto} DescriptorProto + */ + DescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DescriptorProto) + return object; + var message = new $root.google.protobuf.DescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.field) { + if (!Array.isArray(object.field)) + throw TypeError(".google.protobuf.DescriptorProto.field: array expected"); + message.field = []; + for (var i = 0; i < object.field.length; ++i) { + if (typeof object.field[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.field: object expected"); + message.field[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.field[i]); + } + } + if (object.extension) { + if (!Array.isArray(object.extension)) + throw TypeError(".google.protobuf.DescriptorProto.extension: array expected"); + message.extension = []; + for (var i = 0; i < object.extension.length; ++i) { + if (typeof object.extension[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.extension: object expected"); + message.extension[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.extension[i]); + } + } + if (object.nestedType) { + if (!Array.isArray(object.nestedType)) + throw TypeError(".google.protobuf.DescriptorProto.nestedType: array expected"); + message.nestedType = []; + for (var i = 0; i < object.nestedType.length; ++i) { + if (typeof object.nestedType[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.nestedType: object expected"); + message.nestedType[i] = $root.google.protobuf.DescriptorProto.fromObject(object.nestedType[i]); + } + } + if (object.enumType) { + if (!Array.isArray(object.enumType)) + throw TypeError(".google.protobuf.DescriptorProto.enumType: array expected"); + message.enumType = []; + for (var i = 0; i < object.enumType.length; ++i) { + if (typeof object.enumType[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.enumType: object expected"); + message.enumType[i] = $root.google.protobuf.EnumDescriptorProto.fromObject(object.enumType[i]); + } + } + if (object.extensionRange) { + if (!Array.isArray(object.extensionRange)) + throw TypeError(".google.protobuf.DescriptorProto.extensionRange: array expected"); + message.extensionRange = []; + for (var i = 0; i < object.extensionRange.length; ++i) { + if (typeof object.extensionRange[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.extensionRange: object expected"); + message.extensionRange[i] = $root.google.protobuf.DescriptorProto.ExtensionRange.fromObject(object.extensionRange[i]); + } + } + if (object.oneofDecl) { + if (!Array.isArray(object.oneofDecl)) + throw TypeError(".google.protobuf.DescriptorProto.oneofDecl: array expected"); + message.oneofDecl = []; + for (var i = 0; i < object.oneofDecl.length; ++i) { + if (typeof object.oneofDecl[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.oneofDecl: object expected"); + message.oneofDecl[i] = $root.google.protobuf.OneofDescriptorProto.fromObject(object.oneofDecl[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.DescriptorProto.options: object expected"); + message.options = $root.google.protobuf.MessageOptions.fromObject(object.options); + } + if (object.reservedRange) { + if (!Array.isArray(object.reservedRange)) + throw TypeError(".google.protobuf.DescriptorProto.reservedRange: array expected"); + message.reservedRange = []; + for (var i = 0; i < object.reservedRange.length; ++i) { + if (typeof object.reservedRange[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.reservedRange: object expected"); + message.reservedRange[i] = $root.google.protobuf.DescriptorProto.ReservedRange.fromObject(object.reservedRange[i]); + } + } + if (object.reservedName) { + if (!Array.isArray(object.reservedName)) + throw TypeError(".google.protobuf.DescriptorProto.reservedName: array expected"); + message.reservedName = []; + for (var i = 0; i < object.reservedName.length; ++i) + message.reservedName[i] = String(object.reservedName[i]); + } + return message; + }; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.DescriptorProto + * @static + * @param {google.protobuf.DescriptorProto} message DescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.field = []; + object.nestedType = []; + object.enumType = []; + object.extensionRange = []; + object.extension = []; + object.oneofDecl = []; + object.reservedRange = []; + object.reservedName = []; + } + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.field && message.field.length) { + object.field = []; + for (var j = 0; j < message.field.length; ++j) + object.field[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.field[j], options); + } + if (message.nestedType && message.nestedType.length) { + object.nestedType = []; + for (var j = 0; j < message.nestedType.length; ++j) + object.nestedType[j] = $root.google.protobuf.DescriptorProto.toObject(message.nestedType[j], options); + } + if (message.enumType && message.enumType.length) { + object.enumType = []; + for (var j = 0; j < message.enumType.length; ++j) + object.enumType[j] = $root.google.protobuf.EnumDescriptorProto.toObject(message.enumType[j], options); + } + if (message.extensionRange && message.extensionRange.length) { + object.extensionRange = []; + for (var j = 0; j < message.extensionRange.length; ++j) + object.extensionRange[j] = $root.google.protobuf.DescriptorProto.ExtensionRange.toObject(message.extensionRange[j], options); + } + if (message.extension && message.extension.length) { + object.extension = []; + for (var j = 0; j < message.extension.length; ++j) + object.extension[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.extension[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.MessageOptions.toObject(message.options, options); + if (message.oneofDecl && message.oneofDecl.length) { + object.oneofDecl = []; + for (var j = 0; j < message.oneofDecl.length; ++j) + object.oneofDecl[j] = $root.google.protobuf.OneofDescriptorProto.toObject(message.oneofDecl[j], options); + } + if (message.reservedRange && message.reservedRange.length) { + object.reservedRange = []; + for (var j = 0; j < message.reservedRange.length; ++j) + object.reservedRange[j] = $root.google.protobuf.DescriptorProto.ReservedRange.toObject(message.reservedRange[j], options); + } + if (message.reservedName && message.reservedName.length) { + object.reservedName = []; + for (var j = 0; j < message.reservedName.length; ++j) + object.reservedName[j] = message.reservedName[j]; + } + return object; + }; + + /** + * Converts this DescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.DescriptorProto + * @instance + * @returns {Object.} JSON object + */ + DescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.DescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.DescriptorProto"; + }; + + DescriptorProto.ExtensionRange = (function() { + + /** + * Properties of an ExtensionRange. + * @memberof google.protobuf.DescriptorProto + * @interface IExtensionRange + * @property {number|null} [start] ExtensionRange start + * @property {number|null} [end] ExtensionRange end + * @property {google.protobuf.IExtensionRangeOptions|null} [options] ExtensionRange options + */ + + /** + * Constructs a new ExtensionRange. + * @memberof google.protobuf.DescriptorProto + * @classdesc Represents an ExtensionRange. + * @implements IExtensionRange + * @constructor + * @param {google.protobuf.DescriptorProto.IExtensionRange=} [properties] Properties to set + */ + function ExtensionRange(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExtensionRange start. + * @member {number} start + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @instance + */ + ExtensionRange.prototype.start = 0; + + /** + * ExtensionRange end. + * @member {number} end + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @instance + */ + ExtensionRange.prototype.end = 0; + + /** + * ExtensionRange options. + * @member {google.protobuf.IExtensionRangeOptions|null|undefined} options + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @instance + */ + ExtensionRange.prototype.options = null; + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DescriptorProto.ExtensionRange} ExtensionRange + */ + ExtensionRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DescriptorProto.ExtensionRange) + return object; + var message = new $root.google.protobuf.DescriptorProto.ExtensionRange(); + if (object.start != null) + message.start = object.start | 0; + if (object.end != null) + message.end = object.end | 0; + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.DescriptorProto.ExtensionRange.options: object expected"); + message.options = $root.google.protobuf.ExtensionRangeOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {google.protobuf.DescriptorProto.ExtensionRange} message ExtensionRange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExtensionRange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.start = 0; + object.end = 0; + object.options = null; + } + if (message.start != null && message.hasOwnProperty("start")) + object.start = message.start; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.ExtensionRangeOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this ExtensionRange to JSON. + * @function toJSON + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @instance + * @returns {Object.} JSON object + */ + ExtensionRange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExtensionRange + * @function getTypeUrl + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExtensionRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.DescriptorProto.ExtensionRange"; + }; + + return ExtensionRange; + })(); + + DescriptorProto.ReservedRange = (function() { + + /** + * Properties of a ReservedRange. + * @memberof google.protobuf.DescriptorProto + * @interface IReservedRange + * @property {number|null} [start] ReservedRange start + * @property {number|null} [end] ReservedRange end + */ + + /** + * Constructs a new ReservedRange. + * @memberof google.protobuf.DescriptorProto + * @classdesc Represents a ReservedRange. + * @implements IReservedRange + * @constructor + * @param {google.protobuf.DescriptorProto.IReservedRange=} [properties] Properties to set + */ + function ReservedRange(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReservedRange start. + * @member {number} start + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @instance + */ + ReservedRange.prototype.start = 0; + + /** + * ReservedRange end. + * @member {number} end + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @instance + */ + ReservedRange.prototype.end = 0; + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DescriptorProto.ReservedRange} ReservedRange + */ + ReservedRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DescriptorProto.ReservedRange) + return object; + var message = new $root.google.protobuf.DescriptorProto.ReservedRange(); + if (object.start != null) + message.start = object.start | 0; + if (object.end != null) + message.end = object.end | 0; + return message; + }; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {google.protobuf.DescriptorProto.ReservedRange} message ReservedRange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReservedRange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.start = 0; + object.end = 0; + } + if (message.start != null && message.hasOwnProperty("start")) + object.start = message.start; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + return object; + }; + + /** + * Converts this ReservedRange to JSON. + * @function toJSON + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @instance + * @returns {Object.} JSON object + */ + ReservedRange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReservedRange + * @function getTypeUrl + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReservedRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.DescriptorProto.ReservedRange"; + }; + + return ReservedRange; + })(); + + return DescriptorProto; + })(); + + protobuf.ExtensionRangeOptions = (function() { + + /** + * Properties of an ExtensionRangeOptions. + * @memberof google.protobuf + * @interface IExtensionRangeOptions + * @property {Array.|null} [uninterpretedOption] ExtensionRangeOptions uninterpretedOption + * @property {Array.|null} [declaration] ExtensionRangeOptions declaration + * @property {google.protobuf.IFeatureSet|null} [features] ExtensionRangeOptions features + * @property {google.protobuf.ExtensionRangeOptions.VerificationState|null} [verification] ExtensionRangeOptions verification + */ + + /** + * Constructs a new ExtensionRangeOptions. + * @memberof google.protobuf + * @classdesc Represents an ExtensionRangeOptions. + * @implements IExtensionRangeOptions + * @constructor + * @param {google.protobuf.IExtensionRangeOptions=} [properties] Properties to set + */ + function ExtensionRangeOptions(properties) { + this.uninterpretedOption = []; + this.declaration = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExtensionRangeOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * ExtensionRangeOptions declaration. + * @member {Array.} declaration + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.declaration = $util.emptyArray; + + /** + * ExtensionRangeOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.features = null; + + /** + * ExtensionRangeOptions verification. + * @member {google.protobuf.ExtensionRangeOptions.VerificationState} verification + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.verification = 1; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ExtensionRangeOptions} ExtensionRangeOptions + */ + ExtensionRangeOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ExtensionRangeOptions) + return object; + var message = new $root.google.protobuf.ExtensionRangeOptions(); + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.ExtensionRangeOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.ExtensionRangeOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object.declaration) { + if (!Array.isArray(object.declaration)) + throw TypeError(".google.protobuf.ExtensionRangeOptions.declaration: array expected"); + message.declaration = []; + for (var i = 0; i < object.declaration.length; ++i) { + if (typeof object.declaration[i] !== "object") + throw TypeError(".google.protobuf.ExtensionRangeOptions.declaration: object expected"); + message.declaration[i] = $root.google.protobuf.ExtensionRangeOptions.Declaration.fromObject(object.declaration[i]); + } + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.ExtensionRangeOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + switch (object.verification) { + case "DECLARATION": + case 0: + message.verification = 0; + break; + default: + if (typeof object.verification === "number") { + message.verification = object.verification; + break; + } + break; + case "UNVERIFIED": + case 1: + message.verification = 1; + break; + } + return message; + }; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {google.protobuf.ExtensionRangeOptions} message ExtensionRangeOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExtensionRangeOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.declaration = []; + object.uninterpretedOption = []; + } + if (options.defaults) { + object.verification = options.enums === String ? "UNVERIFIED" : 1; + object.features = null; + } + if (message.declaration && message.declaration.length) { + object.declaration = []; + for (var j = 0; j < message.declaration.length; ++j) + object.declaration[j] = $root.google.protobuf.ExtensionRangeOptions.Declaration.toObject(message.declaration[j], options); + } + if (message.verification != null && message.hasOwnProperty("verification")) + object.verification = options.enums === String ? $root.google.protobuf.ExtensionRangeOptions.VerificationState[message.verification] === undefined ? message.verification : $root.google.protobuf.ExtensionRangeOptions.VerificationState[message.verification] : message.verification; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @function toJSON + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + * @returns {Object.} JSON object + */ + ExtensionRangeOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @function getTypeUrl + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExtensionRangeOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ExtensionRangeOptions"; + }; + + ExtensionRangeOptions.Declaration = (function() { + + /** + * Properties of a Declaration. + * @memberof google.protobuf.ExtensionRangeOptions + * @interface IDeclaration + * @property {number|null} [number] Declaration number + * @property {string|null} [fullName] Declaration fullName + * @property {string|null} [type] Declaration type + * @property {boolean|null} [reserved] Declaration reserved + * @property {boolean|null} [repeated] Declaration repeated + */ + + /** + * Constructs a new Declaration. + * @memberof google.protobuf.ExtensionRangeOptions + * @classdesc Represents a Declaration. + * @implements IDeclaration + * @constructor + * @param {google.protobuf.ExtensionRangeOptions.IDeclaration=} [properties] Properties to set + */ + function Declaration(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Declaration number. + * @member {number} number + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.number = 0; + + /** + * Declaration fullName. + * @member {string} fullName + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.fullName = ""; + + /** + * Declaration type. + * @member {string} type + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.type = ""; + + /** + * Declaration reserved. + * @member {boolean} reserved + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.reserved = false; + + /** + * Declaration repeated. + * @member {boolean} repeated + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.repeated = false; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ExtensionRangeOptions.Declaration} Declaration + */ + Declaration.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ExtensionRangeOptions.Declaration) + return object; + var message = new $root.google.protobuf.ExtensionRangeOptions.Declaration(); + if (object.number != null) + message.number = object.number | 0; + if (object.fullName != null) + message.fullName = String(object.fullName); + if (object.type != null) + message.type = String(object.type); + if (object.reserved != null) + message.reserved = Boolean(object.reserved); + if (object.repeated != null) + message.repeated = Boolean(object.repeated); + return message; + }; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {google.protobuf.ExtensionRangeOptions.Declaration} message Declaration + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Declaration.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.number = 0; + object.fullName = ""; + object.type = ""; + object.reserved = false; + object.repeated = false; + } + if (message.number != null && message.hasOwnProperty("number")) + object.number = message.number; + if (message.fullName != null && message.hasOwnProperty("fullName")) + object.fullName = message.fullName; + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.reserved != null && message.hasOwnProperty("reserved")) + object.reserved = message.reserved; + if (message.repeated != null && message.hasOwnProperty("repeated")) + object.repeated = message.repeated; + return object; + }; + + /** + * Converts this Declaration to JSON. + * @function toJSON + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + * @returns {Object.} JSON object + */ + Declaration.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Declaration + * @function getTypeUrl + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Declaration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ExtensionRangeOptions.Declaration"; + }; + + return Declaration; + })(); + + /** + * VerificationState enum. + * @name google.protobuf.ExtensionRangeOptions.VerificationState + * @enum {string} + * @property {string} DECLARATION=DECLARATION DECLARATION value + * @property {string} UNVERIFIED=UNVERIFIED UNVERIFIED value + */ + ExtensionRangeOptions.VerificationState = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DECLARATION"] = "DECLARATION"; + values[valuesById[1] = "UNVERIFIED"] = "UNVERIFIED"; + return values; + })(); + + return ExtensionRangeOptions; + })(); + + protobuf.FieldDescriptorProto = (function() { + + /** + * Properties of a FieldDescriptorProto. + * @memberof google.protobuf + * @interface IFieldDescriptorProto + * @property {string|null} [name] FieldDescriptorProto name + * @property {number|null} [number] FieldDescriptorProto number + * @property {google.protobuf.FieldDescriptorProto.Label|null} [label] FieldDescriptorProto label + * @property {google.protobuf.FieldDescriptorProto.Type|null} [type] FieldDescriptorProto type + * @property {string|null} [typeName] FieldDescriptorProto typeName + * @property {string|null} [extendee] FieldDescriptorProto extendee + * @property {string|null} [defaultValue] FieldDescriptorProto defaultValue + * @property {number|null} [oneofIndex] FieldDescriptorProto oneofIndex + * @property {string|null} [jsonName] FieldDescriptorProto jsonName + * @property {google.protobuf.IFieldOptions|null} [options] FieldDescriptorProto options + * @property {boolean|null} [proto3Optional] FieldDescriptorProto proto3Optional + */ + + /** + * Constructs a new FieldDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a FieldDescriptorProto. + * @implements IFieldDescriptorProto + * @constructor + * @param {google.protobuf.IFieldDescriptorProto=} [properties] Properties to set + */ + function FieldDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.name = ""; + + /** + * FieldDescriptorProto number. + * @member {number} number + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.number = 0; + + /** + * FieldDescriptorProto label. + * @member {google.protobuf.FieldDescriptorProto.Label} label + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.label = 1; + + /** + * FieldDescriptorProto type. + * @member {google.protobuf.FieldDescriptorProto.Type} type + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.type = 1; + + /** + * FieldDescriptorProto typeName. + * @member {string} typeName + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.typeName = ""; + + /** + * FieldDescriptorProto extendee. + * @member {string} extendee + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.extendee = ""; + + /** + * FieldDescriptorProto defaultValue. + * @member {string} defaultValue + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.defaultValue = ""; + + /** + * FieldDescriptorProto oneofIndex. + * @member {number} oneofIndex + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.oneofIndex = 0; + + /** + * FieldDescriptorProto jsonName. + * @member {string} jsonName + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.jsonName = ""; + + /** + * FieldDescriptorProto options. + * @member {google.protobuf.IFieldOptions|null|undefined} options + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.options = null; + + /** + * FieldDescriptorProto proto3Optional. + * @member {boolean} proto3Optional + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.proto3Optional = false; + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldDescriptorProto} FieldDescriptorProto + */ + FieldDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldDescriptorProto) + return object; + var message = new $root.google.protobuf.FieldDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.number != null) + message.number = object.number | 0; + switch (object.label) { + default: + if (typeof object.label === "number") { + message.label = object.label; + break; + } + break; + case "LABEL_OPTIONAL": + case 1: + message.label = 1; + break; + case "LABEL_REPEATED": + case 3: + message.label = 3; + break; + case "LABEL_REQUIRED": + case 2: + message.label = 2; + break; + } + switch (object.type) { + default: + if (typeof object.type === "number") { + message.type = object.type; + break; + } + break; + case "TYPE_DOUBLE": + case 1: + message.type = 1; + break; + case "TYPE_FLOAT": + case 2: + message.type = 2; + break; + case "TYPE_INT64": + case 3: + message.type = 3; + break; + case "TYPE_UINT64": + case 4: + message.type = 4; + break; + case "TYPE_INT32": + case 5: + message.type = 5; + break; + case "TYPE_FIXED64": + case 6: + message.type = 6; + break; + case "TYPE_FIXED32": + case 7: + message.type = 7; + break; + case "TYPE_BOOL": + case 8: + message.type = 8; + break; + case "TYPE_STRING": + case 9: + message.type = 9; + break; + case "TYPE_GROUP": + case 10: + message.type = 10; + break; + case "TYPE_MESSAGE": + case 11: + message.type = 11; + break; + case "TYPE_BYTES": + case 12: + message.type = 12; + break; + case "TYPE_UINT32": + case 13: + message.type = 13; + break; + case "TYPE_ENUM": + case 14: + message.type = 14; + break; + case "TYPE_SFIXED32": + case 15: + message.type = 15; + break; + case "TYPE_SFIXED64": + case 16: + message.type = 16; + break; + case "TYPE_SINT32": + case 17: + message.type = 17; + break; + case "TYPE_SINT64": + case 18: + message.type = 18; + break; + } + if (object.typeName != null) + message.typeName = String(object.typeName); + if (object.extendee != null) + message.extendee = String(object.extendee); + if (object.defaultValue != null) + message.defaultValue = String(object.defaultValue); + if (object.oneofIndex != null) + message.oneofIndex = object.oneofIndex | 0; + if (object.jsonName != null) + message.jsonName = String(object.jsonName); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.FieldDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.FieldOptions.fromObject(object.options); + } + if (object.proto3Optional != null) + message.proto3Optional = Boolean(object.proto3Optional); + return message; + }; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {google.protobuf.FieldDescriptorProto} message FieldDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.extendee = ""; + object.number = 0; + object.label = options.enums === String ? "LABEL_OPTIONAL" : 1; + object.type = options.enums === String ? "TYPE_DOUBLE" : 1; + object.typeName = ""; + object.defaultValue = ""; + object.options = null; + object.oneofIndex = 0; + object.jsonName = ""; + object.proto3Optional = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.extendee != null && message.hasOwnProperty("extendee")) + object.extendee = message.extendee; + if (message.number != null && message.hasOwnProperty("number")) + object.number = message.number; + if (message.label != null && message.hasOwnProperty("label")) + object.label = options.enums === String ? $root.google.protobuf.FieldDescriptorProto.Label[message.label] === undefined ? message.label : $root.google.protobuf.FieldDescriptorProto.Label[message.label] : message.label; + if (message.type != null && message.hasOwnProperty("type")) + object.type = options.enums === String ? $root.google.protobuf.FieldDescriptorProto.Type[message.type] === undefined ? message.type : $root.google.protobuf.FieldDescriptorProto.Type[message.type] : message.type; + if (message.typeName != null && message.hasOwnProperty("typeName")) + object.typeName = message.typeName; + if (message.defaultValue != null && message.hasOwnProperty("defaultValue")) + object.defaultValue = message.defaultValue; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.FieldOptions.toObject(message.options, options); + if (message.oneofIndex != null && message.hasOwnProperty("oneofIndex")) + object.oneofIndex = message.oneofIndex; + if (message.jsonName != null && message.hasOwnProperty("jsonName")) + object.jsonName = message.jsonName; + if (message.proto3Optional != null && message.hasOwnProperty("proto3Optional")) + object.proto3Optional = message.proto3Optional; + return object; + }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.FieldDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + FieldDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldDescriptorProto"; + }; + + /** + * Type enum. + * @name google.protobuf.FieldDescriptorProto.Type + * @enum {string} + * @property {string} TYPE_DOUBLE=TYPE_DOUBLE TYPE_DOUBLE value + * @property {string} TYPE_FLOAT=TYPE_FLOAT TYPE_FLOAT value + * @property {string} TYPE_INT64=TYPE_INT64 TYPE_INT64 value + * @property {string} TYPE_UINT64=TYPE_UINT64 TYPE_UINT64 value + * @property {string} TYPE_INT32=TYPE_INT32 TYPE_INT32 value + * @property {string} TYPE_FIXED64=TYPE_FIXED64 TYPE_FIXED64 value + * @property {string} TYPE_FIXED32=TYPE_FIXED32 TYPE_FIXED32 value + * @property {string} TYPE_BOOL=TYPE_BOOL TYPE_BOOL value + * @property {string} TYPE_STRING=TYPE_STRING TYPE_STRING value + * @property {string} TYPE_GROUP=TYPE_GROUP TYPE_GROUP value + * @property {string} TYPE_MESSAGE=TYPE_MESSAGE TYPE_MESSAGE value + * @property {string} TYPE_BYTES=TYPE_BYTES TYPE_BYTES value + * @property {string} TYPE_UINT32=TYPE_UINT32 TYPE_UINT32 value + * @property {string} TYPE_ENUM=TYPE_ENUM TYPE_ENUM value + * @property {string} TYPE_SFIXED32=TYPE_SFIXED32 TYPE_SFIXED32 value + * @property {string} TYPE_SFIXED64=TYPE_SFIXED64 TYPE_SFIXED64 value + * @property {string} TYPE_SINT32=TYPE_SINT32 TYPE_SINT32 value + * @property {string} TYPE_SINT64=TYPE_SINT64 TYPE_SINT64 value + */ + FieldDescriptorProto.Type = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[1] = "TYPE_DOUBLE"] = "TYPE_DOUBLE"; + values[valuesById[2] = "TYPE_FLOAT"] = "TYPE_FLOAT"; + values[valuesById[3] = "TYPE_INT64"] = "TYPE_INT64"; + values[valuesById[4] = "TYPE_UINT64"] = "TYPE_UINT64"; + values[valuesById[5] = "TYPE_INT32"] = "TYPE_INT32"; + values[valuesById[6] = "TYPE_FIXED64"] = "TYPE_FIXED64"; + values[valuesById[7] = "TYPE_FIXED32"] = "TYPE_FIXED32"; + values[valuesById[8] = "TYPE_BOOL"] = "TYPE_BOOL"; + values[valuesById[9] = "TYPE_STRING"] = "TYPE_STRING"; + values[valuesById[10] = "TYPE_GROUP"] = "TYPE_GROUP"; + values[valuesById[11] = "TYPE_MESSAGE"] = "TYPE_MESSAGE"; + values[valuesById[12] = "TYPE_BYTES"] = "TYPE_BYTES"; + values[valuesById[13] = "TYPE_UINT32"] = "TYPE_UINT32"; + values[valuesById[14] = "TYPE_ENUM"] = "TYPE_ENUM"; + values[valuesById[15] = "TYPE_SFIXED32"] = "TYPE_SFIXED32"; + values[valuesById[16] = "TYPE_SFIXED64"] = "TYPE_SFIXED64"; + values[valuesById[17] = "TYPE_SINT32"] = "TYPE_SINT32"; + values[valuesById[18] = "TYPE_SINT64"] = "TYPE_SINT64"; + return values; + })(); + + /** + * Label enum. + * @name google.protobuf.FieldDescriptorProto.Label + * @enum {string} + * @property {string} LABEL_OPTIONAL=LABEL_OPTIONAL LABEL_OPTIONAL value + * @property {string} LABEL_REPEATED=LABEL_REPEATED LABEL_REPEATED value + * @property {string} LABEL_REQUIRED=LABEL_REQUIRED LABEL_REQUIRED value + */ + FieldDescriptorProto.Label = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[1] = "LABEL_OPTIONAL"] = "LABEL_OPTIONAL"; + values[valuesById[3] = "LABEL_REPEATED"] = "LABEL_REPEATED"; + values[valuesById[2] = "LABEL_REQUIRED"] = "LABEL_REQUIRED"; + return values; + })(); + + return FieldDescriptorProto; + })(); + + protobuf.OneofDescriptorProto = (function() { + + /** + * Properties of an OneofDescriptorProto. + * @memberof google.protobuf + * @interface IOneofDescriptorProto + * @property {string|null} [name] OneofDescriptorProto name + * @property {google.protobuf.IOneofOptions|null} [options] OneofDescriptorProto options + */ + + /** + * Constructs a new OneofDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents an OneofDescriptorProto. + * @implements IOneofDescriptorProto + * @constructor + * @param {google.protobuf.IOneofDescriptorProto=} [properties] Properties to set + */ + function OneofDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OneofDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.OneofDescriptorProto + * @instance + */ + OneofDescriptorProto.prototype.name = ""; + + /** + * OneofDescriptorProto options. + * @member {google.protobuf.IOneofOptions|null|undefined} options + * @memberof google.protobuf.OneofDescriptorProto + * @instance + */ + OneofDescriptorProto.prototype.options = null; + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.OneofDescriptorProto} OneofDescriptorProto + */ + OneofDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.OneofDescriptorProto) + return object; + var message = new $root.google.protobuf.OneofDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.OneofDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.OneofOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {google.protobuf.OneofDescriptorProto} message OneofDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OneofDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.OneofOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.OneofDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + OneofDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OneofDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OneofDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.OneofDescriptorProto"; + }; + + return OneofDescriptorProto; + })(); + + protobuf.EnumDescriptorProto = (function() { + + /** + * Properties of an EnumDescriptorProto. + * @memberof google.protobuf + * @interface IEnumDescriptorProto + * @property {string|null} [name] EnumDescriptorProto name + * @property {Array.|null} [value] EnumDescriptorProto value + * @property {google.protobuf.IEnumOptions|null} [options] EnumDescriptorProto options + * @property {Array.|null} [reservedRange] EnumDescriptorProto reservedRange + * @property {Array.|null} [reservedName] EnumDescriptorProto reservedName + */ + + /** + * Constructs a new EnumDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents an EnumDescriptorProto. + * @implements IEnumDescriptorProto + * @constructor + * @param {google.protobuf.IEnumDescriptorProto=} [properties] Properties to set + */ + function EnumDescriptorProto(properties) { + this.value = []; + this.reservedRange = []; + this.reservedName = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.name = ""; + + /** + * EnumDescriptorProto value. + * @member {Array.} value + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.value = $util.emptyArray; + + /** + * EnumDescriptorProto options. + * @member {google.protobuf.IEnumOptions|null|undefined} options + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.options = null; + + /** + * EnumDescriptorProto reservedRange. + * @member {Array.} reservedRange + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.reservedRange = $util.emptyArray; + + /** + * EnumDescriptorProto reservedName. + * @member {Array.} reservedName + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.reservedName = $util.emptyArray; + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumDescriptorProto} EnumDescriptorProto + */ + EnumDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumDescriptorProto) + return object; + var message = new $root.google.protobuf.EnumDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.value) { + if (!Array.isArray(object.value)) + throw TypeError(".google.protobuf.EnumDescriptorProto.value: array expected"); + message.value = []; + for (var i = 0; i < object.value.length; ++i) { + if (typeof object.value[i] !== "object") + throw TypeError(".google.protobuf.EnumDescriptorProto.value: object expected"); + message.value[i] = $root.google.protobuf.EnumValueDescriptorProto.fromObject(object.value[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.EnumDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.EnumOptions.fromObject(object.options); + } + if (object.reservedRange) { + if (!Array.isArray(object.reservedRange)) + throw TypeError(".google.protobuf.EnumDescriptorProto.reservedRange: array expected"); + message.reservedRange = []; + for (var i = 0; i < object.reservedRange.length; ++i) { + if (typeof object.reservedRange[i] !== "object") + throw TypeError(".google.protobuf.EnumDescriptorProto.reservedRange: object expected"); + message.reservedRange[i] = $root.google.protobuf.EnumDescriptorProto.EnumReservedRange.fromObject(object.reservedRange[i]); + } + } + if (object.reservedName) { + if (!Array.isArray(object.reservedName)) + throw TypeError(".google.protobuf.EnumDescriptorProto.reservedName: array expected"); + message.reservedName = []; + for (var i = 0; i < object.reservedName.length; ++i) + message.reservedName[i] = String(object.reservedName[i]); + } + return message; + }; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {google.protobuf.EnumDescriptorProto} message EnumDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.value = []; + object.reservedRange = []; + object.reservedName = []; + } + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.value && message.value.length) { + object.value = []; + for (var j = 0; j < message.value.length; ++j) + object.value[j] = $root.google.protobuf.EnumValueDescriptorProto.toObject(message.value[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.EnumOptions.toObject(message.options, options); + if (message.reservedRange && message.reservedRange.length) { + object.reservedRange = []; + for (var j = 0; j < message.reservedRange.length; ++j) + object.reservedRange[j] = $root.google.protobuf.EnumDescriptorProto.EnumReservedRange.toObject(message.reservedRange[j], options); + } + if (message.reservedName && message.reservedName.length) { + object.reservedName = []; + for (var j = 0; j < message.reservedName.length; ++j) + object.reservedName[j] = message.reservedName[j]; + } + return object; + }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.EnumDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + EnumDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumDescriptorProto"; + }; + + EnumDescriptorProto.EnumReservedRange = (function() { + + /** + * Properties of an EnumReservedRange. + * @memberof google.protobuf.EnumDescriptorProto + * @interface IEnumReservedRange + * @property {number|null} [start] EnumReservedRange start + * @property {number|null} [end] EnumReservedRange end + */ + + /** + * Constructs a new EnumReservedRange. + * @memberof google.protobuf.EnumDescriptorProto + * @classdesc Represents an EnumReservedRange. + * @implements IEnumReservedRange + * @constructor + * @param {google.protobuf.EnumDescriptorProto.IEnumReservedRange=} [properties] Properties to set + */ + function EnumReservedRange(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumReservedRange start. + * @member {number} start + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @instance + */ + EnumReservedRange.prototype.start = 0; + + /** + * EnumReservedRange end. + * @member {number} end + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @instance + */ + EnumReservedRange.prototype.end = 0; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumDescriptorProto.EnumReservedRange} EnumReservedRange + */ + EnumReservedRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumDescriptorProto.EnumReservedRange) + return object; + var message = new $root.google.protobuf.EnumDescriptorProto.EnumReservedRange(); + if (object.start != null) + message.start = object.start | 0; + if (object.end != null) + message.end = object.end | 0; + return message; + }; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {google.protobuf.EnumDescriptorProto.EnumReservedRange} message EnumReservedRange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumReservedRange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.start = 0; + object.end = 0; + } + if (message.start != null && message.hasOwnProperty("start")) + object.start = message.start; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + return object; + }; + + /** + * Converts this EnumReservedRange to JSON. + * @function toJSON + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @instance + * @returns {Object.} JSON object + */ + EnumReservedRange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumReservedRange + * @function getTypeUrl + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumReservedRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumDescriptorProto.EnumReservedRange"; + }; + + return EnumReservedRange; + })(); + + return EnumDescriptorProto; + })(); + + protobuf.EnumValueDescriptorProto = (function() { + + /** + * Properties of an EnumValueDescriptorProto. + * @memberof google.protobuf + * @interface IEnumValueDescriptorProto + * @property {string|null} [name] EnumValueDescriptorProto name + * @property {number|null} [number] EnumValueDescriptorProto number + * @property {google.protobuf.IEnumValueOptions|null} [options] EnumValueDescriptorProto options + */ + + /** + * Constructs a new EnumValueDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents an EnumValueDescriptorProto. + * @implements IEnumValueDescriptorProto + * @constructor + * @param {google.protobuf.IEnumValueDescriptorProto=} [properties] Properties to set + */ + function EnumValueDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumValueDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + */ + EnumValueDescriptorProto.prototype.name = ""; + + /** + * EnumValueDescriptorProto number. + * @member {number} number + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + */ + EnumValueDescriptorProto.prototype.number = 0; + + /** + * EnumValueDescriptorProto options. + * @member {google.protobuf.IEnumValueOptions|null|undefined} options + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + */ + EnumValueDescriptorProto.prototype.options = null; + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumValueDescriptorProto} EnumValueDescriptorProto + */ + EnumValueDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumValueDescriptorProto) + return object; + var message = new $root.google.protobuf.EnumValueDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.number != null) + message.number = object.number | 0; + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.EnumValueDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.EnumValueOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {google.protobuf.EnumValueDescriptorProto} message EnumValueDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumValueDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.number = 0; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.number != null && message.hasOwnProperty("number")) + object.number = message.number; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.EnumValueOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + EnumValueDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumValueDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumValueDescriptorProto"; + }; + + return EnumValueDescriptorProto; + })(); + + protobuf.ServiceDescriptorProto = (function() { + + /** + * Properties of a ServiceDescriptorProto. + * @memberof google.protobuf + * @interface IServiceDescriptorProto + * @property {string|null} [name] ServiceDescriptorProto name + * @property {Array.|null} [method] ServiceDescriptorProto method + * @property {google.protobuf.IServiceOptions|null} [options] ServiceDescriptorProto options + */ + + /** + * Constructs a new ServiceDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a ServiceDescriptorProto. + * @implements IServiceDescriptorProto + * @constructor + * @param {google.protobuf.IServiceDescriptorProto=} [properties] Properties to set + */ + function ServiceDescriptorProto(properties) { + this.method = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ServiceDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + */ + ServiceDescriptorProto.prototype.name = ""; + + /** + * ServiceDescriptorProto method. + * @member {Array.} method + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + */ + ServiceDescriptorProto.prototype.method = $util.emptyArray; + + /** + * ServiceDescriptorProto options. + * @member {google.protobuf.IServiceOptions|null|undefined} options + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + */ + ServiceDescriptorProto.prototype.options = null; + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ServiceDescriptorProto} ServiceDescriptorProto + */ + ServiceDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ServiceDescriptorProto) + return object; + var message = new $root.google.protobuf.ServiceDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.method) { + if (!Array.isArray(object.method)) + throw TypeError(".google.protobuf.ServiceDescriptorProto.method: array expected"); + message.method = []; + for (var i = 0; i < object.method.length; ++i) { + if (typeof object.method[i] !== "object") + throw TypeError(".google.protobuf.ServiceDescriptorProto.method: object expected"); + message.method[i] = $root.google.protobuf.MethodDescriptorProto.fromObject(object.method[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.ServiceDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.ServiceOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {google.protobuf.ServiceDescriptorProto} message ServiceDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ServiceDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.method = []; + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.method && message.method.length) { + object.method = []; + for (var j = 0; j < message.method.length; ++j) + object.method[j] = $root.google.protobuf.MethodDescriptorProto.toObject(message.method[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.ServiceOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + ServiceDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ServiceDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ServiceDescriptorProto"; + }; + + return ServiceDescriptorProto; + })(); + + protobuf.MethodDescriptorProto = (function() { + + /** + * Properties of a MethodDescriptorProto. + * @memberof google.protobuf + * @interface IMethodDescriptorProto + * @property {string|null} [name] MethodDescriptorProto name + * @property {string|null} [inputType] MethodDescriptorProto inputType + * @property {string|null} [outputType] MethodDescriptorProto outputType + * @property {google.protobuf.IMethodOptions|null} [options] MethodDescriptorProto options + * @property {boolean|null} [clientStreaming] MethodDescriptorProto clientStreaming + * @property {boolean|null} [serverStreaming] MethodDescriptorProto serverStreaming + */ + + /** + * Constructs a new MethodDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a MethodDescriptorProto. + * @implements IMethodDescriptorProto + * @constructor + * @param {google.protobuf.IMethodDescriptorProto=} [properties] Properties to set + */ + function MethodDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MethodDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.name = ""; + + /** + * MethodDescriptorProto inputType. + * @member {string} inputType + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.inputType = ""; + + /** + * MethodDescriptorProto outputType. + * @member {string} outputType + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.outputType = ""; + + /** + * MethodDescriptorProto options. + * @member {google.protobuf.IMethodOptions|null|undefined} options + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.options = null; + + /** + * MethodDescriptorProto clientStreaming. + * @member {boolean} clientStreaming + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.clientStreaming = false; + + /** + * MethodDescriptorProto serverStreaming. + * @member {boolean} serverStreaming + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.serverStreaming = false; + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.MethodDescriptorProto} MethodDescriptorProto + */ + MethodDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.MethodDescriptorProto) + return object; + var message = new $root.google.protobuf.MethodDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.inputType != null) + message.inputType = String(object.inputType); + if (object.outputType != null) + message.outputType = String(object.outputType); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.MethodDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.MethodOptions.fromObject(object.options); + } + if (object.clientStreaming != null) + message.clientStreaming = Boolean(object.clientStreaming); + if (object.serverStreaming != null) + message.serverStreaming = Boolean(object.serverStreaming); + return message; + }; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {google.protobuf.MethodDescriptorProto} message MethodDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MethodDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.inputType = ""; + object.outputType = ""; + object.options = null; + object.clientStreaming = false; + object.serverStreaming = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.inputType != null && message.hasOwnProperty("inputType")) + object.inputType = message.inputType; + if (message.outputType != null && message.hasOwnProperty("outputType")) + object.outputType = message.outputType; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.MethodOptions.toObject(message.options, options); + if (message.clientStreaming != null && message.hasOwnProperty("clientStreaming")) + object.clientStreaming = message.clientStreaming; + if (message.serverStreaming != null && message.hasOwnProperty("serverStreaming")) + object.serverStreaming = message.serverStreaming; + return object; + }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.MethodDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + MethodDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MethodDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MethodDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.MethodDescriptorProto"; + }; + + return MethodDescriptorProto; + })(); + + protobuf.FileOptions = (function() { + + /** + * Properties of a FileOptions. + * @memberof google.protobuf + * @interface IFileOptions + * @property {string|null} [javaPackage] FileOptions javaPackage + * @property {string|null} [javaOuterClassname] FileOptions javaOuterClassname + * @property {boolean|null} [javaMultipleFiles] FileOptions javaMultipleFiles + * @property {boolean|null} [javaGenerateEqualsAndHash] FileOptions javaGenerateEqualsAndHash + * @property {boolean|null} [javaStringCheckUtf8] FileOptions javaStringCheckUtf8 + * @property {google.protobuf.FileOptions.OptimizeMode|null} [optimizeFor] FileOptions optimizeFor + * @property {string|null} [goPackage] FileOptions goPackage + * @property {boolean|null} [ccGenericServices] FileOptions ccGenericServices + * @property {boolean|null} [javaGenericServices] FileOptions javaGenericServices + * @property {boolean|null} [pyGenericServices] FileOptions pyGenericServices + * @property {boolean|null} [deprecated] FileOptions deprecated + * @property {boolean|null} [ccEnableArenas] FileOptions ccEnableArenas + * @property {string|null} [objcClassPrefix] FileOptions objcClassPrefix + * @property {string|null} [csharpNamespace] FileOptions csharpNamespace + * @property {string|null} [swiftPrefix] FileOptions swiftPrefix + * @property {string|null} [phpClassPrefix] FileOptions phpClassPrefix + * @property {string|null} [phpNamespace] FileOptions phpNamespace + * @property {string|null} [phpMetadataNamespace] FileOptions phpMetadataNamespace + * @property {string|null} [rubyPackage] FileOptions rubyPackage + * @property {google.protobuf.IFeatureSet|null} [features] FileOptions features + * @property {Array.|null} [uninterpretedOption] FileOptions uninterpretedOption + * @property {Array.|null} [".google.api.resourceDefinition"] FileOptions .google.api.resourceDefinition + */ + + /** + * Constructs a new FileOptions. + * @memberof google.protobuf + * @classdesc Represents a FileOptions. + * @implements IFileOptions + * @constructor + * @param {google.protobuf.IFileOptions=} [properties] Properties to set + */ + function FileOptions(properties) { + this.uninterpretedOption = []; + this[".google.api.resourceDefinition"] = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FileOptions javaPackage. + * @member {string} javaPackage + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaPackage = ""; + + /** + * FileOptions javaOuterClassname. + * @member {string} javaOuterClassname + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaOuterClassname = ""; + + /** + * FileOptions javaMultipleFiles. + * @member {boolean} javaMultipleFiles + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaMultipleFiles = false; + + /** + * FileOptions javaGenerateEqualsAndHash. + * @member {boolean} javaGenerateEqualsAndHash + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaGenerateEqualsAndHash = false; + + /** + * FileOptions javaStringCheckUtf8. + * @member {boolean} javaStringCheckUtf8 + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaStringCheckUtf8 = false; + + /** + * FileOptions optimizeFor. + * @member {google.protobuf.FileOptions.OptimizeMode} optimizeFor + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.optimizeFor = 1; + + /** + * FileOptions goPackage. + * @member {string} goPackage + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.goPackage = ""; + + /** + * FileOptions ccGenericServices. + * @member {boolean} ccGenericServices + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.ccGenericServices = false; + + /** + * FileOptions javaGenericServices. + * @member {boolean} javaGenericServices + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaGenericServices = false; + + /** + * FileOptions pyGenericServices. + * @member {boolean} pyGenericServices + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.pyGenericServices = false; + + /** + * FileOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.deprecated = false; + + /** + * FileOptions ccEnableArenas. + * @member {boolean} ccEnableArenas + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.ccEnableArenas = true; + + /** + * FileOptions objcClassPrefix. + * @member {string} objcClassPrefix + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.objcClassPrefix = ""; + + /** + * FileOptions csharpNamespace. + * @member {string} csharpNamespace + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.csharpNamespace = ""; + + /** + * FileOptions swiftPrefix. + * @member {string} swiftPrefix + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.swiftPrefix = ""; + + /** + * FileOptions phpClassPrefix. + * @member {string} phpClassPrefix + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.phpClassPrefix = ""; + + /** + * FileOptions phpNamespace. + * @member {string} phpNamespace + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.phpNamespace = ""; + + /** + * FileOptions phpMetadataNamespace. + * @member {string} phpMetadataNamespace + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.phpMetadataNamespace = ""; + + /** + * FileOptions rubyPackage. + * @member {string} rubyPackage + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.rubyPackage = ""; + + /** + * FileOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.features = null; + + /** + * FileOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * FileOptions .google.api.resourceDefinition. + * @member {Array.} .google.api.resourceDefinition + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype[".google.api.resourceDefinition"] = $util.emptyArray; + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FileOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FileOptions} FileOptions + */ + FileOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FileOptions) + return object; + var message = new $root.google.protobuf.FileOptions(); + if (object.javaPackage != null) + message.javaPackage = String(object.javaPackage); + if (object.javaOuterClassname != null) + message.javaOuterClassname = String(object.javaOuterClassname); + if (object.javaMultipleFiles != null) + message.javaMultipleFiles = Boolean(object.javaMultipleFiles); + if (object.javaGenerateEqualsAndHash != null) + message.javaGenerateEqualsAndHash = Boolean(object.javaGenerateEqualsAndHash); + if (object.javaStringCheckUtf8 != null) + message.javaStringCheckUtf8 = Boolean(object.javaStringCheckUtf8); + switch (object.optimizeFor) { + default: + if (typeof object.optimizeFor === "number") { + message.optimizeFor = object.optimizeFor; + break; + } + break; + case "SPEED": + case 1: + message.optimizeFor = 1; + break; + case "CODE_SIZE": + case 2: + message.optimizeFor = 2; + break; + case "LITE_RUNTIME": + case 3: + message.optimizeFor = 3; + break; + } + if (object.goPackage != null) + message.goPackage = String(object.goPackage); + if (object.ccGenericServices != null) + message.ccGenericServices = Boolean(object.ccGenericServices); + if (object.javaGenericServices != null) + message.javaGenericServices = Boolean(object.javaGenericServices); + if (object.pyGenericServices != null) + message.pyGenericServices = Boolean(object.pyGenericServices); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.ccEnableArenas != null) + message.ccEnableArenas = Boolean(object.ccEnableArenas); + if (object.objcClassPrefix != null) + message.objcClassPrefix = String(object.objcClassPrefix); + if (object.csharpNamespace != null) + message.csharpNamespace = String(object.csharpNamespace); + if (object.swiftPrefix != null) + message.swiftPrefix = String(object.swiftPrefix); + if (object.phpClassPrefix != null) + message.phpClassPrefix = String(object.phpClassPrefix); + if (object.phpNamespace != null) + message.phpNamespace = String(object.phpNamespace); + if (object.phpMetadataNamespace != null) + message.phpMetadataNamespace = String(object.phpMetadataNamespace); + if (object.rubyPackage != null) + message.rubyPackage = String(object.rubyPackage); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.FileOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.FileOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.FileOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.resourceDefinition"]) { + if (!Array.isArray(object[".google.api.resourceDefinition"])) + throw TypeError(".google.protobuf.FileOptions..google.api.resourceDefinition: array expected"); + message[".google.api.resourceDefinition"] = []; + for (var i = 0; i < object[".google.api.resourceDefinition"].length; ++i) { + if (typeof object[".google.api.resourceDefinition"][i] !== "object") + throw TypeError(".google.protobuf.FileOptions..google.api.resourceDefinition: object expected"); + message[".google.api.resourceDefinition"][i] = $root.google.api.ResourceDescriptor.fromObject(object[".google.api.resourceDefinition"][i]); + } + } + return message; + }; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FileOptions + * @static + * @param {google.protobuf.FileOptions} message FileOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FileOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.uninterpretedOption = []; + object[".google.api.resourceDefinition"] = []; + } + if (options.defaults) { + object.javaPackage = ""; + object.javaOuterClassname = ""; + object.optimizeFor = options.enums === String ? "SPEED" : 1; + object.javaMultipleFiles = false; + object.goPackage = ""; + object.ccGenericServices = false; + object.javaGenericServices = false; + object.pyGenericServices = false; + object.javaGenerateEqualsAndHash = false; + object.deprecated = false; + object.javaStringCheckUtf8 = false; + object.ccEnableArenas = true; + object.objcClassPrefix = ""; + object.csharpNamespace = ""; + object.swiftPrefix = ""; + object.phpClassPrefix = ""; + object.phpNamespace = ""; + object.phpMetadataNamespace = ""; + object.rubyPackage = ""; + object.features = null; + } + if (message.javaPackage != null && message.hasOwnProperty("javaPackage")) + object.javaPackage = message.javaPackage; + if (message.javaOuterClassname != null && message.hasOwnProperty("javaOuterClassname")) + object.javaOuterClassname = message.javaOuterClassname; + if (message.optimizeFor != null && message.hasOwnProperty("optimizeFor")) + object.optimizeFor = options.enums === String ? $root.google.protobuf.FileOptions.OptimizeMode[message.optimizeFor] === undefined ? message.optimizeFor : $root.google.protobuf.FileOptions.OptimizeMode[message.optimizeFor] : message.optimizeFor; + if (message.javaMultipleFiles != null && message.hasOwnProperty("javaMultipleFiles")) + object.javaMultipleFiles = message.javaMultipleFiles; + if (message.goPackage != null && message.hasOwnProperty("goPackage")) + object.goPackage = message.goPackage; + if (message.ccGenericServices != null && message.hasOwnProperty("ccGenericServices")) + object.ccGenericServices = message.ccGenericServices; + if (message.javaGenericServices != null && message.hasOwnProperty("javaGenericServices")) + object.javaGenericServices = message.javaGenericServices; + if (message.pyGenericServices != null && message.hasOwnProperty("pyGenericServices")) + object.pyGenericServices = message.pyGenericServices; + if (message.javaGenerateEqualsAndHash != null && message.hasOwnProperty("javaGenerateEqualsAndHash")) + object.javaGenerateEqualsAndHash = message.javaGenerateEqualsAndHash; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.javaStringCheckUtf8 != null && message.hasOwnProperty("javaStringCheckUtf8")) + object.javaStringCheckUtf8 = message.javaStringCheckUtf8; + if (message.ccEnableArenas != null && message.hasOwnProperty("ccEnableArenas")) + object.ccEnableArenas = message.ccEnableArenas; + if (message.objcClassPrefix != null && message.hasOwnProperty("objcClassPrefix")) + object.objcClassPrefix = message.objcClassPrefix; + if (message.csharpNamespace != null && message.hasOwnProperty("csharpNamespace")) + object.csharpNamespace = message.csharpNamespace; + if (message.swiftPrefix != null && message.hasOwnProperty("swiftPrefix")) + object.swiftPrefix = message.swiftPrefix; + if (message.phpClassPrefix != null && message.hasOwnProperty("phpClassPrefix")) + object.phpClassPrefix = message.phpClassPrefix; + if (message.phpNamespace != null && message.hasOwnProperty("phpNamespace")) + object.phpNamespace = message.phpNamespace; + if (message.phpMetadataNamespace != null && message.hasOwnProperty("phpMetadataNamespace")) + object.phpMetadataNamespace = message.phpMetadataNamespace; + if (message.rubyPackage != null && message.hasOwnProperty("rubyPackage")) + object.rubyPackage = message.rubyPackage; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.resourceDefinition"] && message[".google.api.resourceDefinition"].length) { + object[".google.api.resourceDefinition"] = []; + for (var j = 0; j < message[".google.api.resourceDefinition"].length; ++j) + object[".google.api.resourceDefinition"][j] = $root.google.api.ResourceDescriptor.toObject(message[".google.api.resourceDefinition"][j], options); + } + return object; + }; + + /** + * Converts this FileOptions to JSON. + * @function toJSON + * @memberof google.protobuf.FileOptions + * @instance + * @returns {Object.} JSON object + */ + FileOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FileOptions + * @function getTypeUrl + * @memberof google.protobuf.FileOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FileOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FileOptions"; + }; + + /** + * OptimizeMode enum. + * @name google.protobuf.FileOptions.OptimizeMode + * @enum {string} + * @property {string} SPEED=SPEED SPEED value + * @property {string} CODE_SIZE=CODE_SIZE CODE_SIZE value + * @property {string} LITE_RUNTIME=LITE_RUNTIME LITE_RUNTIME value + */ + FileOptions.OptimizeMode = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[1] = "SPEED"] = "SPEED"; + values[valuesById[2] = "CODE_SIZE"] = "CODE_SIZE"; + values[valuesById[3] = "LITE_RUNTIME"] = "LITE_RUNTIME"; + return values; + })(); + + return FileOptions; + })(); + + protobuf.MessageOptions = (function() { + + /** + * Properties of a MessageOptions. + * @memberof google.protobuf + * @interface IMessageOptions + * @property {boolean|null} [messageSetWireFormat] MessageOptions messageSetWireFormat + * @property {boolean|null} [noStandardDescriptorAccessor] MessageOptions noStandardDescriptorAccessor + * @property {boolean|null} [deprecated] MessageOptions deprecated + * @property {boolean|null} [mapEntry] MessageOptions mapEntry + * @property {boolean|null} [deprecatedLegacyJsonFieldConflicts] MessageOptions deprecatedLegacyJsonFieldConflicts + * @property {google.protobuf.IFeatureSet|null} [features] MessageOptions features + * @property {Array.|null} [uninterpretedOption] MessageOptions uninterpretedOption + * @property {google.api.IResourceDescriptor|null} [".google.api.resource"] MessageOptions .google.api.resource + */ + + /** + * Constructs a new MessageOptions. + * @memberof google.protobuf + * @classdesc Represents a MessageOptions. + * @implements IMessageOptions + * @constructor + * @param {google.protobuf.IMessageOptions=} [properties] Properties to set + */ + function MessageOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MessageOptions messageSetWireFormat. + * @member {boolean} messageSetWireFormat + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.messageSetWireFormat = false; + + /** + * MessageOptions noStandardDescriptorAccessor. + * @member {boolean} noStandardDescriptorAccessor + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.noStandardDescriptorAccessor = false; + + /** + * MessageOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.deprecated = false; + + /** + * MessageOptions mapEntry. + * @member {boolean} mapEntry + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.mapEntry = false; + + /** + * MessageOptions deprecatedLegacyJsonFieldConflicts. + * @member {boolean} deprecatedLegacyJsonFieldConflicts + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.deprecatedLegacyJsonFieldConflicts = false; + + /** + * MessageOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.features = null; + + /** + * MessageOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * MessageOptions .google.api.resource. + * @member {google.api.IResourceDescriptor|null|undefined} .google.api.resource + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype[".google.api.resource"] = null; + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.MessageOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.MessageOptions} MessageOptions + */ + MessageOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.MessageOptions) + return object; + var message = new $root.google.protobuf.MessageOptions(); + if (object.messageSetWireFormat != null) + message.messageSetWireFormat = Boolean(object.messageSetWireFormat); + if (object.noStandardDescriptorAccessor != null) + message.noStandardDescriptorAccessor = Boolean(object.noStandardDescriptorAccessor); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.mapEntry != null) + message.mapEntry = Boolean(object.mapEntry); + if (object.deprecatedLegacyJsonFieldConflicts != null) + message.deprecatedLegacyJsonFieldConflicts = Boolean(object.deprecatedLegacyJsonFieldConflicts); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.MessageOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.MessageOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.MessageOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.resource"] != null) { + if (typeof object[".google.api.resource"] !== "object") + throw TypeError(".google.protobuf.MessageOptions..google.api.resource: object expected"); + message[".google.api.resource"] = $root.google.api.ResourceDescriptor.fromObject(object[".google.api.resource"]); + } + return message; + }; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.MessageOptions + * @static + * @param {google.protobuf.MessageOptions} message MessageOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MessageOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.messageSetWireFormat = false; + object.noStandardDescriptorAccessor = false; + object.deprecated = false; + object.mapEntry = false; + object.deprecatedLegacyJsonFieldConflicts = false; + object.features = null; + object[".google.api.resource"] = null; + } + if (message.messageSetWireFormat != null && message.hasOwnProperty("messageSetWireFormat")) + object.messageSetWireFormat = message.messageSetWireFormat; + if (message.noStandardDescriptorAccessor != null && message.hasOwnProperty("noStandardDescriptorAccessor")) + object.noStandardDescriptorAccessor = message.noStandardDescriptorAccessor; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.mapEntry != null && message.hasOwnProperty("mapEntry")) + object.mapEntry = message.mapEntry; + if (message.deprecatedLegacyJsonFieldConflicts != null && message.hasOwnProperty("deprecatedLegacyJsonFieldConflicts")) + object.deprecatedLegacyJsonFieldConflicts = message.deprecatedLegacyJsonFieldConflicts; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.resource"] != null && message.hasOwnProperty(".google.api.resource")) + object[".google.api.resource"] = $root.google.api.ResourceDescriptor.toObject(message[".google.api.resource"], options); + return object; + }; + + /** + * Converts this MessageOptions to JSON. + * @function toJSON + * @memberof google.protobuf.MessageOptions + * @instance + * @returns {Object.} JSON object + */ + MessageOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MessageOptions + * @function getTypeUrl + * @memberof google.protobuf.MessageOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MessageOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.MessageOptions"; + }; + + return MessageOptions; + })(); + + protobuf.FieldOptions = (function() { + + /** + * Properties of a FieldOptions. + * @memberof google.protobuf + * @interface IFieldOptions + * @property {google.protobuf.FieldOptions.CType|null} [ctype] FieldOptions ctype + * @property {boolean|null} [packed] FieldOptions packed + * @property {google.protobuf.FieldOptions.JSType|null} [jstype] FieldOptions jstype + * @property {boolean|null} [lazy] FieldOptions lazy + * @property {boolean|null} [unverifiedLazy] FieldOptions unverifiedLazy + * @property {boolean|null} [deprecated] FieldOptions deprecated + * @property {boolean|null} [weak] FieldOptions weak + * @property {boolean|null} [debugRedact] FieldOptions debugRedact + * @property {google.protobuf.FieldOptions.OptionRetention|null} [retention] FieldOptions retention + * @property {Array.|null} [targets] FieldOptions targets + * @property {Array.|null} [editionDefaults] FieldOptions editionDefaults + * @property {google.protobuf.IFeatureSet|null} [features] FieldOptions features + * @property {Array.|null} [uninterpretedOption] FieldOptions uninterpretedOption + * @property {Array.|null} [".google.api.fieldBehavior"] FieldOptions .google.api.fieldBehavior + * @property {google.api.IResourceReference|null} [".google.api.resourceReference"] FieldOptions .google.api.resourceReference + */ + + /** + * Constructs a new FieldOptions. + * @memberof google.protobuf + * @classdesc Represents a FieldOptions. + * @implements IFieldOptions + * @constructor + * @param {google.protobuf.IFieldOptions=} [properties] Properties to set + */ + function FieldOptions(properties) { + this.targets = []; + this.editionDefaults = []; + this.uninterpretedOption = []; + this[".google.api.fieldBehavior"] = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldOptions ctype. + * @member {google.protobuf.FieldOptions.CType} ctype + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.ctype = 0; + + /** + * FieldOptions packed. + * @member {boolean} packed + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.packed = false; + + /** + * FieldOptions jstype. + * @member {google.protobuf.FieldOptions.JSType} jstype + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.jstype = 0; + + /** + * FieldOptions lazy. + * @member {boolean} lazy + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.lazy = false; + + /** + * FieldOptions unverifiedLazy. + * @member {boolean} unverifiedLazy + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.unverifiedLazy = false; + + /** + * FieldOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.deprecated = false; + + /** + * FieldOptions weak. + * @member {boolean} weak + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.weak = false; + + /** + * FieldOptions debugRedact. + * @member {boolean} debugRedact + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.debugRedact = false; + + /** + * FieldOptions retention. + * @member {google.protobuf.FieldOptions.OptionRetention} retention + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.retention = 0; + + /** + * FieldOptions targets. + * @member {Array.} targets + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.targets = $util.emptyArray; + + /** + * FieldOptions editionDefaults. + * @member {Array.} editionDefaults + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.editionDefaults = $util.emptyArray; + + /** + * FieldOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.features = null; + + /** + * FieldOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * FieldOptions .google.api.fieldBehavior. + * @member {Array.} .google.api.fieldBehavior + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype[".google.api.fieldBehavior"] = $util.emptyArray; + + /** + * FieldOptions .google.api.resourceReference. + * @member {google.api.IResourceReference|null|undefined} .google.api.resourceReference + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype[".google.api.resourceReference"] = null; + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldOptions} FieldOptions + */ + FieldOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldOptions) + return object; + var message = new $root.google.protobuf.FieldOptions(); + switch (object.ctype) { + default: + if (typeof object.ctype === "number") { + message.ctype = object.ctype; + break; + } + break; + case "STRING": + case 0: + message.ctype = 0; + break; + case "CORD": + case 1: + message.ctype = 1; + break; + case "STRING_PIECE": + case 2: + message.ctype = 2; + break; + } + if (object.packed != null) + message.packed = Boolean(object.packed); + switch (object.jstype) { + default: + if (typeof object.jstype === "number") { + message.jstype = object.jstype; + break; + } + break; + case "JS_NORMAL": + case 0: + message.jstype = 0; + break; + case "JS_STRING": + case 1: + message.jstype = 1; + break; + case "JS_NUMBER": + case 2: + message.jstype = 2; + break; + } + if (object.lazy != null) + message.lazy = Boolean(object.lazy); + if (object.unverifiedLazy != null) + message.unverifiedLazy = Boolean(object.unverifiedLazy); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.weak != null) + message.weak = Boolean(object.weak); + if (object.debugRedact != null) + message.debugRedact = Boolean(object.debugRedact); + switch (object.retention) { + default: + if (typeof object.retention === "number") { + message.retention = object.retention; + break; + } + break; + case "RETENTION_UNKNOWN": + case 0: + message.retention = 0; + break; + case "RETENTION_RUNTIME": + case 1: + message.retention = 1; + break; + case "RETENTION_SOURCE": + case 2: + message.retention = 2; + break; + } + if (object.targets) { + if (!Array.isArray(object.targets)) + throw TypeError(".google.protobuf.FieldOptions.targets: array expected"); + message.targets = []; + for (var i = 0; i < object.targets.length; ++i) + switch (object.targets[i]) { + default: + if (typeof object.targets[i] === "number") { + message.targets[i] = object.targets[i]; + break; + } + case "TARGET_TYPE_UNKNOWN": + case 0: + message.targets[i] = 0; + break; + case "TARGET_TYPE_FILE": + case 1: + message.targets[i] = 1; + break; + case "TARGET_TYPE_EXTENSION_RANGE": + case 2: + message.targets[i] = 2; + break; + case "TARGET_TYPE_MESSAGE": + case 3: + message.targets[i] = 3; + break; + case "TARGET_TYPE_FIELD": + case 4: + message.targets[i] = 4; + break; + case "TARGET_TYPE_ONEOF": + case 5: + message.targets[i] = 5; + break; + case "TARGET_TYPE_ENUM": + case 6: + message.targets[i] = 6; + break; + case "TARGET_TYPE_ENUM_ENTRY": + case 7: + message.targets[i] = 7; + break; + case "TARGET_TYPE_SERVICE": + case 8: + message.targets[i] = 8; + break; + case "TARGET_TYPE_METHOD": + case 9: + message.targets[i] = 9; + break; + } + } + if (object.editionDefaults) { + if (!Array.isArray(object.editionDefaults)) + throw TypeError(".google.protobuf.FieldOptions.editionDefaults: array expected"); + message.editionDefaults = []; + for (var i = 0; i < object.editionDefaults.length; ++i) { + if (typeof object.editionDefaults[i] !== "object") + throw TypeError(".google.protobuf.FieldOptions.editionDefaults: object expected"); + message.editionDefaults[i] = $root.google.protobuf.FieldOptions.EditionDefault.fromObject(object.editionDefaults[i]); + } + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.FieldOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.FieldOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.FieldOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.fieldBehavior"]) { + if (!Array.isArray(object[".google.api.fieldBehavior"])) + throw TypeError(".google.protobuf.FieldOptions..google.api.fieldBehavior: array expected"); + message[".google.api.fieldBehavior"] = []; + for (var i = 0; i < object[".google.api.fieldBehavior"].length; ++i) + switch (object[".google.api.fieldBehavior"][i]) { + default: + if (typeof object[".google.api.fieldBehavior"][i] === "number") { + message[".google.api.fieldBehavior"][i] = object[".google.api.fieldBehavior"][i]; + break; + } + case "FIELD_BEHAVIOR_UNSPECIFIED": + case 0: + message[".google.api.fieldBehavior"][i] = 0; + break; + case "OPTIONAL": + case 1: + message[".google.api.fieldBehavior"][i] = 1; + break; + case "REQUIRED": + case 2: + message[".google.api.fieldBehavior"][i] = 2; + break; + case "OUTPUT_ONLY": + case 3: + message[".google.api.fieldBehavior"][i] = 3; + break; + case "INPUT_ONLY": + case 4: + message[".google.api.fieldBehavior"][i] = 4; + break; + case "IMMUTABLE": + case 5: + message[".google.api.fieldBehavior"][i] = 5; + break; + case "UNORDERED_LIST": + case 6: + message[".google.api.fieldBehavior"][i] = 6; + break; + case "NON_EMPTY_DEFAULT": + case 7: + message[".google.api.fieldBehavior"][i] = 7; + break; + case "IDENTIFIER": + case 8: + message[".google.api.fieldBehavior"][i] = 8; + break; + } + } + if (object[".google.api.resourceReference"] != null) { + if (typeof object[".google.api.resourceReference"] !== "object") + throw TypeError(".google.protobuf.FieldOptions..google.api.resourceReference: object expected"); + message[".google.api.resourceReference"] = $root.google.api.ResourceReference.fromObject(object[".google.api.resourceReference"]); + } + return message; + }; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldOptions + * @static + * @param {google.protobuf.FieldOptions} message FieldOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.targets = []; + object.editionDefaults = []; + object.uninterpretedOption = []; + object[".google.api.fieldBehavior"] = []; + } + if (options.defaults) { + object.ctype = options.enums === String ? "STRING" : 0; + object.packed = false; + object.deprecated = false; + object.lazy = false; + object.jstype = options.enums === String ? "JS_NORMAL" : 0; + object.weak = false; + object.unverifiedLazy = false; + object.debugRedact = false; + object.retention = options.enums === String ? "RETENTION_UNKNOWN" : 0; + object.features = null; + object[".google.api.resourceReference"] = null; + } + if (message.ctype != null && message.hasOwnProperty("ctype")) + object.ctype = options.enums === String ? $root.google.protobuf.FieldOptions.CType[message.ctype] === undefined ? message.ctype : $root.google.protobuf.FieldOptions.CType[message.ctype] : message.ctype; + if (message.packed != null && message.hasOwnProperty("packed")) + object.packed = message.packed; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.lazy != null && message.hasOwnProperty("lazy")) + object.lazy = message.lazy; + if (message.jstype != null && message.hasOwnProperty("jstype")) + object.jstype = options.enums === String ? $root.google.protobuf.FieldOptions.JSType[message.jstype] === undefined ? message.jstype : $root.google.protobuf.FieldOptions.JSType[message.jstype] : message.jstype; + if (message.weak != null && message.hasOwnProperty("weak")) + object.weak = message.weak; + if (message.unverifiedLazy != null && message.hasOwnProperty("unverifiedLazy")) + object.unverifiedLazy = message.unverifiedLazy; + if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) + object.debugRedact = message.debugRedact; + if (message.retention != null && message.hasOwnProperty("retention")) + object.retention = options.enums === String ? $root.google.protobuf.FieldOptions.OptionRetention[message.retention] === undefined ? message.retention : $root.google.protobuf.FieldOptions.OptionRetention[message.retention] : message.retention; + if (message.targets && message.targets.length) { + object.targets = []; + for (var j = 0; j < message.targets.length; ++j) + object.targets[j] = options.enums === String ? $root.google.protobuf.FieldOptions.OptionTargetType[message.targets[j]] === undefined ? message.targets[j] : $root.google.protobuf.FieldOptions.OptionTargetType[message.targets[j]] : message.targets[j]; + } + if (message.editionDefaults && message.editionDefaults.length) { + object.editionDefaults = []; + for (var j = 0; j < message.editionDefaults.length; ++j) + object.editionDefaults[j] = $root.google.protobuf.FieldOptions.EditionDefault.toObject(message.editionDefaults[j], options); + } + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.fieldBehavior"] && message[".google.api.fieldBehavior"].length) { + object[".google.api.fieldBehavior"] = []; + for (var j = 0; j < message[".google.api.fieldBehavior"].length; ++j) + object[".google.api.fieldBehavior"][j] = options.enums === String ? $root.google.api.FieldBehavior[message[".google.api.fieldBehavior"][j]] === undefined ? message[".google.api.fieldBehavior"][j] : $root.google.api.FieldBehavior[message[".google.api.fieldBehavior"][j]] : message[".google.api.fieldBehavior"][j]; + } + if (message[".google.api.resourceReference"] != null && message.hasOwnProperty(".google.api.resourceReference")) + object[".google.api.resourceReference"] = $root.google.api.ResourceReference.toObject(message[".google.api.resourceReference"], options); + return object; + }; + + /** + * Converts this FieldOptions to JSON. + * @function toJSON + * @memberof google.protobuf.FieldOptions + * @instance + * @returns {Object.} JSON object + */ + FieldOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldOptions + * @function getTypeUrl + * @memberof google.protobuf.FieldOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldOptions"; + }; + + /** + * CType enum. + * @name google.protobuf.FieldOptions.CType + * @enum {string} + * @property {string} STRING=STRING STRING value + * @property {string} CORD=CORD CORD value + * @property {string} STRING_PIECE=STRING_PIECE STRING_PIECE value + */ + FieldOptions.CType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STRING"] = "STRING"; + values[valuesById[1] = "CORD"] = "CORD"; + values[valuesById[2] = "STRING_PIECE"] = "STRING_PIECE"; + return values; + })(); + + /** + * JSType enum. + * @name google.protobuf.FieldOptions.JSType + * @enum {string} + * @property {string} JS_NORMAL=JS_NORMAL JS_NORMAL value + * @property {string} JS_STRING=JS_STRING JS_STRING value + * @property {string} JS_NUMBER=JS_NUMBER JS_NUMBER value + */ + FieldOptions.JSType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "JS_NORMAL"] = "JS_NORMAL"; + values[valuesById[1] = "JS_STRING"] = "JS_STRING"; + values[valuesById[2] = "JS_NUMBER"] = "JS_NUMBER"; + return values; + })(); + + /** + * OptionRetention enum. + * @name google.protobuf.FieldOptions.OptionRetention + * @enum {string} + * @property {string} RETENTION_UNKNOWN=RETENTION_UNKNOWN RETENTION_UNKNOWN value + * @property {string} RETENTION_RUNTIME=RETENTION_RUNTIME RETENTION_RUNTIME value + * @property {string} RETENTION_SOURCE=RETENTION_SOURCE RETENTION_SOURCE value + */ + FieldOptions.OptionRetention = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "RETENTION_UNKNOWN"] = "RETENTION_UNKNOWN"; + values[valuesById[1] = "RETENTION_RUNTIME"] = "RETENTION_RUNTIME"; + values[valuesById[2] = "RETENTION_SOURCE"] = "RETENTION_SOURCE"; + return values; + })(); + + /** + * OptionTargetType enum. + * @name google.protobuf.FieldOptions.OptionTargetType + * @enum {string} + * @property {string} TARGET_TYPE_UNKNOWN=TARGET_TYPE_UNKNOWN TARGET_TYPE_UNKNOWN value + * @property {string} TARGET_TYPE_FILE=TARGET_TYPE_FILE TARGET_TYPE_FILE value + * @property {string} TARGET_TYPE_EXTENSION_RANGE=TARGET_TYPE_EXTENSION_RANGE TARGET_TYPE_EXTENSION_RANGE value + * @property {string} TARGET_TYPE_MESSAGE=TARGET_TYPE_MESSAGE TARGET_TYPE_MESSAGE value + * @property {string} TARGET_TYPE_FIELD=TARGET_TYPE_FIELD TARGET_TYPE_FIELD value + * @property {string} TARGET_TYPE_ONEOF=TARGET_TYPE_ONEOF TARGET_TYPE_ONEOF value + * @property {string} TARGET_TYPE_ENUM=TARGET_TYPE_ENUM TARGET_TYPE_ENUM value + * @property {string} TARGET_TYPE_ENUM_ENTRY=TARGET_TYPE_ENUM_ENTRY TARGET_TYPE_ENUM_ENTRY value + * @property {string} TARGET_TYPE_SERVICE=TARGET_TYPE_SERVICE TARGET_TYPE_SERVICE value + * @property {string} TARGET_TYPE_METHOD=TARGET_TYPE_METHOD TARGET_TYPE_METHOD value + */ + FieldOptions.OptionTargetType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "TARGET_TYPE_UNKNOWN"] = "TARGET_TYPE_UNKNOWN"; + values[valuesById[1] = "TARGET_TYPE_FILE"] = "TARGET_TYPE_FILE"; + values[valuesById[2] = "TARGET_TYPE_EXTENSION_RANGE"] = "TARGET_TYPE_EXTENSION_RANGE"; + values[valuesById[3] = "TARGET_TYPE_MESSAGE"] = "TARGET_TYPE_MESSAGE"; + values[valuesById[4] = "TARGET_TYPE_FIELD"] = "TARGET_TYPE_FIELD"; + values[valuesById[5] = "TARGET_TYPE_ONEOF"] = "TARGET_TYPE_ONEOF"; + values[valuesById[6] = "TARGET_TYPE_ENUM"] = "TARGET_TYPE_ENUM"; + values[valuesById[7] = "TARGET_TYPE_ENUM_ENTRY"] = "TARGET_TYPE_ENUM_ENTRY"; + values[valuesById[8] = "TARGET_TYPE_SERVICE"] = "TARGET_TYPE_SERVICE"; + values[valuesById[9] = "TARGET_TYPE_METHOD"] = "TARGET_TYPE_METHOD"; + return values; + })(); + + FieldOptions.EditionDefault = (function() { + + /** + * Properties of an EditionDefault. + * @memberof google.protobuf.FieldOptions + * @interface IEditionDefault + * @property {google.protobuf.Edition|null} [edition] EditionDefault edition + * @property {string|null} [value] EditionDefault value + */ + + /** + * Constructs a new EditionDefault. + * @memberof google.protobuf.FieldOptions + * @classdesc Represents an EditionDefault. + * @implements IEditionDefault + * @constructor + * @param {google.protobuf.FieldOptions.IEditionDefault=} [properties] Properties to set + */ + function EditionDefault(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EditionDefault edition. + * @member {google.protobuf.Edition} edition + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + */ + EditionDefault.prototype.edition = 0; + + /** + * EditionDefault value. + * @member {string} value + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + */ + EditionDefault.prototype.value = ""; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldOptions.EditionDefault} EditionDefault + */ + EditionDefault.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldOptions.EditionDefault) + return object; + var message = new $root.google.protobuf.FieldOptions.EditionDefault(); + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.edition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.edition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.edition = 999; + break; + case "EDITION_2023": + case 1000: + message.edition = 1000; + break; + case "EDITION_2024": + case 1001: + message.edition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.edition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.edition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.edition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.edition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.edition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.edition = 2147483647; + break; + } + if (object.value != null) + message.value = String(object.value); + return message; + }; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {google.protobuf.FieldOptions.EditionDefault} message EditionDefault + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EditionDefault.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.value = ""; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; + return object; + }; + + /** + * Converts this EditionDefault to JSON. + * @function toJSON + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + * @returns {Object.} JSON object + */ + EditionDefault.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EditionDefault + * @function getTypeUrl + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldOptions.EditionDefault"; + }; + + return EditionDefault; + })(); + + return FieldOptions; + })(); + + protobuf.OneofOptions = (function() { + + /** + * Properties of an OneofOptions. + * @memberof google.protobuf + * @interface IOneofOptions + * @property {google.protobuf.IFeatureSet|null} [features] OneofOptions features + * @property {Array.|null} [uninterpretedOption] OneofOptions uninterpretedOption + */ + + /** + * Constructs a new OneofOptions. + * @memberof google.protobuf + * @classdesc Represents an OneofOptions. + * @implements IOneofOptions + * @constructor + * @param {google.protobuf.IOneofOptions=} [properties] Properties to set + */ + function OneofOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OneofOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.OneofOptions + * @instance + */ + OneofOptions.prototype.features = null; + + /** + * OneofOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.OneofOptions + * @instance + */ + OneofOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.OneofOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.OneofOptions} OneofOptions + */ + OneofOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.OneofOptions) + return object; + var message = new $root.google.protobuf.OneofOptions(); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.OneofOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.OneofOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.OneofOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.OneofOptions + * @static + * @param {google.protobuf.OneofOptions} message OneofOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OneofOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) + object.features = null; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this OneofOptions to JSON. + * @function toJSON + * @memberof google.protobuf.OneofOptions + * @instance + * @returns {Object.} JSON object + */ + OneofOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OneofOptions + * @function getTypeUrl + * @memberof google.protobuf.OneofOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OneofOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.OneofOptions"; + }; + + return OneofOptions; + })(); + + protobuf.EnumOptions = (function() { + + /** + * Properties of an EnumOptions. + * @memberof google.protobuf + * @interface IEnumOptions + * @property {boolean|null} [allowAlias] EnumOptions allowAlias + * @property {boolean|null} [deprecated] EnumOptions deprecated + * @property {boolean|null} [deprecatedLegacyJsonFieldConflicts] EnumOptions deprecatedLegacyJsonFieldConflicts + * @property {google.protobuf.IFeatureSet|null} [features] EnumOptions features + * @property {Array.|null} [uninterpretedOption] EnumOptions uninterpretedOption + */ + + /** + * Constructs a new EnumOptions. + * @memberof google.protobuf + * @classdesc Represents an EnumOptions. + * @implements IEnumOptions + * @constructor + * @param {google.protobuf.IEnumOptions=} [properties] Properties to set + */ + function EnumOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumOptions allowAlias. + * @member {boolean} allowAlias + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.allowAlias = false; + + /** + * EnumOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.deprecated = false; + + /** + * EnumOptions deprecatedLegacyJsonFieldConflicts. + * @member {boolean} deprecatedLegacyJsonFieldConflicts + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.deprecatedLegacyJsonFieldConflicts = false; + + /** + * EnumOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.features = null; + + /** + * EnumOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumOptions} EnumOptions + */ + EnumOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumOptions) + return object; + var message = new $root.google.protobuf.EnumOptions(); + if (object.allowAlias != null) + message.allowAlias = Boolean(object.allowAlias); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.deprecatedLegacyJsonFieldConflicts != null) + message.deprecatedLegacyJsonFieldConflicts = Boolean(object.deprecatedLegacyJsonFieldConflicts); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.EnumOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.EnumOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.EnumOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumOptions + * @static + * @param {google.protobuf.EnumOptions} message EnumOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.allowAlias = false; + object.deprecated = false; + object.deprecatedLegacyJsonFieldConflicts = false; + object.features = null; + } + if (message.allowAlias != null && message.hasOwnProperty("allowAlias")) + object.allowAlias = message.allowAlias; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.deprecatedLegacyJsonFieldConflicts != null && message.hasOwnProperty("deprecatedLegacyJsonFieldConflicts")) + object.deprecatedLegacyJsonFieldConflicts = message.deprecatedLegacyJsonFieldConflicts; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this EnumOptions to JSON. + * @function toJSON + * @memberof google.protobuf.EnumOptions + * @instance + * @returns {Object.} JSON object + */ + EnumOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumOptions + * @function getTypeUrl + * @memberof google.protobuf.EnumOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumOptions"; + }; + + return EnumOptions; + })(); + + protobuf.EnumValueOptions = (function() { + + /** + * Properties of an EnumValueOptions. + * @memberof google.protobuf + * @interface IEnumValueOptions + * @property {boolean|null} [deprecated] EnumValueOptions deprecated + * @property {google.protobuf.IFeatureSet|null} [features] EnumValueOptions features + * @property {boolean|null} [debugRedact] EnumValueOptions debugRedact + * @property {Array.|null} [uninterpretedOption] EnumValueOptions uninterpretedOption + */ + + /** + * Constructs a new EnumValueOptions. + * @memberof google.protobuf + * @classdesc Represents an EnumValueOptions. + * @implements IEnumValueOptions + * @constructor + * @param {google.protobuf.IEnumValueOptions=} [properties] Properties to set + */ + function EnumValueOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumValueOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.deprecated = false; + + /** + * EnumValueOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.features = null; + + /** + * EnumValueOptions debugRedact. + * @member {boolean} debugRedact + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.debugRedact = false; + + /** + * EnumValueOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumValueOptions} EnumValueOptions + */ + EnumValueOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumValueOptions) + return object; + var message = new $root.google.protobuf.EnumValueOptions(); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.debugRedact != null) + message.debugRedact = Boolean(object.debugRedact); + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.EnumValueOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {google.protobuf.EnumValueOptions} message EnumValueOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumValueOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.deprecated = false; + object.features = null; + object.debugRedact = false; + } + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) + object.debugRedact = message.debugRedact; + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this EnumValueOptions to JSON. + * @function toJSON + * @memberof google.protobuf.EnumValueOptions + * @instance + * @returns {Object.} JSON object + */ + EnumValueOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumValueOptions + * @function getTypeUrl + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumValueOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumValueOptions"; + }; + + return EnumValueOptions; + })(); + + protobuf.ServiceOptions = (function() { + + /** + * Properties of a ServiceOptions. + * @memberof google.protobuf + * @interface IServiceOptions + * @property {google.protobuf.IFeatureSet|null} [features] ServiceOptions features + * @property {boolean|null} [deprecated] ServiceOptions deprecated + * @property {Array.|null} [uninterpretedOption] ServiceOptions uninterpretedOption + * @property {string|null} [".google.api.defaultHost"] ServiceOptions .google.api.defaultHost + * @property {string|null} [".google.api.oauthScopes"] ServiceOptions .google.api.oauthScopes + * @property {string|null} [".google.api.apiVersion"] ServiceOptions .google.api.apiVersion + */ + + /** + * Constructs a new ServiceOptions. + * @memberof google.protobuf + * @classdesc Represents a ServiceOptions. + * @implements IServiceOptions + * @constructor + * @param {google.protobuf.IServiceOptions=} [properties] Properties to set + */ + function ServiceOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ServiceOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype.features = null; + + /** + * ServiceOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype.deprecated = false; + + /** + * ServiceOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * ServiceOptions .google.api.defaultHost. + * @member {string} .google.api.defaultHost + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype[".google.api.defaultHost"] = ""; + + /** + * ServiceOptions .google.api.oauthScopes. + * @member {string} .google.api.oauthScopes + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype[".google.api.oauthScopes"] = ""; + + /** + * ServiceOptions .google.api.apiVersion. + * @member {string} .google.api.apiVersion + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype[".google.api.apiVersion"] = ""; + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ServiceOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ServiceOptions} ServiceOptions + */ + ServiceOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ServiceOptions) + return object; + var message = new $root.google.protobuf.ServiceOptions(); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.ServiceOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.ServiceOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.ServiceOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.defaultHost"] != null) + message[".google.api.defaultHost"] = String(object[".google.api.defaultHost"]); + if (object[".google.api.oauthScopes"] != null) + message[".google.api.oauthScopes"] = String(object[".google.api.oauthScopes"]); + if (object[".google.api.apiVersion"] != null) + message[".google.api.apiVersion"] = String(object[".google.api.apiVersion"]); + return message; + }; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ServiceOptions + * @static + * @param {google.protobuf.ServiceOptions} message ServiceOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ServiceOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.deprecated = false; + object.features = null; + object[".google.api.defaultHost"] = ""; + object[".google.api.oauthScopes"] = ""; + object[".google.api.apiVersion"] = ""; + } + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.defaultHost"] != null && message.hasOwnProperty(".google.api.defaultHost")) + object[".google.api.defaultHost"] = message[".google.api.defaultHost"]; + if (message[".google.api.oauthScopes"] != null && message.hasOwnProperty(".google.api.oauthScopes")) + object[".google.api.oauthScopes"] = message[".google.api.oauthScopes"]; + if (message[".google.api.apiVersion"] != null && message.hasOwnProperty(".google.api.apiVersion")) + object[".google.api.apiVersion"] = message[".google.api.apiVersion"]; + return object; + }; + + /** + * Converts this ServiceOptions to JSON. + * @function toJSON + * @memberof google.protobuf.ServiceOptions + * @instance + * @returns {Object.} JSON object + */ + ServiceOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ServiceOptions + * @function getTypeUrl + * @memberof google.protobuf.ServiceOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ServiceOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ServiceOptions"; + }; + + return ServiceOptions; + })(); + + protobuf.MethodOptions = (function() { + + /** + * Properties of a MethodOptions. + * @memberof google.protobuf + * @interface IMethodOptions + * @property {boolean|null} [deprecated] MethodOptions deprecated + * @property {google.protobuf.MethodOptions.IdempotencyLevel|null} [idempotencyLevel] MethodOptions idempotencyLevel + * @property {google.protobuf.IFeatureSet|null} [features] MethodOptions features + * @property {Array.|null} [uninterpretedOption] MethodOptions uninterpretedOption + * @property {google.api.IHttpRule|null} [".google.api.http"] MethodOptions .google.api.http + * @property {Array.|null} [".google.api.methodSignature"] MethodOptions .google.api.methodSignature + * @property {google.api.IRoutingRule|null} [".google.api.routing"] MethodOptions .google.api.routing + * @property {google.longrunning.IOperationInfo|null} [".google.longrunning.operationInfo"] MethodOptions .google.longrunning.operationInfo + */ + + /** + * Constructs a new MethodOptions. + * @memberof google.protobuf + * @classdesc Represents a MethodOptions. + * @implements IMethodOptions + * @constructor + * @param {google.protobuf.IMethodOptions=} [properties] Properties to set + */ + function MethodOptions(properties) { + this.uninterpretedOption = []; + this[".google.api.methodSignature"] = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MethodOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.deprecated = false; + + /** + * MethodOptions idempotencyLevel. + * @member {google.protobuf.MethodOptions.IdempotencyLevel} idempotencyLevel + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.idempotencyLevel = 0; + + /** + * MethodOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.features = null; + + /** + * MethodOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * MethodOptions .google.api.http. + * @member {google.api.IHttpRule|null|undefined} .google.api.http + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.api.http"] = null; + + /** + * MethodOptions .google.api.methodSignature. + * @member {Array.} .google.api.methodSignature + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.api.methodSignature"] = $util.emptyArray; + + /** + * MethodOptions .google.api.routing. + * @member {google.api.IRoutingRule|null|undefined} .google.api.routing + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.api.routing"] = null; + + /** + * MethodOptions .google.longrunning.operationInfo. + * @member {google.longrunning.IOperationInfo|null|undefined} .google.longrunning.operationInfo + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.longrunning.operationInfo"] = null; + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.MethodOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.MethodOptions} MethodOptions + */ + MethodOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.MethodOptions) + return object; + var message = new $root.google.protobuf.MethodOptions(); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + switch (object.idempotencyLevel) { + default: + if (typeof object.idempotencyLevel === "number") { + message.idempotencyLevel = object.idempotencyLevel; + break; + } + break; + case "IDEMPOTENCY_UNKNOWN": + case 0: + message.idempotencyLevel = 0; + break; + case "NO_SIDE_EFFECTS": + case 1: + message.idempotencyLevel = 1; + break; + case "IDEMPOTENT": + case 2: + message.idempotencyLevel = 2; + break; + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.MethodOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.MethodOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.MethodOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.http"] != null) { + if (typeof object[".google.api.http"] !== "object") + throw TypeError(".google.protobuf.MethodOptions..google.api.http: object expected"); + message[".google.api.http"] = $root.google.api.HttpRule.fromObject(object[".google.api.http"]); + } + if (object[".google.api.methodSignature"]) { + if (!Array.isArray(object[".google.api.methodSignature"])) + throw TypeError(".google.protobuf.MethodOptions..google.api.methodSignature: array expected"); + message[".google.api.methodSignature"] = []; + for (var i = 0; i < object[".google.api.methodSignature"].length; ++i) + message[".google.api.methodSignature"][i] = String(object[".google.api.methodSignature"][i]); + } + if (object[".google.api.routing"] != null) { + if (typeof object[".google.api.routing"] !== "object") + throw TypeError(".google.protobuf.MethodOptions..google.api.routing: object expected"); + message[".google.api.routing"] = $root.google.api.RoutingRule.fromObject(object[".google.api.routing"]); + } + if (object[".google.longrunning.operationInfo"] != null) { + if (typeof object[".google.longrunning.operationInfo"] !== "object") + throw TypeError(".google.protobuf.MethodOptions..google.longrunning.operationInfo: object expected"); + message[".google.longrunning.operationInfo"] = $root.google.longrunning.OperationInfo.fromObject(object[".google.longrunning.operationInfo"]); + } + return message; + }; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.MethodOptions + * @static + * @param {google.protobuf.MethodOptions} message MethodOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MethodOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.uninterpretedOption = []; + object[".google.api.methodSignature"] = []; + } + if (options.defaults) { + object.deprecated = false; + object.idempotencyLevel = options.enums === String ? "IDEMPOTENCY_UNKNOWN" : 0; + object.features = null; + object[".google.longrunning.operationInfo"] = null; + object[".google.api.http"] = null; + object[".google.api.routing"] = null; + } + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.idempotencyLevel != null && message.hasOwnProperty("idempotencyLevel")) + object.idempotencyLevel = options.enums === String ? $root.google.protobuf.MethodOptions.IdempotencyLevel[message.idempotencyLevel] === undefined ? message.idempotencyLevel : $root.google.protobuf.MethodOptions.IdempotencyLevel[message.idempotencyLevel] : message.idempotencyLevel; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.longrunning.operationInfo"] != null && message.hasOwnProperty(".google.longrunning.operationInfo")) + object[".google.longrunning.operationInfo"] = $root.google.longrunning.OperationInfo.toObject(message[".google.longrunning.operationInfo"], options); + if (message[".google.api.methodSignature"] && message[".google.api.methodSignature"].length) { + object[".google.api.methodSignature"] = []; + for (var j = 0; j < message[".google.api.methodSignature"].length; ++j) + object[".google.api.methodSignature"][j] = message[".google.api.methodSignature"][j]; + } + if (message[".google.api.http"] != null && message.hasOwnProperty(".google.api.http")) + object[".google.api.http"] = $root.google.api.HttpRule.toObject(message[".google.api.http"], options); + if (message[".google.api.routing"] != null && message.hasOwnProperty(".google.api.routing")) + object[".google.api.routing"] = $root.google.api.RoutingRule.toObject(message[".google.api.routing"], options); + return object; + }; + + /** + * Converts this MethodOptions to JSON. + * @function toJSON + * @memberof google.protobuf.MethodOptions + * @instance + * @returns {Object.} JSON object + */ + MethodOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MethodOptions + * @function getTypeUrl + * @memberof google.protobuf.MethodOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MethodOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.MethodOptions"; + }; + + /** + * IdempotencyLevel enum. + * @name google.protobuf.MethodOptions.IdempotencyLevel + * @enum {string} + * @property {string} IDEMPOTENCY_UNKNOWN=IDEMPOTENCY_UNKNOWN IDEMPOTENCY_UNKNOWN value + * @property {string} NO_SIDE_EFFECTS=NO_SIDE_EFFECTS NO_SIDE_EFFECTS value + * @property {string} IDEMPOTENT=IDEMPOTENT IDEMPOTENT value + */ + MethodOptions.IdempotencyLevel = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; + values[valuesById[1] = "NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; + values[valuesById[2] = "IDEMPOTENT"] = "IDEMPOTENT"; + return values; + })(); + + return MethodOptions; + })(); + + protobuf.UninterpretedOption = (function() { + + /** + * Properties of an UninterpretedOption. + * @memberof google.protobuf + * @interface IUninterpretedOption + * @property {Array.|null} [name] UninterpretedOption name + * @property {string|null} [identifierValue] UninterpretedOption identifierValue + * @property {number|string|null} [positiveIntValue] UninterpretedOption positiveIntValue + * @property {number|string|null} [negativeIntValue] UninterpretedOption negativeIntValue + * @property {number|null} [doubleValue] UninterpretedOption doubleValue + * @property {Uint8Array|null} [stringValue] UninterpretedOption stringValue + * @property {string|null} [aggregateValue] UninterpretedOption aggregateValue + */ + + /** + * Constructs a new UninterpretedOption. + * @memberof google.protobuf + * @classdesc Represents an UninterpretedOption. + * @implements IUninterpretedOption + * @constructor + * @param {google.protobuf.IUninterpretedOption=} [properties] Properties to set + */ + function UninterpretedOption(properties) { + this.name = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UninterpretedOption name. + * @member {Array.} name + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.name = $util.emptyArray; + + /** + * UninterpretedOption identifierValue. + * @member {string} identifierValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.identifierValue = ""; + + /** + * UninterpretedOption positiveIntValue. + * @member {number|string} positiveIntValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.positiveIntValue = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * UninterpretedOption negativeIntValue. + * @member {number|string} negativeIntValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.negativeIntValue = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * UninterpretedOption doubleValue. + * @member {number} doubleValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.doubleValue = 0; + + /** + * UninterpretedOption stringValue. + * @member {Uint8Array} stringValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.stringValue = $util.newBuffer([]); + + /** + * UninterpretedOption aggregateValue. + * @member {string} aggregateValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.aggregateValue = ""; + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.UninterpretedOption} UninterpretedOption + */ + UninterpretedOption.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UninterpretedOption) + return object; + var message = new $root.google.protobuf.UninterpretedOption(); + if (object.name) { + if (!Array.isArray(object.name)) + throw TypeError(".google.protobuf.UninterpretedOption.name: array expected"); + message.name = []; + for (var i = 0; i < object.name.length; ++i) { + if (typeof object.name[i] !== "object") + throw TypeError(".google.protobuf.UninterpretedOption.name: object expected"); + message.name[i] = $root.google.protobuf.UninterpretedOption.NamePart.fromObject(object.name[i]); + } + } + if (object.identifierValue != null) + message.identifierValue = String(object.identifierValue); + if (object.positiveIntValue != null) + if ($util.Long) + (message.positiveIntValue = $util.Long.fromValue(object.positiveIntValue)).unsigned = true; + else if (typeof object.positiveIntValue === "string") + message.positiveIntValue = parseInt(object.positiveIntValue, 10); + else if (typeof object.positiveIntValue === "number") + message.positiveIntValue = object.positiveIntValue; + else if (typeof object.positiveIntValue === "object") + message.positiveIntValue = new $util.LongBits(object.positiveIntValue.low >>> 0, object.positiveIntValue.high >>> 0).toNumber(true); + if (object.negativeIntValue != null) + if ($util.Long) + (message.negativeIntValue = $util.Long.fromValue(object.negativeIntValue)).unsigned = false; + else if (typeof object.negativeIntValue === "string") + message.negativeIntValue = parseInt(object.negativeIntValue, 10); + else if (typeof object.negativeIntValue === "number") + message.negativeIntValue = object.negativeIntValue; + else if (typeof object.negativeIntValue === "object") + message.negativeIntValue = new $util.LongBits(object.negativeIntValue.low >>> 0, object.negativeIntValue.high >>> 0).toNumber(); + if (object.doubleValue != null) + message.doubleValue = Number(object.doubleValue); + if (object.stringValue != null) + if (typeof object.stringValue === "string") + $util.base64.decode(object.stringValue, message.stringValue = $util.newBuffer($util.base64.length(object.stringValue)), 0); + else if (object.stringValue.length >= 0) + message.stringValue = object.stringValue; + if (object.aggregateValue != null) + message.aggregateValue = String(object.aggregateValue); + return message; + }; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {google.protobuf.UninterpretedOption} message UninterpretedOption + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UninterpretedOption.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.name = []; + if (options.defaults) { + object.identifierValue = ""; + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.positiveIntValue = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.positiveIntValue = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.negativeIntValue = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.negativeIntValue = options.longs === String ? "0" : 0; + object.doubleValue = 0; + if (options.bytes === String) + object.stringValue = ""; + else { + object.stringValue = []; + if (options.bytes !== Array) + object.stringValue = $util.newBuffer(object.stringValue); + } + object.aggregateValue = ""; + } + if (message.name && message.name.length) { + object.name = []; + for (var j = 0; j < message.name.length; ++j) + object.name[j] = $root.google.protobuf.UninterpretedOption.NamePart.toObject(message.name[j], options); + } + if (message.identifierValue != null && message.hasOwnProperty("identifierValue")) + object.identifierValue = message.identifierValue; + if (message.positiveIntValue != null && message.hasOwnProperty("positiveIntValue")) + if (typeof message.positiveIntValue === "number") + object.positiveIntValue = options.longs === String ? String(message.positiveIntValue) : message.positiveIntValue; + else + object.positiveIntValue = options.longs === String ? $util.Long.prototype.toString.call(message.positiveIntValue) : options.longs === Number ? new $util.LongBits(message.positiveIntValue.low >>> 0, message.positiveIntValue.high >>> 0).toNumber(true) : message.positiveIntValue; + if (message.negativeIntValue != null && message.hasOwnProperty("negativeIntValue")) + if (typeof message.negativeIntValue === "number") + object.negativeIntValue = options.longs === String ? String(message.negativeIntValue) : message.negativeIntValue; + else + object.negativeIntValue = options.longs === String ? $util.Long.prototype.toString.call(message.negativeIntValue) : options.longs === Number ? new $util.LongBits(message.negativeIntValue.low >>> 0, message.negativeIntValue.high >>> 0).toNumber() : message.negativeIntValue; + if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) + object.doubleValue = options.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue; + if (message.stringValue != null && message.hasOwnProperty("stringValue")) + object.stringValue = options.bytes === String ? $util.base64.encode(message.stringValue, 0, message.stringValue.length) : options.bytes === Array ? Array.prototype.slice.call(message.stringValue) : message.stringValue; + if (message.aggregateValue != null && message.hasOwnProperty("aggregateValue")) + object.aggregateValue = message.aggregateValue; + return object; + }; + + /** + * Converts this UninterpretedOption to JSON. + * @function toJSON + * @memberof google.protobuf.UninterpretedOption + * @instance + * @returns {Object.} JSON object + */ + UninterpretedOption.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UninterpretedOption + * @function getTypeUrl + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UninterpretedOption.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.UninterpretedOption"; + }; + + UninterpretedOption.NamePart = (function() { + + /** + * Properties of a NamePart. + * @memberof google.protobuf.UninterpretedOption + * @interface INamePart + * @property {string} namePart NamePart namePart + * @property {boolean} isExtension NamePart isExtension + */ + + /** + * Constructs a new NamePart. + * @memberof google.protobuf.UninterpretedOption + * @classdesc Represents a NamePart. + * @implements INamePart + * @constructor + * @param {google.protobuf.UninterpretedOption.INamePart=} [properties] Properties to set + */ + function NamePart(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * NamePart namePart. + * @member {string} namePart + * @memberof google.protobuf.UninterpretedOption.NamePart + * @instance + */ + NamePart.prototype.namePart = ""; + + /** + * NamePart isExtension. + * @member {boolean} isExtension + * @memberof google.protobuf.UninterpretedOption.NamePart + * @instance + */ + NamePart.prototype.isExtension = false; + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.UninterpretedOption.NamePart} NamePart + */ + NamePart.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UninterpretedOption.NamePart) + return object; + var message = new $root.google.protobuf.UninterpretedOption.NamePart(); + if (object.namePart != null) + message.namePart = String(object.namePart); + if (object.isExtension != null) + message.isExtension = Boolean(object.isExtension); + return message; + }; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {google.protobuf.UninterpretedOption.NamePart} message NamePart + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + NamePart.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.namePart = ""; + object.isExtension = false; + } + if (message.namePart != null && message.hasOwnProperty("namePart")) + object.namePart = message.namePart; + if (message.isExtension != null && message.hasOwnProperty("isExtension")) + object.isExtension = message.isExtension; + return object; + }; + + /** + * Converts this NamePart to JSON. + * @function toJSON + * @memberof google.protobuf.UninterpretedOption.NamePart + * @instance + * @returns {Object.} JSON object + */ + NamePart.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for NamePart + * @function getTypeUrl + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + NamePart.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.UninterpretedOption.NamePart"; + }; + + return NamePart; + })(); + + return UninterpretedOption; + })(); + + protobuf.FeatureSet = (function() { + + /** + * Properties of a FeatureSet. + * @memberof google.protobuf + * @interface IFeatureSet + * @property {google.protobuf.FeatureSet.FieldPresence|null} [fieldPresence] FeatureSet fieldPresence + * @property {google.protobuf.FeatureSet.EnumType|null} [enumType] FeatureSet enumType + * @property {google.protobuf.FeatureSet.RepeatedFieldEncoding|null} [repeatedFieldEncoding] FeatureSet repeatedFieldEncoding + * @property {google.protobuf.FeatureSet.Utf8Validation|null} [utf8Validation] FeatureSet utf8Validation + * @property {google.protobuf.FeatureSet.MessageEncoding|null} [messageEncoding] FeatureSet messageEncoding + * @property {google.protobuf.FeatureSet.JsonFormat|null} [jsonFormat] FeatureSet jsonFormat + */ + + /** + * Constructs a new FeatureSet. + * @memberof google.protobuf + * @classdesc Represents a FeatureSet. + * @implements IFeatureSet + * @constructor + * @param {google.protobuf.IFeatureSet=} [properties] Properties to set + */ + function FeatureSet(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FeatureSet fieldPresence. + * @member {google.protobuf.FeatureSet.FieldPresence} fieldPresence + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.fieldPresence = 0; + + /** + * FeatureSet enumType. + * @member {google.protobuf.FeatureSet.EnumType} enumType + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.enumType = 0; + + /** + * FeatureSet repeatedFieldEncoding. + * @member {google.protobuf.FeatureSet.RepeatedFieldEncoding} repeatedFieldEncoding + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.repeatedFieldEncoding = 0; + + /** + * FeatureSet utf8Validation. + * @member {google.protobuf.FeatureSet.Utf8Validation} utf8Validation + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.utf8Validation = 0; + + /** + * FeatureSet messageEncoding. + * @member {google.protobuf.FeatureSet.MessageEncoding} messageEncoding + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.messageEncoding = 0; + + /** + * FeatureSet jsonFormat. + * @member {google.protobuf.FeatureSet.JsonFormat} jsonFormat + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.jsonFormat = 0; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSet + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSet} FeatureSet + */ + FeatureSet.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSet) + return object; + var message = new $root.google.protobuf.FeatureSet(); + switch (object.fieldPresence) { + default: + if (typeof object.fieldPresence === "number") { + message.fieldPresence = object.fieldPresence; + break; + } + break; + case "FIELD_PRESENCE_UNKNOWN": + case 0: + message.fieldPresence = 0; + break; + case "EXPLICIT": + case 1: + message.fieldPresence = 1; + break; + case "IMPLICIT": + case 2: + message.fieldPresence = 2; + break; + case "LEGACY_REQUIRED": + case 3: + message.fieldPresence = 3; + break; + } + switch (object.enumType) { + default: + if (typeof object.enumType === "number") { + message.enumType = object.enumType; + break; + } + break; + case "ENUM_TYPE_UNKNOWN": + case 0: + message.enumType = 0; + break; + case "OPEN": + case 1: + message.enumType = 1; + break; + case "CLOSED": + case 2: + message.enumType = 2; + break; + } + switch (object.repeatedFieldEncoding) { + default: + if (typeof object.repeatedFieldEncoding === "number") { + message.repeatedFieldEncoding = object.repeatedFieldEncoding; + break; + } + break; + case "REPEATED_FIELD_ENCODING_UNKNOWN": + case 0: + message.repeatedFieldEncoding = 0; + break; + case "PACKED": + case 1: + message.repeatedFieldEncoding = 1; + break; + case "EXPANDED": + case 2: + message.repeatedFieldEncoding = 2; + break; + } + switch (object.utf8Validation) { + default: + if (typeof object.utf8Validation === "number") { + message.utf8Validation = object.utf8Validation; + break; + } + break; + case "UTF8_VALIDATION_UNKNOWN": + case 0: + message.utf8Validation = 0; + break; + case "VERIFY": + case 2: + message.utf8Validation = 2; + break; + case "NONE": + case 3: + message.utf8Validation = 3; + break; + } + switch (object.messageEncoding) { + default: + if (typeof object.messageEncoding === "number") { + message.messageEncoding = object.messageEncoding; + break; + } + break; + case "MESSAGE_ENCODING_UNKNOWN": + case 0: + message.messageEncoding = 0; + break; + case "LENGTH_PREFIXED": + case 1: + message.messageEncoding = 1; + break; + case "DELIMITED": + case 2: + message.messageEncoding = 2; + break; + } + switch (object.jsonFormat) { + default: + if (typeof object.jsonFormat === "number") { + message.jsonFormat = object.jsonFormat; + break; + } + break; + case "JSON_FORMAT_UNKNOWN": + case 0: + message.jsonFormat = 0; + break; + case "ALLOW": + case 1: + message.jsonFormat = 1; + break; + case "LEGACY_BEST_EFFORT": + case 2: + message.jsonFormat = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSet + * @static + * @param {google.protobuf.FeatureSet} message FeatureSet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FeatureSet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.fieldPresence = options.enums === String ? "FIELD_PRESENCE_UNKNOWN" : 0; + object.enumType = options.enums === String ? "ENUM_TYPE_UNKNOWN" : 0; + object.repeatedFieldEncoding = options.enums === String ? "REPEATED_FIELD_ENCODING_UNKNOWN" : 0; + object.utf8Validation = options.enums === String ? "UTF8_VALIDATION_UNKNOWN" : 0; + object.messageEncoding = options.enums === String ? "MESSAGE_ENCODING_UNKNOWN" : 0; + object.jsonFormat = options.enums === String ? "JSON_FORMAT_UNKNOWN" : 0; + } + if (message.fieldPresence != null && message.hasOwnProperty("fieldPresence")) + object.fieldPresence = options.enums === String ? $root.google.protobuf.FeatureSet.FieldPresence[message.fieldPresence] === undefined ? message.fieldPresence : $root.google.protobuf.FeatureSet.FieldPresence[message.fieldPresence] : message.fieldPresence; + if (message.enumType != null && message.hasOwnProperty("enumType")) + object.enumType = options.enums === String ? $root.google.protobuf.FeatureSet.EnumType[message.enumType] === undefined ? message.enumType : $root.google.protobuf.FeatureSet.EnumType[message.enumType] : message.enumType; + if (message.repeatedFieldEncoding != null && message.hasOwnProperty("repeatedFieldEncoding")) + object.repeatedFieldEncoding = options.enums === String ? $root.google.protobuf.FeatureSet.RepeatedFieldEncoding[message.repeatedFieldEncoding] === undefined ? message.repeatedFieldEncoding : $root.google.protobuf.FeatureSet.RepeatedFieldEncoding[message.repeatedFieldEncoding] : message.repeatedFieldEncoding; + if (message.utf8Validation != null && message.hasOwnProperty("utf8Validation")) + object.utf8Validation = options.enums === String ? $root.google.protobuf.FeatureSet.Utf8Validation[message.utf8Validation] === undefined ? message.utf8Validation : $root.google.protobuf.FeatureSet.Utf8Validation[message.utf8Validation] : message.utf8Validation; + if (message.messageEncoding != null && message.hasOwnProperty("messageEncoding")) + object.messageEncoding = options.enums === String ? $root.google.protobuf.FeatureSet.MessageEncoding[message.messageEncoding] === undefined ? message.messageEncoding : $root.google.protobuf.FeatureSet.MessageEncoding[message.messageEncoding] : message.messageEncoding; + if (message.jsonFormat != null && message.hasOwnProperty("jsonFormat")) + object.jsonFormat = options.enums === String ? $root.google.protobuf.FeatureSet.JsonFormat[message.jsonFormat] === undefined ? message.jsonFormat : $root.google.protobuf.FeatureSet.JsonFormat[message.jsonFormat] : message.jsonFormat; + return object; + }; + + /** + * Converts this FeatureSet to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSet + * @instance + * @returns {Object.} JSON object + */ + FeatureSet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FeatureSet + * @function getTypeUrl + * @memberof google.protobuf.FeatureSet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FeatureSet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSet"; + }; + + /** + * FieldPresence enum. + * @name google.protobuf.FeatureSet.FieldPresence + * @enum {string} + * @property {string} FIELD_PRESENCE_UNKNOWN=FIELD_PRESENCE_UNKNOWN FIELD_PRESENCE_UNKNOWN value + * @property {string} EXPLICIT=EXPLICIT EXPLICIT value + * @property {string} IMPLICIT=IMPLICIT IMPLICIT value + * @property {string} LEGACY_REQUIRED=LEGACY_REQUIRED LEGACY_REQUIRED value + */ + FeatureSet.FieldPresence = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "FIELD_PRESENCE_UNKNOWN"] = "FIELD_PRESENCE_UNKNOWN"; + values[valuesById[1] = "EXPLICIT"] = "EXPLICIT"; + values[valuesById[2] = "IMPLICIT"] = "IMPLICIT"; + values[valuesById[3] = "LEGACY_REQUIRED"] = "LEGACY_REQUIRED"; + return values; + })(); + + /** + * EnumType enum. + * @name google.protobuf.FeatureSet.EnumType + * @enum {string} + * @property {string} ENUM_TYPE_UNKNOWN=ENUM_TYPE_UNKNOWN ENUM_TYPE_UNKNOWN value + * @property {string} OPEN=OPEN OPEN value + * @property {string} CLOSED=CLOSED CLOSED value + */ + FeatureSet.EnumType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ENUM_TYPE_UNKNOWN"] = "ENUM_TYPE_UNKNOWN"; + values[valuesById[1] = "OPEN"] = "OPEN"; + values[valuesById[2] = "CLOSED"] = "CLOSED"; + return values; + })(); + + /** + * RepeatedFieldEncoding enum. + * @name google.protobuf.FeatureSet.RepeatedFieldEncoding + * @enum {string} + * @property {string} REPEATED_FIELD_ENCODING_UNKNOWN=REPEATED_FIELD_ENCODING_UNKNOWN REPEATED_FIELD_ENCODING_UNKNOWN value + * @property {string} PACKED=PACKED PACKED value + * @property {string} EXPANDED=EXPANDED EXPANDED value + */ + FeatureSet.RepeatedFieldEncoding = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "REPEATED_FIELD_ENCODING_UNKNOWN"] = "REPEATED_FIELD_ENCODING_UNKNOWN"; + values[valuesById[1] = "PACKED"] = "PACKED"; + values[valuesById[2] = "EXPANDED"] = "EXPANDED"; + return values; + })(); + + /** + * Utf8Validation enum. + * @name google.protobuf.FeatureSet.Utf8Validation + * @enum {string} + * @property {string} UTF8_VALIDATION_UNKNOWN=UTF8_VALIDATION_UNKNOWN UTF8_VALIDATION_UNKNOWN value + * @property {string} VERIFY=VERIFY VERIFY value + * @property {string} NONE=NONE NONE value + */ + FeatureSet.Utf8Validation = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UTF8_VALIDATION_UNKNOWN"] = "UTF8_VALIDATION_UNKNOWN"; + values[valuesById[2] = "VERIFY"] = "VERIFY"; + values[valuesById[3] = "NONE"] = "NONE"; + return values; + })(); + + /** + * MessageEncoding enum. + * @name google.protobuf.FeatureSet.MessageEncoding + * @enum {string} + * @property {string} MESSAGE_ENCODING_UNKNOWN=MESSAGE_ENCODING_UNKNOWN MESSAGE_ENCODING_UNKNOWN value + * @property {string} LENGTH_PREFIXED=LENGTH_PREFIXED LENGTH_PREFIXED value + * @property {string} DELIMITED=DELIMITED DELIMITED value + */ + FeatureSet.MessageEncoding = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "MESSAGE_ENCODING_UNKNOWN"] = "MESSAGE_ENCODING_UNKNOWN"; + values[valuesById[1] = "LENGTH_PREFIXED"] = "LENGTH_PREFIXED"; + values[valuesById[2] = "DELIMITED"] = "DELIMITED"; + return values; + })(); + + /** + * JsonFormat enum. + * @name google.protobuf.FeatureSet.JsonFormat + * @enum {string} + * @property {string} JSON_FORMAT_UNKNOWN=JSON_FORMAT_UNKNOWN JSON_FORMAT_UNKNOWN value + * @property {string} ALLOW=ALLOW ALLOW value + * @property {string} LEGACY_BEST_EFFORT=LEGACY_BEST_EFFORT LEGACY_BEST_EFFORT value + */ + FeatureSet.JsonFormat = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "JSON_FORMAT_UNKNOWN"] = "JSON_FORMAT_UNKNOWN"; + values[valuesById[1] = "ALLOW"] = "ALLOW"; + values[valuesById[2] = "LEGACY_BEST_EFFORT"] = "LEGACY_BEST_EFFORT"; + return values; + })(); + + return FeatureSet; + })(); + + protobuf.FeatureSetDefaults = (function() { + + /** + * Properties of a FeatureSetDefaults. + * @memberof google.protobuf + * @interface IFeatureSetDefaults + * @property {Array.|null} [defaults] FeatureSetDefaults defaults + * @property {google.protobuf.Edition|null} [minimumEdition] FeatureSetDefaults minimumEdition + * @property {google.protobuf.Edition|null} [maximumEdition] FeatureSetDefaults maximumEdition + */ + + /** + * Constructs a new FeatureSetDefaults. + * @memberof google.protobuf + * @classdesc Represents a FeatureSetDefaults. + * @implements IFeatureSetDefaults + * @constructor + * @param {google.protobuf.IFeatureSetDefaults=} [properties] Properties to set + */ + function FeatureSetDefaults(properties) { + this.defaults = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FeatureSetDefaults defaults. + * @member {Array.} defaults + * @memberof google.protobuf.FeatureSetDefaults + * @instance + */ + FeatureSetDefaults.prototype.defaults = $util.emptyArray; + + /** + * FeatureSetDefaults minimumEdition. + * @member {google.protobuf.Edition} minimumEdition + * @memberof google.protobuf.FeatureSetDefaults + * @instance + */ + FeatureSetDefaults.prototype.minimumEdition = 0; + + /** + * FeatureSetDefaults maximumEdition. + * @member {google.protobuf.Edition} maximumEdition + * @memberof google.protobuf.FeatureSetDefaults + * @instance + */ + FeatureSetDefaults.prototype.maximumEdition = 0; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSetDefaults} FeatureSetDefaults + */ + FeatureSetDefaults.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSetDefaults) + return object; + var message = new $root.google.protobuf.FeatureSetDefaults(); + if (object.defaults) { + if (!Array.isArray(object.defaults)) + throw TypeError(".google.protobuf.FeatureSetDefaults.defaults: array expected"); + message.defaults = []; + for (var i = 0; i < object.defaults.length; ++i) { + if (typeof object.defaults[i] !== "object") + throw TypeError(".google.protobuf.FeatureSetDefaults.defaults: object expected"); + message.defaults[i] = $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.fromObject(object.defaults[i]); + } + } + switch (object.minimumEdition) { + default: + if (typeof object.minimumEdition === "number") { + message.minimumEdition = object.minimumEdition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.minimumEdition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.minimumEdition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.minimumEdition = 999; + break; + case "EDITION_2023": + case 1000: + message.minimumEdition = 1000; + break; + case "EDITION_2024": + case 1001: + message.minimumEdition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.minimumEdition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.minimumEdition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.minimumEdition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.minimumEdition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.minimumEdition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.minimumEdition = 2147483647; + break; + } + switch (object.maximumEdition) { + default: + if (typeof object.maximumEdition === "number") { + message.maximumEdition = object.maximumEdition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.maximumEdition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.maximumEdition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.maximumEdition = 999; + break; + case "EDITION_2023": + case 1000: + message.maximumEdition = 1000; + break; + case "EDITION_2024": + case 1001: + message.maximumEdition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.maximumEdition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.maximumEdition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.maximumEdition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.maximumEdition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.maximumEdition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.maximumEdition = 2147483647; + break; + } + return message; + }; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {google.protobuf.FeatureSetDefaults} message FeatureSetDefaults + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FeatureSetDefaults.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.defaults = []; + if (options.defaults) { + object.minimumEdition = options.enums === String ? "EDITION_UNKNOWN" : 0; + object.maximumEdition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.defaults && message.defaults.length) { + object.defaults = []; + for (var j = 0; j < message.defaults.length; ++j) + object.defaults[j] = $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.toObject(message.defaults[j], options); + } + if (message.minimumEdition != null && message.hasOwnProperty("minimumEdition")) + object.minimumEdition = options.enums === String ? $root.google.protobuf.Edition[message.minimumEdition] === undefined ? message.minimumEdition : $root.google.protobuf.Edition[message.minimumEdition] : message.minimumEdition; + if (message.maximumEdition != null && message.hasOwnProperty("maximumEdition")) + object.maximumEdition = options.enums === String ? $root.google.protobuf.Edition[message.maximumEdition] === undefined ? message.maximumEdition : $root.google.protobuf.Edition[message.maximumEdition] : message.maximumEdition; + return object; + }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSetDefaults + * @instance + * @returns {Object.} JSON object + */ + FeatureSetDefaults.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FeatureSetDefaults + * @function getTypeUrl + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FeatureSetDefaults.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSetDefaults"; + }; + + FeatureSetDefaults.FeatureSetEditionDefault = (function() { + + /** + * Properties of a FeatureSetEditionDefault. + * @memberof google.protobuf.FeatureSetDefaults + * @interface IFeatureSetEditionDefault + * @property {google.protobuf.Edition|null} [edition] FeatureSetEditionDefault edition + * @property {google.protobuf.IFeatureSet|null} [features] FeatureSetEditionDefault features + */ + + /** + * Constructs a new FeatureSetEditionDefault. + * @memberof google.protobuf.FeatureSetDefaults + * @classdesc Represents a FeatureSetEditionDefault. + * @implements IFeatureSetEditionDefault + * @constructor + * @param {google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault=} [properties] Properties to set + */ + function FeatureSetEditionDefault(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FeatureSetEditionDefault edition. + * @member {google.protobuf.Edition} edition + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @instance + */ + FeatureSetEditionDefault.prototype.edition = 0; + + /** + * FeatureSetEditionDefault features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @instance + */ + FeatureSetEditionDefault.prototype.features = null; + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault} FeatureSetEditionDefault + */ + FeatureSetEditionDefault.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault) + return object; + var message = new $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault(); + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.edition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.edition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.edition = 999; + break; + case "EDITION_2023": + case 1000: + message.edition = 1000; + break; + case "EDITION_2024": + case 1001: + message.edition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.edition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.edition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.edition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.edition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.edition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.edition = 2147483647; + break; + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + return message; + }; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault} message FeatureSetEditionDefault + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FeatureSetEditionDefault.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.features = null; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; + return object; + }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @instance + * @returns {Object.} JSON object + */ + FeatureSetEditionDefault.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @function getTypeUrl + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FeatureSetEditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault"; + }; + + return FeatureSetEditionDefault; + })(); + + return FeatureSetDefaults; + })(); + + protobuf.SourceCodeInfo = (function() { + + /** + * Properties of a SourceCodeInfo. + * @memberof google.protobuf + * @interface ISourceCodeInfo + * @property {Array.|null} [location] SourceCodeInfo location + */ + + /** + * Constructs a new SourceCodeInfo. + * @memberof google.protobuf + * @classdesc Represents a SourceCodeInfo. + * @implements ISourceCodeInfo + * @constructor + * @param {google.protobuf.ISourceCodeInfo=} [properties] Properties to set + */ + function SourceCodeInfo(properties) { + this.location = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SourceCodeInfo location. + * @member {Array.} location + * @memberof google.protobuf.SourceCodeInfo + * @instance + */ + SourceCodeInfo.prototype.location = $util.emptyArray; + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.SourceCodeInfo} SourceCodeInfo + */ + SourceCodeInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.SourceCodeInfo) + return object; + var message = new $root.google.protobuf.SourceCodeInfo(); + if (object.location) { + if (!Array.isArray(object.location)) + throw TypeError(".google.protobuf.SourceCodeInfo.location: array expected"); + message.location = []; + for (var i = 0; i < object.location.length; ++i) { + if (typeof object.location[i] !== "object") + throw TypeError(".google.protobuf.SourceCodeInfo.location: object expected"); + message.location[i] = $root.google.protobuf.SourceCodeInfo.Location.fromObject(object.location[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {google.protobuf.SourceCodeInfo} message SourceCodeInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SourceCodeInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.location = []; + if (message.location && message.location.length) { + object.location = []; + for (var j = 0; j < message.location.length; ++j) + object.location[j] = $root.google.protobuf.SourceCodeInfo.Location.toObject(message.location[j], options); + } + return object; + }; + + /** + * Converts this SourceCodeInfo to JSON. + * @function toJSON + * @memberof google.protobuf.SourceCodeInfo + * @instance + * @returns {Object.} JSON object + */ + SourceCodeInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SourceCodeInfo + * @function getTypeUrl + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SourceCodeInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.SourceCodeInfo"; + }; + + SourceCodeInfo.Location = (function() { + + /** + * Properties of a Location. + * @memberof google.protobuf.SourceCodeInfo + * @interface ILocation + * @property {Array.|null} [path] Location path + * @property {Array.|null} [span] Location span + * @property {string|null} [leadingComments] Location leadingComments + * @property {string|null} [trailingComments] Location trailingComments + * @property {Array.|null} [leadingDetachedComments] Location leadingDetachedComments + */ + + /** + * Constructs a new Location. + * @memberof google.protobuf.SourceCodeInfo + * @classdesc Represents a Location. + * @implements ILocation + * @constructor + * @param {google.protobuf.SourceCodeInfo.ILocation=} [properties] Properties to set + */ + function Location(properties) { + this.path = []; + this.span = []; + this.leadingDetachedComments = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Location path. + * @member {Array.} path + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.path = $util.emptyArray; + + /** + * Location span. + * @member {Array.} span + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.span = $util.emptyArray; + + /** + * Location leadingComments. + * @member {string} leadingComments + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.leadingComments = ""; + + /** + * Location trailingComments. + * @member {string} trailingComments + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.trailingComments = ""; + + /** + * Location leadingDetachedComments. + * @member {Array.} leadingDetachedComments + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.leadingDetachedComments = $util.emptyArray; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.SourceCodeInfo.Location} Location + */ + Location.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.SourceCodeInfo.Location) + return object; + var message = new $root.google.protobuf.SourceCodeInfo.Location(); + if (object.path) { + if (!Array.isArray(object.path)) + throw TypeError(".google.protobuf.SourceCodeInfo.Location.path: array expected"); + message.path = []; + for (var i = 0; i < object.path.length; ++i) + message.path[i] = object.path[i] | 0; + } + if (object.span) { + if (!Array.isArray(object.span)) + throw TypeError(".google.protobuf.SourceCodeInfo.Location.span: array expected"); + message.span = []; + for (var i = 0; i < object.span.length; ++i) + message.span[i] = object.span[i] | 0; + } + if (object.leadingComments != null) + message.leadingComments = String(object.leadingComments); + if (object.trailingComments != null) + message.trailingComments = String(object.trailingComments); + if (object.leadingDetachedComments) { + if (!Array.isArray(object.leadingDetachedComments)) + throw TypeError(".google.protobuf.SourceCodeInfo.Location.leadingDetachedComments: array expected"); + message.leadingDetachedComments = []; + for (var i = 0; i < object.leadingDetachedComments.length; ++i) + message.leadingDetachedComments[i] = String(object.leadingDetachedComments[i]); + } + return message; + }; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {google.protobuf.SourceCodeInfo.Location} message Location + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Location.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.path = []; + object.span = []; + object.leadingDetachedComments = []; + } + if (options.defaults) { + object.leadingComments = ""; + object.trailingComments = ""; + } + if (message.path && message.path.length) { + object.path = []; + for (var j = 0; j < message.path.length; ++j) + object.path[j] = message.path[j]; + } + if (message.span && message.span.length) { + object.span = []; + for (var j = 0; j < message.span.length; ++j) + object.span[j] = message.span[j]; + } + if (message.leadingComments != null && message.hasOwnProperty("leadingComments")) + object.leadingComments = message.leadingComments; + if (message.trailingComments != null && message.hasOwnProperty("trailingComments")) + object.trailingComments = message.trailingComments; + if (message.leadingDetachedComments && message.leadingDetachedComments.length) { + object.leadingDetachedComments = []; + for (var j = 0; j < message.leadingDetachedComments.length; ++j) + object.leadingDetachedComments[j] = message.leadingDetachedComments[j]; + } + return object; + }; + + /** + * Converts this Location to JSON. + * @function toJSON + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + * @returns {Object.} JSON object + */ + Location.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Location + * @function getTypeUrl + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Location.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.SourceCodeInfo.Location"; + }; + + return Location; + })(); + + return SourceCodeInfo; + })(); + + protobuf.GeneratedCodeInfo = (function() { + + /** + * Properties of a GeneratedCodeInfo. + * @memberof google.protobuf + * @interface IGeneratedCodeInfo + * @property {Array.|null} [annotation] GeneratedCodeInfo annotation + */ + + /** + * Constructs a new GeneratedCodeInfo. + * @memberof google.protobuf + * @classdesc Represents a GeneratedCodeInfo. + * @implements IGeneratedCodeInfo + * @constructor + * @param {google.protobuf.IGeneratedCodeInfo=} [properties] Properties to set + */ + function GeneratedCodeInfo(properties) { + this.annotation = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GeneratedCodeInfo annotation. + * @member {Array.} annotation + * @memberof google.protobuf.GeneratedCodeInfo + * @instance + */ + GeneratedCodeInfo.prototype.annotation = $util.emptyArray; + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.GeneratedCodeInfo} GeneratedCodeInfo + */ + GeneratedCodeInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.GeneratedCodeInfo) + return object; + var message = new $root.google.protobuf.GeneratedCodeInfo(); + if (object.annotation) { + if (!Array.isArray(object.annotation)) + throw TypeError(".google.protobuf.GeneratedCodeInfo.annotation: array expected"); + message.annotation = []; + for (var i = 0; i < object.annotation.length; ++i) { + if (typeof object.annotation[i] !== "object") + throw TypeError(".google.protobuf.GeneratedCodeInfo.annotation: object expected"); + message.annotation[i] = $root.google.protobuf.GeneratedCodeInfo.Annotation.fromObject(object.annotation[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {google.protobuf.GeneratedCodeInfo} message GeneratedCodeInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GeneratedCodeInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.annotation = []; + if (message.annotation && message.annotation.length) { + object.annotation = []; + for (var j = 0; j < message.annotation.length; ++j) + object.annotation[j] = $root.google.protobuf.GeneratedCodeInfo.Annotation.toObject(message.annotation[j], options); + } + return object; + }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @function toJSON + * @memberof google.protobuf.GeneratedCodeInfo + * @instance + * @returns {Object.} JSON object + */ + GeneratedCodeInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @function getTypeUrl + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GeneratedCodeInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.GeneratedCodeInfo"; + }; + + GeneratedCodeInfo.Annotation = (function() { + + /** + * Properties of an Annotation. + * @memberof google.protobuf.GeneratedCodeInfo + * @interface IAnnotation + * @property {Array.|null} [path] Annotation path + * @property {string|null} [sourceFile] Annotation sourceFile + * @property {number|null} [begin] Annotation begin + * @property {number|null} [end] Annotation end + * @property {google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null} [semantic] Annotation semantic + */ + + /** + * Constructs a new Annotation. + * @memberof google.protobuf.GeneratedCodeInfo + * @classdesc Represents an Annotation. + * @implements IAnnotation + * @constructor + * @param {google.protobuf.GeneratedCodeInfo.IAnnotation=} [properties] Properties to set + */ + function Annotation(properties) { + this.path = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Annotation path. + * @member {Array.} path + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.path = $util.emptyArray; + + /** + * Annotation sourceFile. + * @member {string} sourceFile + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.sourceFile = ""; + + /** + * Annotation begin. + * @member {number} begin + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.begin = 0; + + /** + * Annotation end. + * @member {number} end + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.end = 0; + + /** + * Annotation semantic. + * @member {google.protobuf.GeneratedCodeInfo.Annotation.Semantic} semantic + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.semantic = 0; + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.GeneratedCodeInfo.Annotation} Annotation + */ + Annotation.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.GeneratedCodeInfo.Annotation) + return object; + var message = new $root.google.protobuf.GeneratedCodeInfo.Annotation(); + if (object.path) { + if (!Array.isArray(object.path)) + throw TypeError(".google.protobuf.GeneratedCodeInfo.Annotation.path: array expected"); + message.path = []; + for (var i = 0; i < object.path.length; ++i) + message.path[i] = object.path[i] | 0; + } + if (object.sourceFile != null) + message.sourceFile = String(object.sourceFile); + if (object.begin != null) + message.begin = object.begin | 0; + if (object.end != null) + message.end = object.end | 0; + switch (object.semantic) { + default: + if (typeof object.semantic === "number") { + message.semantic = object.semantic; + break; + } + break; + case "NONE": + case 0: + message.semantic = 0; + break; + case "SET": + case 1: + message.semantic = 1; + break; + case "ALIAS": + case 2: + message.semantic = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {google.protobuf.GeneratedCodeInfo.Annotation} message Annotation + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Annotation.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.path = []; + if (options.defaults) { + object.sourceFile = ""; + object.begin = 0; + object.end = 0; + object.semantic = options.enums === String ? "NONE" : 0; + } + if (message.path && message.path.length) { + object.path = []; + for (var j = 0; j < message.path.length; ++j) + object.path[j] = message.path[j]; + } + if (message.sourceFile != null && message.hasOwnProperty("sourceFile")) + object.sourceFile = message.sourceFile; + if (message.begin != null && message.hasOwnProperty("begin")) + object.begin = message.begin; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + if (message.semantic != null && message.hasOwnProperty("semantic")) + object.semantic = options.enums === String ? $root.google.protobuf.GeneratedCodeInfo.Annotation.Semantic[message.semantic] === undefined ? message.semantic : $root.google.protobuf.GeneratedCodeInfo.Annotation.Semantic[message.semantic] : message.semantic; + return object; + }; + + /** + * Converts this Annotation to JSON. + * @function toJSON + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + * @returns {Object.} JSON object + */ + Annotation.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Annotation + * @function getTypeUrl + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Annotation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.GeneratedCodeInfo.Annotation"; + }; + + /** + * Semantic enum. + * @name google.protobuf.GeneratedCodeInfo.Annotation.Semantic + * @enum {string} + * @property {string} NONE=NONE NONE value + * @property {string} SET=SET SET value + * @property {string} ALIAS=ALIAS ALIAS value + */ + Annotation.Semantic = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "NONE"] = "NONE"; + values[valuesById[1] = "SET"] = "SET"; + values[valuesById[2] = "ALIAS"] = "ALIAS"; + return values; + })(); + + return Annotation; + })(); + + return GeneratedCodeInfo; + })(); + + protobuf.Duration = (function() { + + /** + * Properties of a Duration. + * @memberof google.protobuf + * @interface IDuration + * @property {number|string|null} [seconds] Duration seconds + * @property {number|null} [nanos] Duration nanos + */ + + /** + * Constructs a new Duration. + * @memberof google.protobuf + * @classdesc Represents a Duration. + * @implements IDuration + * @constructor + * @param {google.protobuf.IDuration=} [properties] Properties to set + */ + function Duration(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Duration seconds. + * @member {number|string} seconds + * @memberof google.protobuf.Duration + * @instance + */ + Duration.prototype.seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Duration nanos. + * @member {number} nanos + * @memberof google.protobuf.Duration + * @instance + */ + Duration.prototype.nanos = 0; + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Duration + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Duration} Duration + */ + Duration.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Duration) + return object; + var message = new $root.google.protobuf.Duration(); + if (object.seconds != null) + if ($util.Long) + (message.seconds = $util.Long.fromValue(object.seconds)).unsigned = false; + else if (typeof object.seconds === "string") + message.seconds = parseInt(object.seconds, 10); + else if (typeof object.seconds === "number") + message.seconds = object.seconds; + else if (typeof object.seconds === "object") + message.seconds = new $util.LongBits(object.seconds.low >>> 0, object.seconds.high >>> 0).toNumber(); + if (object.nanos != null) + message.nanos = object.nanos | 0; + return message; + }; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Duration + * @static + * @param {google.protobuf.Duration} message Duration + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Duration.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.seconds = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.seconds = options.longs === String ? "0" : 0; + object.nanos = 0; + } + if (message.seconds != null && message.hasOwnProperty("seconds")) + if (typeof message.seconds === "number") + object.seconds = options.longs === String ? String(message.seconds) : message.seconds; + else + object.seconds = options.longs === String ? $util.Long.prototype.toString.call(message.seconds) : options.longs === Number ? new $util.LongBits(message.seconds.low >>> 0, message.seconds.high >>> 0).toNumber() : message.seconds; + if (message.nanos != null && message.hasOwnProperty("nanos")) + object.nanos = message.nanos; + return object; + }; + + /** + * Converts this Duration to JSON. + * @function toJSON + * @memberof google.protobuf.Duration + * @instance + * @returns {Object.} JSON object + */ + Duration.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Duration + * @function getTypeUrl + * @memberof google.protobuf.Duration + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Duration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Duration"; + }; + + return Duration; + })(); + + protobuf.DoubleValue = (function() { + + /** + * Properties of a DoubleValue. + * @memberof google.protobuf + * @interface IDoubleValue + * @property {number|null} [value] DoubleValue value + */ + + /** + * Constructs a new DoubleValue. + * @memberof google.protobuf + * @classdesc Represents a DoubleValue. + * @implements IDoubleValue + * @constructor + * @param {google.protobuf.IDoubleValue=} [properties] Properties to set + */ + function DoubleValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DoubleValue value. + * @member {number} value + * @memberof google.protobuf.DoubleValue + * @instance + */ + DoubleValue.prototype.value = 0; + + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DoubleValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DoubleValue} DoubleValue + */ + DoubleValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DoubleValue) + return object; + var message = new $root.google.protobuf.DoubleValue(); + if (object.value != null) + message.value = Number(object.value); + return message; + }; + + /** + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.DoubleValue + * @static + * @param {google.protobuf.DoubleValue} message DoubleValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DoubleValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = 0; + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value; + return object; + }; + + /** + * Converts this DoubleValue to JSON. + * @function toJSON + * @memberof google.protobuf.DoubleValue + * @instance + * @returns {Object.} JSON object + */ + DoubleValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DoubleValue + * @function getTypeUrl + * @memberof google.protobuf.DoubleValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DoubleValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.DoubleValue"; + }; + + return DoubleValue; + })(); + + protobuf.FloatValue = (function() { + + /** + * Properties of a FloatValue. + * @memberof google.protobuf + * @interface IFloatValue + * @property {number|null} [value] FloatValue value + */ + + /** + * Constructs a new FloatValue. + * @memberof google.protobuf + * @classdesc Represents a FloatValue. + * @implements IFloatValue + * @constructor + * @param {google.protobuf.IFloatValue=} [properties] Properties to set + */ + function FloatValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FloatValue value. + * @member {number} value + * @memberof google.protobuf.FloatValue + * @instance + */ + FloatValue.prototype.value = 0; + + /** + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FloatValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FloatValue} FloatValue + */ + FloatValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FloatValue) + return object; + var message = new $root.google.protobuf.FloatValue(); + if (object.value != null) + message.value = Number(object.value); + return message; + }; + + /** + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FloatValue + * @static + * @param {google.protobuf.FloatValue} message FloatValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FloatValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = 0; + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value; + return object; + }; + + /** + * Converts this FloatValue to JSON. + * @function toJSON + * @memberof google.protobuf.FloatValue + * @instance + * @returns {Object.} JSON object + */ + FloatValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FloatValue + * @function getTypeUrl + * @memberof google.protobuf.FloatValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FloatValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FloatValue"; + }; + + return FloatValue; + })(); + + protobuf.Int64Value = (function() { + + /** + * Properties of an Int64Value. + * @memberof google.protobuf + * @interface IInt64Value + * @property {number|string|null} [value] Int64Value value + */ + + /** + * Constructs a new Int64Value. + * @memberof google.protobuf + * @classdesc Represents an Int64Value. + * @implements IInt64Value + * @constructor + * @param {google.protobuf.IInt64Value=} [properties] Properties to set + */ + function Int64Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Int64Value value. + * @member {number|string} value + * @memberof google.protobuf.Int64Value + * @instance + */ + Int64Value.prototype.value = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Int64Value + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Int64Value} Int64Value + */ + Int64Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Int64Value) + return object; + var message = new $root.google.protobuf.Int64Value(); + if (object.value != null) + if ($util.Long) + (message.value = $util.Long.fromValue(object.value)).unsigned = false; + else if (typeof object.value === "string") + message.value = parseInt(object.value, 10); + else if (typeof object.value === "number") + message.value = object.value; + else if (typeof object.value === "object") + message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Int64Value + * @static + * @param {google.protobuf.Int64Value} message Int64Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Int64Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.value = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.value = options.longs === String ? "0" : 0; + if (message.value != null && message.hasOwnProperty("value")) + if (typeof message.value === "number") + object.value = options.longs === String ? String(message.value) : message.value; + else + object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber() : message.value; + return object; + }; + + /** + * Converts this Int64Value to JSON. + * @function toJSON + * @memberof google.protobuf.Int64Value + * @instance + * @returns {Object.} JSON object + */ + Int64Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Int64Value + * @function getTypeUrl + * @memberof google.protobuf.Int64Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Int64Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Int64Value"; + }; + + return Int64Value; + })(); + + protobuf.UInt64Value = (function() { + + /** + * Properties of a UInt64Value. + * @memberof google.protobuf + * @interface IUInt64Value + * @property {number|string|null} [value] UInt64Value value + */ + + /** + * Constructs a new UInt64Value. + * @memberof google.protobuf + * @classdesc Represents a UInt64Value. + * @implements IUInt64Value + * @constructor + * @param {google.protobuf.IUInt64Value=} [properties] Properties to set + */ + function UInt64Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UInt64Value value. + * @member {number|string} value + * @memberof google.protobuf.UInt64Value + * @instance + */ + UInt64Value.prototype.value = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.UInt64Value + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.UInt64Value} UInt64Value + */ + UInt64Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UInt64Value) + return object; + var message = new $root.google.protobuf.UInt64Value(); + if (object.value != null) + if ($util.Long) + (message.value = $util.Long.fromValue(object.value)).unsigned = true; + else if (typeof object.value === "string") + message.value = parseInt(object.value, 10); + else if (typeof object.value === "number") + message.value = object.value; + else if (typeof object.value === "object") + message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(true); + return message; + }; + + /** + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.UInt64Value + * @static + * @param {google.protobuf.UInt64Value} message UInt64Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UInt64Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.value = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.value = options.longs === String ? "0" : 0; + if (message.value != null && message.hasOwnProperty("value")) + if (typeof message.value === "number") + object.value = options.longs === String ? String(message.value) : message.value; + else + object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber(true) : message.value; + return object; + }; + + /** + * Converts this UInt64Value to JSON. + * @function toJSON + * @memberof google.protobuf.UInt64Value + * @instance + * @returns {Object.} JSON object + */ + UInt64Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UInt64Value + * @function getTypeUrl + * @memberof google.protobuf.UInt64Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UInt64Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.UInt64Value"; + }; + + return UInt64Value; + })(); + + protobuf.Int32Value = (function() { + + /** + * Properties of an Int32Value. + * @memberof google.protobuf + * @interface IInt32Value + * @property {number|null} [value] Int32Value value + */ + + /** + * Constructs a new Int32Value. + * @memberof google.protobuf + * @classdesc Represents an Int32Value. + * @implements IInt32Value + * @constructor + * @param {google.protobuf.IInt32Value=} [properties] Properties to set + */ + function Int32Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Int32Value value. + * @member {number} value + * @memberof google.protobuf.Int32Value + * @instance + */ + Int32Value.prototype.value = 0; + + /** + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Int32Value + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Int32Value} Int32Value + */ + Int32Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Int32Value) + return object; + var message = new $root.google.protobuf.Int32Value(); + if (object.value != null) + message.value = object.value | 0; + return message; + }; + + /** + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Int32Value + * @static + * @param {google.protobuf.Int32Value} message Int32Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Int32Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = 0; + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + return object; + }; + + /** + * Converts this Int32Value to JSON. + * @function toJSON + * @memberof google.protobuf.Int32Value + * @instance + * @returns {Object.} JSON object + */ + Int32Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Int32Value + * @function getTypeUrl + * @memberof google.protobuf.Int32Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Int32Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Int32Value"; + }; + + return Int32Value; + })(); + + protobuf.UInt32Value = (function() { + + /** + * Properties of a UInt32Value. + * @memberof google.protobuf + * @interface IUInt32Value + * @property {number|null} [value] UInt32Value value + */ + + /** + * Constructs a new UInt32Value. + * @memberof google.protobuf + * @classdesc Represents a UInt32Value. + * @implements IUInt32Value + * @constructor + * @param {google.protobuf.IUInt32Value=} [properties] Properties to set + */ + function UInt32Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UInt32Value value. + * @member {number} value + * @memberof google.protobuf.UInt32Value + * @instance + */ + UInt32Value.prototype.value = 0; + + /** + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.UInt32Value + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.UInt32Value} UInt32Value + */ + UInt32Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UInt32Value) + return object; + var message = new $root.google.protobuf.UInt32Value(); + if (object.value != null) + message.value = object.value >>> 0; + return message; + }; + + /** + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.UInt32Value + * @static + * @param {google.protobuf.UInt32Value} message UInt32Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UInt32Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = 0; + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + return object; + }; + + /** + * Converts this UInt32Value to JSON. + * @function toJSON + * @memberof google.protobuf.UInt32Value + * @instance + * @returns {Object.} JSON object + */ + UInt32Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UInt32Value + * @function getTypeUrl + * @memberof google.protobuf.UInt32Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UInt32Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.UInt32Value"; + }; + + return UInt32Value; + })(); + + protobuf.BoolValue = (function() { + + /** + * Properties of a BoolValue. + * @memberof google.protobuf + * @interface IBoolValue + * @property {boolean|null} [value] BoolValue value + */ + + /** + * Constructs a new BoolValue. + * @memberof google.protobuf + * @classdesc Represents a BoolValue. + * @implements IBoolValue + * @constructor + * @param {google.protobuf.IBoolValue=} [properties] Properties to set + */ + function BoolValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BoolValue value. + * @member {boolean} value + * @memberof google.protobuf.BoolValue + * @instance + */ + BoolValue.prototype.value = false; + + /** + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.BoolValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.BoolValue} BoolValue + */ + BoolValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.BoolValue) + return object; + var message = new $root.google.protobuf.BoolValue(); + if (object.value != null) + message.value = Boolean(object.value); + return message; + }; + + /** + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.BoolValue + * @static + * @param {google.protobuf.BoolValue} message BoolValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BoolValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = false; + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + return object; + }; + + /** + * Converts this BoolValue to JSON. + * @function toJSON + * @memberof google.protobuf.BoolValue + * @instance + * @returns {Object.} JSON object + */ + BoolValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BoolValue + * @function getTypeUrl + * @memberof google.protobuf.BoolValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BoolValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.BoolValue"; + }; + + return BoolValue; + })(); + + protobuf.StringValue = (function() { + + /** + * Properties of a StringValue. + * @memberof google.protobuf + * @interface IStringValue + * @property {string|null} [value] StringValue value + */ + + /** + * Constructs a new StringValue. + * @memberof google.protobuf + * @classdesc Represents a StringValue. + * @implements IStringValue + * @constructor + * @param {google.protobuf.IStringValue=} [properties] Properties to set + */ + function StringValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * StringValue value. + * @member {string} value + * @memberof google.protobuf.StringValue + * @instance + */ + StringValue.prototype.value = ""; + + /** + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.StringValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.StringValue} StringValue + */ + StringValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.StringValue) + return object; + var message = new $root.google.protobuf.StringValue(); + if (object.value != null) + message.value = String(object.value); + return message; + }; + + /** + * Creates a plain object from a StringValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.StringValue + * @static + * @param {google.protobuf.StringValue} message StringValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + StringValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.value = ""; + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + return object; + }; + + /** + * Converts this StringValue to JSON. + * @function toJSON + * @memberof google.protobuf.StringValue + * @instance + * @returns {Object.} JSON object + */ + StringValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for StringValue + * @function getTypeUrl + * @memberof google.protobuf.StringValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + StringValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.StringValue"; + }; + + return StringValue; + })(); + + protobuf.BytesValue = (function() { + + /** + * Properties of a BytesValue. + * @memberof google.protobuf + * @interface IBytesValue + * @property {Uint8Array|null} [value] BytesValue value + */ + + /** + * Constructs a new BytesValue. + * @memberof google.protobuf + * @classdesc Represents a BytesValue. + * @implements IBytesValue + * @constructor + * @param {google.protobuf.IBytesValue=} [properties] Properties to set + */ + function BytesValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BytesValue value. + * @member {Uint8Array} value + * @memberof google.protobuf.BytesValue + * @instance + */ + BytesValue.prototype.value = $util.newBuffer([]); + + /** + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.BytesValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.BytesValue} BytesValue + */ + BytesValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.BytesValue) + return object; + var message = new $root.google.protobuf.BytesValue(); + if (object.value != null) + if (typeof object.value === "string") + $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0); + else if (object.value.length >= 0) + message.value = object.value; + return message; + }; + + /** + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.BytesValue + * @static + * @param {google.protobuf.BytesValue} message BytesValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BytesValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if (options.bytes === String) + object.value = ""; + else { + object.value = []; + if (options.bytes !== Array) + object.value = $util.newBuffer(object.value); + } + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; + return object; + }; + + /** + * Converts this BytesValue to JSON. + * @function toJSON + * @memberof google.protobuf.BytesValue + * @instance + * @returns {Object.} JSON object + */ + BytesValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BytesValue + * @function getTypeUrl + * @memberof google.protobuf.BytesValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BytesValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.BytesValue"; + }; + + return BytesValue; + })(); + + protobuf.Empty = (function() { + + /** + * Properties of an Empty. + * @memberof google.protobuf + * @interface IEmpty + */ + + /** + * Constructs a new Empty. + * @memberof google.protobuf + * @classdesc Represents an Empty. + * @implements IEmpty + * @constructor + * @param {google.protobuf.IEmpty=} [properties] Properties to set + */ + function Empty(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Empty + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Empty} Empty + */ + Empty.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Empty) + return object; + return new $root.google.protobuf.Empty(); + }; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Empty + * @static + * @param {google.protobuf.Empty} message Empty + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Empty.toObject = function toObject() { + return {}; + }; + + /** + * Converts this Empty to JSON. + * @function toJSON + * @memberof google.protobuf.Empty + * @instance + * @returns {Object.} JSON object + */ + Empty.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Empty + * @function getTypeUrl + * @memberof google.protobuf.Empty + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Empty.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Empty"; + }; + + return Empty; + })(); + + protobuf.Any = (function() { + + /** + * Properties of an Any. + * @memberof google.protobuf + * @interface IAny + * @property {string|null} [type_url] Any type_url + * @property {Uint8Array|null} [value] Any value + */ + + /** + * Constructs a new Any. + * @memberof google.protobuf + * @classdesc Represents an Any. + * @implements IAny + * @constructor + * @param {google.protobuf.IAny=} [properties] Properties to set + */ + function Any(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Any type_url. + * @member {string} type_url + * @memberof google.protobuf.Any + * @instance + */ + Any.prototype.type_url = ""; + + /** + * Any value. + * @member {Uint8Array} value + * @memberof google.protobuf.Any + * @instance + */ + Any.prototype.value = $util.newBuffer([]); + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Any + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Any} Any + */ + Any.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Any) + return object; + var message = new $root.google.protobuf.Any(); + if (object.type_url != null) + message.type_url = String(object.type_url); + if (object.value != null) + if (typeof object.value === "string") + $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0); + else if (object.value.length >= 0) + message.value = object.value; + return message; + }; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Any + * @static + * @param {google.protobuf.Any} message Any + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Any.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.type_url = ""; + if (options.bytes === String) + object.value = ""; + else { + object.value = []; + if (options.bytes !== Array) + object.value = $util.newBuffer(object.value); + } + } + if (message.type_url != null && message.hasOwnProperty("type_url")) + object.type_url = message.type_url; + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; + return object; + }; + + /** + * Converts this Any to JSON. + * @function toJSON + * @memberof google.protobuf.Any + * @instance + * @returns {Object.} JSON object + */ + Any.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Any + * @function getTypeUrl + * @memberof google.protobuf.Any + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Any.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Any"; + }; + + return Any; + })(); + + protobuf.FieldMask = (function() { + + /** + * Properties of a FieldMask. + * @memberof google.protobuf + * @interface IFieldMask + * @property {Array.|null} [paths] FieldMask paths + */ + + /** + * Constructs a new FieldMask. + * @memberof google.protobuf + * @classdesc Represents a FieldMask. + * @implements IFieldMask + * @constructor + * @param {google.protobuf.IFieldMask=} [properties] Properties to set + */ + function FieldMask(properties) { + this.paths = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldMask paths. + * @member {Array.} paths + * @memberof google.protobuf.FieldMask + * @instance + */ + FieldMask.prototype.paths = $util.emptyArray; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldMask + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldMask} FieldMask + */ + FieldMask.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldMask) + return object; + var message = new $root.google.protobuf.FieldMask(); + if (object.paths) { + if (!Array.isArray(object.paths)) + throw TypeError(".google.protobuf.FieldMask.paths: array expected"); + message.paths = []; + for (var i = 0; i < object.paths.length; ++i) + message.paths[i] = String(object.paths[i]); + } + return message; + }; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldMask + * @static + * @param {google.protobuf.FieldMask} message FieldMask + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldMask.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.paths = []; + if (message.paths && message.paths.length) { + object.paths = []; + for (var j = 0; j < message.paths.length; ++j) + object.paths[j] = message.paths[j]; + } + return object; + }; + + /** + * Converts this FieldMask to JSON. + * @function toJSON + * @memberof google.protobuf.FieldMask + * @instance + * @returns {Object.} JSON object + */ + FieldMask.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldMask + * @function getTypeUrl + * @memberof google.protobuf.FieldMask + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldMask.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldMask"; + }; + + return FieldMask; + })(); + + return protobuf; + })(); + + google.firestore = (function() { + + /** + * Namespace firestore. + * @memberof google + * @namespace + */ + var firestore = {}; + + firestore.v1beta1 = (function() { + + /** + * Namespace v1beta1. + * @memberof google.firestore + * @namespace + */ + var v1beta1 = {}; + + v1beta1.DocumentMask = (function() { + + /** + * Properties of a DocumentMask. + * @memberof google.firestore.v1beta1 + * @interface IDocumentMask + * @property {Array.|null} [fieldPaths] DocumentMask fieldPaths + */ + + /** + * Constructs a new DocumentMask. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a DocumentMask. + * @implements IDocumentMask + * @constructor + * @param {google.firestore.v1beta1.IDocumentMask=} [properties] Properties to set + */ + function DocumentMask(properties) { + this.fieldPaths = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DocumentMask fieldPaths. + * @member {Array.} fieldPaths + * @memberof google.firestore.v1beta1.DocumentMask + * @instance + */ + DocumentMask.prototype.fieldPaths = $util.emptyArray; + + /** + * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.DocumentMask + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.DocumentMask} DocumentMask + */ + DocumentMask.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.DocumentMask) + return object; + var message = new $root.google.firestore.v1beta1.DocumentMask(); + if (object.fieldPaths) { + if (!Array.isArray(object.fieldPaths)) + throw TypeError(".google.firestore.v1beta1.DocumentMask.fieldPaths: array expected"); + message.fieldPaths = []; + for (var i = 0; i < object.fieldPaths.length; ++i) + message.fieldPaths[i] = String(object.fieldPaths[i]); + } + return message; + }; + + /** + * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.DocumentMask + * @static + * @param {google.firestore.v1beta1.DocumentMask} message DocumentMask + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DocumentMask.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.fieldPaths = []; + if (message.fieldPaths && message.fieldPaths.length) { + object.fieldPaths = []; + for (var j = 0; j < message.fieldPaths.length; ++j) + object.fieldPaths[j] = message.fieldPaths[j]; + } + return object; + }; + + /** + * Converts this DocumentMask to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.DocumentMask + * @instance + * @returns {Object.} JSON object + */ + DocumentMask.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DocumentMask + * @function getTypeUrl + * @memberof google.firestore.v1beta1.DocumentMask + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DocumentMask.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.DocumentMask"; + }; + + return DocumentMask; + })(); + + v1beta1.Precondition = (function() { + + /** + * Properties of a Precondition. + * @memberof google.firestore.v1beta1 + * @interface IPrecondition + * @property {boolean|null} [exists] Precondition exists + * @property {google.protobuf.ITimestamp|null} [updateTime] Precondition updateTime + */ + + /** + * Constructs a new Precondition. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a Precondition. + * @implements IPrecondition + * @constructor + * @param {google.firestore.v1beta1.IPrecondition=} [properties] Properties to set + */ + function Precondition(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Precondition exists. + * @member {boolean|null|undefined} exists + * @memberof google.firestore.v1beta1.Precondition + * @instance + */ + Precondition.prototype.exists = null; + + /** + * Precondition updateTime. + * @member {google.protobuf.ITimestamp|null|undefined} updateTime + * @memberof google.firestore.v1beta1.Precondition + * @instance + */ + Precondition.prototype.updateTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Precondition conditionType. + * @member {"exists"|"updateTime"|undefined} conditionType + * @memberof google.firestore.v1beta1.Precondition + * @instance + */ + Object.defineProperty(Precondition.prototype, "conditionType", { + get: $util.oneOfGetter($oneOfFields = ["exists", "updateTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a Precondition message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.Precondition + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.Precondition} Precondition + */ + Precondition.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.Precondition) + return object; + var message = new $root.google.firestore.v1beta1.Precondition(); + if (object.exists != null) + message.exists = Boolean(object.exists); + if (object.updateTime != null) { + if (typeof object.updateTime !== "object") + throw TypeError(".google.firestore.v1beta1.Precondition.updateTime: object expected"); + message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + } + return message; + }; + + /** + * Creates a plain object from a Precondition message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.Precondition + * @static + * @param {google.firestore.v1beta1.Precondition} message Precondition + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Precondition.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.exists != null && message.hasOwnProperty("exists")) { + object.exists = message.exists; + if (options.oneofs) + object.conditionType = "exists"; + } + if (message.updateTime != null && message.hasOwnProperty("updateTime")) { + object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + if (options.oneofs) + object.conditionType = "updateTime"; + } + return object; + }; + + /** + * Converts this Precondition to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.Precondition + * @instance + * @returns {Object.} JSON object + */ + Precondition.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Precondition + * @function getTypeUrl + * @memberof google.firestore.v1beta1.Precondition + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Precondition.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.Precondition"; + }; + + return Precondition; + })(); + + v1beta1.TransactionOptions = (function() { + + /** + * Properties of a TransactionOptions. + * @memberof google.firestore.v1beta1 + * @interface ITransactionOptions + * @property {google.firestore.v1beta1.TransactionOptions.IReadOnly|null} [readOnly] TransactionOptions readOnly + * @property {google.firestore.v1beta1.TransactionOptions.IReadWrite|null} [readWrite] TransactionOptions readWrite + */ + + /** + * Constructs a new TransactionOptions. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a TransactionOptions. + * @implements ITransactionOptions + * @constructor + * @param {google.firestore.v1beta1.ITransactionOptions=} [properties] Properties to set + */ + function TransactionOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TransactionOptions readOnly. + * @member {google.firestore.v1beta1.TransactionOptions.IReadOnly|null|undefined} readOnly + * @memberof google.firestore.v1beta1.TransactionOptions + * @instance + */ + TransactionOptions.prototype.readOnly = null; + + /** + * TransactionOptions readWrite. + * @member {google.firestore.v1beta1.TransactionOptions.IReadWrite|null|undefined} readWrite + * @memberof google.firestore.v1beta1.TransactionOptions + * @instance + */ + TransactionOptions.prototype.readWrite = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * TransactionOptions mode. + * @member {"readOnly"|"readWrite"|undefined} mode + * @memberof google.firestore.v1beta1.TransactionOptions + * @instance + */ + Object.defineProperty(TransactionOptions.prototype, "mode", { + get: $util.oneOfGetter($oneOfFields = ["readOnly", "readWrite"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.TransactionOptions + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.TransactionOptions} TransactionOptions + */ + TransactionOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.TransactionOptions) + return object; + var message = new $root.google.firestore.v1beta1.TransactionOptions(); + if (object.readOnly != null) { + if (typeof object.readOnly !== "object") + throw TypeError(".google.firestore.v1beta1.TransactionOptions.readOnly: object expected"); + message.readOnly = $root.google.firestore.v1beta1.TransactionOptions.ReadOnly.fromObject(object.readOnly); + } + if (object.readWrite != null) { + if (typeof object.readWrite !== "object") + throw TypeError(".google.firestore.v1beta1.TransactionOptions.readWrite: object expected"); + message.readWrite = $root.google.firestore.v1beta1.TransactionOptions.ReadWrite.fromObject(object.readWrite); + } + return message; + }; + + /** + * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.TransactionOptions + * @static + * @param {google.firestore.v1beta1.TransactionOptions} message TransactionOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TransactionOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.readOnly != null && message.hasOwnProperty("readOnly")) { + object.readOnly = $root.google.firestore.v1beta1.TransactionOptions.ReadOnly.toObject(message.readOnly, options); + if (options.oneofs) + object.mode = "readOnly"; + } + if (message.readWrite != null && message.hasOwnProperty("readWrite")) { + object.readWrite = $root.google.firestore.v1beta1.TransactionOptions.ReadWrite.toObject(message.readWrite, options); + if (options.oneofs) + object.mode = "readWrite"; + } + return object; + }; + + /** + * Converts this TransactionOptions to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.TransactionOptions + * @instance + * @returns {Object.} JSON object + */ + TransactionOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TransactionOptions + * @function getTypeUrl + * @memberof google.firestore.v1beta1.TransactionOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TransactionOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.TransactionOptions"; + }; + + TransactionOptions.ReadWrite = (function() { + + /** + * Properties of a ReadWrite. + * @memberof google.firestore.v1beta1.TransactionOptions + * @interface IReadWrite + * @property {Uint8Array|null} [retryTransaction] ReadWrite retryTransaction + */ + + /** + * Constructs a new ReadWrite. + * @memberof google.firestore.v1beta1.TransactionOptions + * @classdesc Represents a ReadWrite. + * @implements IReadWrite + * @constructor + * @param {google.firestore.v1beta1.TransactionOptions.IReadWrite=} [properties] Properties to set + */ + function ReadWrite(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReadWrite retryTransaction. + * @member {Uint8Array} retryTransaction + * @memberof google.firestore.v1beta1.TransactionOptions.ReadWrite + * @instance + */ + ReadWrite.prototype.retryTransaction = $util.newBuffer([]); + + /** + * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.TransactionOptions.ReadWrite + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.TransactionOptions.ReadWrite} ReadWrite + */ + ReadWrite.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.TransactionOptions.ReadWrite) + return object; + var message = new $root.google.firestore.v1beta1.TransactionOptions.ReadWrite(); + if (object.retryTransaction != null) + if (typeof object.retryTransaction === "string") + $util.base64.decode(object.retryTransaction, message.retryTransaction = $util.newBuffer($util.base64.length(object.retryTransaction)), 0); + else if (object.retryTransaction.length >= 0) + message.retryTransaction = object.retryTransaction; + return message; + }; + + /** + * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.TransactionOptions.ReadWrite + * @static + * @param {google.firestore.v1beta1.TransactionOptions.ReadWrite} message ReadWrite + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReadWrite.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if (options.bytes === String) + object.retryTransaction = ""; + else { + object.retryTransaction = []; + if (options.bytes !== Array) + object.retryTransaction = $util.newBuffer(object.retryTransaction); + } + if (message.retryTransaction != null && message.hasOwnProperty("retryTransaction")) + object.retryTransaction = options.bytes === String ? $util.base64.encode(message.retryTransaction, 0, message.retryTransaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.retryTransaction) : message.retryTransaction; + return object; + }; + + /** + * Converts this ReadWrite to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.TransactionOptions.ReadWrite + * @instance + * @returns {Object.} JSON object + */ + ReadWrite.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReadWrite + * @function getTypeUrl + * @memberof google.firestore.v1beta1.TransactionOptions.ReadWrite + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReadWrite.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.TransactionOptions.ReadWrite"; + }; + + return ReadWrite; + })(); + + TransactionOptions.ReadOnly = (function() { + + /** + * Properties of a ReadOnly. + * @memberof google.firestore.v1beta1.TransactionOptions + * @interface IReadOnly + * @property {google.protobuf.ITimestamp|null} [readTime] ReadOnly readTime + */ + + /** + * Constructs a new ReadOnly. + * @memberof google.firestore.v1beta1.TransactionOptions + * @classdesc Represents a ReadOnly. + * @implements IReadOnly + * @constructor + * @param {google.firestore.v1beta1.TransactionOptions.IReadOnly=} [properties] Properties to set + */ + function ReadOnly(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReadOnly readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly + * @instance + */ + ReadOnly.prototype.readTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ReadOnly consistencySelector. + * @member {"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly + * @instance + */ + Object.defineProperty(ReadOnly.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.TransactionOptions.ReadOnly} ReadOnly + */ + ReadOnly.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.TransactionOptions.ReadOnly) + return object; + var message = new $root.google.firestore.v1beta1.TransactionOptions.ReadOnly(); + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1beta1.TransactionOptions.ReadOnly.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly + * @static + * @param {google.firestore.v1beta1.TransactionOptions.ReadOnly} message ReadOnly + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReadOnly.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + return object; + }; + + /** + * Converts this ReadOnly to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly + * @instance + * @returns {Object.} JSON object + */ + ReadOnly.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReadOnly + * @function getTypeUrl + * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReadOnly.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.TransactionOptions.ReadOnly"; + }; + + return ReadOnly; + })(); + + return TransactionOptions; + })(); + + v1beta1.Document = (function() { + + /** + * Properties of a Document. + * @memberof google.firestore.v1beta1 + * @interface IDocument + * @property {string|null} [name] Document name + * @property {Object.|null} [fields] Document fields + * @property {google.protobuf.ITimestamp|null} [createTime] Document createTime + * @property {google.protobuf.ITimestamp|null} [updateTime] Document updateTime + */ + + /** + * Constructs a new Document. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a Document. + * @implements IDocument + * @constructor + * @param {google.firestore.v1beta1.IDocument=} [properties] Properties to set + */ + function Document(properties) { + this.fields = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Document name. + * @member {string} name + * @memberof google.firestore.v1beta1.Document + * @instance + */ + Document.prototype.name = ""; + + /** + * Document fields. + * @member {Object.} fields + * @memberof google.firestore.v1beta1.Document + * @instance + */ + Document.prototype.fields = $util.emptyObject; + + /** + * Document createTime. + * @member {google.protobuf.ITimestamp|null|undefined} createTime + * @memberof google.firestore.v1beta1.Document + * @instance + */ + Document.prototype.createTime = null; + + /** + * Document updateTime. + * @member {google.protobuf.ITimestamp|null|undefined} updateTime + * @memberof google.firestore.v1beta1.Document + * @instance + */ + Document.prototype.updateTime = null; + + /** + * Creates a Document message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.Document + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.Document} Document + */ + Document.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.Document) + return object; + var message = new $root.google.firestore.v1beta1.Document(); + if (object.name != null) + message.name = String(object.name); + if (object.fields) { + if (typeof object.fields !== "object") + throw TypeError(".google.firestore.v1beta1.Document.fields: object expected"); + message.fields = {}; + for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { + if (typeof object.fields[keys[i]] !== "object") + throw TypeError(".google.firestore.v1beta1.Document.fields: object expected"); + message.fields[keys[i]] = $root.google.firestore.v1beta1.Value.fromObject(object.fields[keys[i]]); + } + } + if (object.createTime != null) { + if (typeof object.createTime !== "object") + throw TypeError(".google.firestore.v1beta1.Document.createTime: object expected"); + message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime); + } + if (object.updateTime != null) { + if (typeof object.updateTime !== "object") + throw TypeError(".google.firestore.v1beta1.Document.updateTime: object expected"); + message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + } + return message; + }; + + /** + * Creates a plain object from a Document message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.Document + * @static + * @param {google.firestore.v1beta1.Document} message Document + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Document.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.fields = {}; + if (options.defaults) { + object.name = ""; + object.createTime = null; + object.updateTime = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + var keys2; + if (message.fields && (keys2 = Object.keys(message.fields)).length) { + object.fields = {}; + for (var j = 0; j < keys2.length; ++j) + object.fields[keys2[j]] = $root.google.firestore.v1beta1.Value.toObject(message.fields[keys2[j]], options); + } + if (message.createTime != null && message.hasOwnProperty("createTime")) + object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); + if (message.updateTime != null && message.hasOwnProperty("updateTime")) + object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + return object; + }; + + /** + * Converts this Document to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.Document + * @instance + * @returns {Object.} JSON object + */ + Document.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Document + * @function getTypeUrl + * @memberof google.firestore.v1beta1.Document + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Document.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.Document"; + }; + + return Document; + })(); + + v1beta1.Value = (function() { + + /** + * Properties of a Value. + * @memberof google.firestore.v1beta1 + * @interface IValue + * @property {google.protobuf.NullValue|null} [nullValue] Value nullValue + * @property {boolean|null} [booleanValue] Value booleanValue + * @property {number|string|null} [integerValue] Value integerValue + * @property {number|null} [doubleValue] Value doubleValue + * @property {google.protobuf.ITimestamp|null} [timestampValue] Value timestampValue + * @property {string|null} [stringValue] Value stringValue + * @property {Uint8Array|null} [bytesValue] Value bytesValue + * @property {string|null} [referenceValue] Value referenceValue + * @property {google.type.ILatLng|null} [geoPointValue] Value geoPointValue + * @property {google.firestore.v1beta1.IArrayValue|null} [arrayValue] Value arrayValue + * @property {google.firestore.v1beta1.IMapValue|null} [mapValue] Value mapValue + */ + + /** + * Constructs a new Value. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a Value. + * @implements IValue + * @constructor + * @param {google.firestore.v1beta1.IValue=} [properties] Properties to set + */ + function Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Value nullValue. + * @member {google.protobuf.NullValue|null|undefined} nullValue + * @memberof google.firestore.v1beta1.Value + * @instance + */ + Value.prototype.nullValue = null; + + /** + * Value booleanValue. + * @member {boolean|null|undefined} booleanValue + * @memberof google.firestore.v1beta1.Value + * @instance + */ + Value.prototype.booleanValue = null; + + /** + * Value integerValue. + * @member {number|string|null|undefined} integerValue + * @memberof google.firestore.v1beta1.Value + * @instance + */ + Value.prototype.integerValue = null; + + /** + * Value doubleValue. + * @member {number|null|undefined} doubleValue + * @memberof google.firestore.v1beta1.Value + * @instance + */ + Value.prototype.doubleValue = null; + + /** + * Value timestampValue. + * @member {google.protobuf.ITimestamp|null|undefined} timestampValue + * @memberof google.firestore.v1beta1.Value + * @instance + */ + Value.prototype.timestampValue = null; + + /** + * Value stringValue. + * @member {string|null|undefined} stringValue + * @memberof google.firestore.v1beta1.Value + * @instance + */ + Value.prototype.stringValue = null; + + /** + * Value bytesValue. + * @member {Uint8Array|null|undefined} bytesValue + * @memberof google.firestore.v1beta1.Value + * @instance + */ + Value.prototype.bytesValue = null; + + /** + * Value referenceValue. + * @member {string|null|undefined} referenceValue + * @memberof google.firestore.v1beta1.Value + * @instance + */ + Value.prototype.referenceValue = null; + + /** + * Value geoPointValue. + * @member {google.type.ILatLng|null|undefined} geoPointValue + * @memberof google.firestore.v1beta1.Value + * @instance + */ + Value.prototype.geoPointValue = null; + + /** + * Value arrayValue. + * @member {google.firestore.v1beta1.IArrayValue|null|undefined} arrayValue + * @memberof google.firestore.v1beta1.Value + * @instance + */ + Value.prototype.arrayValue = null; + + /** + * Value mapValue. + * @member {google.firestore.v1beta1.IMapValue|null|undefined} mapValue + * @memberof google.firestore.v1beta1.Value + * @instance + */ + Value.prototype.mapValue = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Value valueType. + * @member {"nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"|undefined} valueType + * @memberof google.firestore.v1beta1.Value + * @instance + */ + Object.defineProperty(Value.prototype, "valueType", { + get: $util.oneOfGetter($oneOfFields = ["nullValue", "booleanValue", "integerValue", "doubleValue", "timestampValue", "stringValue", "bytesValue", "referenceValue", "geoPointValue", "arrayValue", "mapValue"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.Value + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.Value} Value + */ + Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.Value) + return object; + var message = new $root.google.firestore.v1beta1.Value(); + switch (object.nullValue) { + default: + if (typeof object.nullValue === "number") { + message.nullValue = object.nullValue; + break; + } + break; + case "NULL_VALUE": + case 0: + message.nullValue = 0; + break; + } + if (object.booleanValue != null) + message.booleanValue = Boolean(object.booleanValue); + if (object.integerValue != null) + if ($util.Long) + (message.integerValue = $util.Long.fromValue(object.integerValue)).unsigned = false; + else if (typeof object.integerValue === "string") + message.integerValue = parseInt(object.integerValue, 10); + else if (typeof object.integerValue === "number") + message.integerValue = object.integerValue; + else if (typeof object.integerValue === "object") + message.integerValue = new $util.LongBits(object.integerValue.low >>> 0, object.integerValue.high >>> 0).toNumber(); + if (object.doubleValue != null) + message.doubleValue = Number(object.doubleValue); + if (object.timestampValue != null) { + if (typeof object.timestampValue !== "object") + throw TypeError(".google.firestore.v1beta1.Value.timestampValue: object expected"); + message.timestampValue = $root.google.protobuf.Timestamp.fromObject(object.timestampValue); + } + if (object.stringValue != null) + message.stringValue = String(object.stringValue); + if (object.bytesValue != null) + if (typeof object.bytesValue === "string") + $util.base64.decode(object.bytesValue, message.bytesValue = $util.newBuffer($util.base64.length(object.bytesValue)), 0); + else if (object.bytesValue.length >= 0) + message.bytesValue = object.bytesValue; + if (object.referenceValue != null) + message.referenceValue = String(object.referenceValue); + if (object.geoPointValue != null) { + if (typeof object.geoPointValue !== "object") + throw TypeError(".google.firestore.v1beta1.Value.geoPointValue: object expected"); + message.geoPointValue = $root.google.type.LatLng.fromObject(object.geoPointValue); + } + if (object.arrayValue != null) { + if (typeof object.arrayValue !== "object") + throw TypeError(".google.firestore.v1beta1.Value.arrayValue: object expected"); + message.arrayValue = $root.google.firestore.v1beta1.ArrayValue.fromObject(object.arrayValue); + } + if (object.mapValue != null) { + if (typeof object.mapValue !== "object") + throw TypeError(".google.firestore.v1beta1.Value.mapValue: object expected"); + message.mapValue = $root.google.firestore.v1beta1.MapValue.fromObject(object.mapValue); + } + return message; + }; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.Value + * @static + * @param {google.firestore.v1beta1.Value} message Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.booleanValue != null && message.hasOwnProperty("booleanValue")) { + object.booleanValue = message.booleanValue; + if (options.oneofs) + object.valueType = "booleanValue"; + } + if (message.integerValue != null && message.hasOwnProperty("integerValue")) { + if (typeof message.integerValue === "number") + object.integerValue = options.longs === String ? String(message.integerValue) : message.integerValue; + else + object.integerValue = options.longs === String ? $util.Long.prototype.toString.call(message.integerValue) : options.longs === Number ? new $util.LongBits(message.integerValue.low >>> 0, message.integerValue.high >>> 0).toNumber() : message.integerValue; + if (options.oneofs) + object.valueType = "integerValue"; + } + if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) { + object.doubleValue = options.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue; + if (options.oneofs) + object.valueType = "doubleValue"; + } + if (message.referenceValue != null && message.hasOwnProperty("referenceValue")) { + object.referenceValue = message.referenceValue; + if (options.oneofs) + object.valueType = "referenceValue"; + } + if (message.mapValue != null && message.hasOwnProperty("mapValue")) { + object.mapValue = $root.google.firestore.v1beta1.MapValue.toObject(message.mapValue, options); + if (options.oneofs) + object.valueType = "mapValue"; + } + if (message.geoPointValue != null && message.hasOwnProperty("geoPointValue")) { + object.geoPointValue = $root.google.type.LatLng.toObject(message.geoPointValue, options); + if (options.oneofs) + object.valueType = "geoPointValue"; + } + if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) { + object.arrayValue = $root.google.firestore.v1beta1.ArrayValue.toObject(message.arrayValue, options); + if (options.oneofs) + object.valueType = "arrayValue"; + } + if (message.timestampValue != null && message.hasOwnProperty("timestampValue")) { + object.timestampValue = $root.google.protobuf.Timestamp.toObject(message.timestampValue, options); + if (options.oneofs) + object.valueType = "timestampValue"; + } + if (message.nullValue != null && message.hasOwnProperty("nullValue")) { + object.nullValue = options.enums === String ? $root.google.protobuf.NullValue[message.nullValue] === undefined ? message.nullValue : $root.google.protobuf.NullValue[message.nullValue] : message.nullValue; + if (options.oneofs) + object.valueType = "nullValue"; + } + if (message.stringValue != null && message.hasOwnProperty("stringValue")) { + object.stringValue = message.stringValue; + if (options.oneofs) + object.valueType = "stringValue"; + } + if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) { + object.bytesValue = options.bytes === String ? $util.base64.encode(message.bytesValue, 0, message.bytesValue.length) : options.bytes === Array ? Array.prototype.slice.call(message.bytesValue) : message.bytesValue; + if (options.oneofs) + object.valueType = "bytesValue"; + } + return object; + }; + + /** + * Converts this Value to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.Value + * @instance + * @returns {Object.} JSON object + */ + Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Value + * @function getTypeUrl + * @memberof google.firestore.v1beta1.Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.Value"; + }; + + return Value; + })(); + + v1beta1.ArrayValue = (function() { + + /** + * Properties of an ArrayValue. + * @memberof google.firestore.v1beta1 + * @interface IArrayValue + * @property {Array.|null} [values] ArrayValue values + */ + + /** + * Constructs a new ArrayValue. + * @memberof google.firestore.v1beta1 + * @classdesc Represents an ArrayValue. + * @implements IArrayValue + * @constructor + * @param {google.firestore.v1beta1.IArrayValue=} [properties] Properties to set + */ + function ArrayValue(properties) { + this.values = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ArrayValue values. + * @member {Array.} values + * @memberof google.firestore.v1beta1.ArrayValue + * @instance + */ + ArrayValue.prototype.values = $util.emptyArray; + + /** + * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.ArrayValue + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.ArrayValue} ArrayValue + */ + ArrayValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.ArrayValue) + return object; + var message = new $root.google.firestore.v1beta1.ArrayValue(); + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".google.firestore.v1beta1.ArrayValue.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".google.firestore.v1beta1.ArrayValue.values: object expected"); + message.values[i] = $root.google.firestore.v1beta1.Value.fromObject(object.values[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.ArrayValue + * @static + * @param {google.firestore.v1beta1.ArrayValue} message ArrayValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ArrayValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.values = []; + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.google.firestore.v1beta1.Value.toObject(message.values[j], options); + } + return object; + }; + + /** + * Converts this ArrayValue to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.ArrayValue + * @instance + * @returns {Object.} JSON object + */ + ArrayValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ArrayValue + * @function getTypeUrl + * @memberof google.firestore.v1beta1.ArrayValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ArrayValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.ArrayValue"; + }; + + return ArrayValue; + })(); + + v1beta1.MapValue = (function() { + + /** + * Properties of a MapValue. + * @memberof google.firestore.v1beta1 + * @interface IMapValue + * @property {Object.|null} [fields] MapValue fields + */ + + /** + * Constructs a new MapValue. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a MapValue. + * @implements IMapValue + * @constructor + * @param {google.firestore.v1beta1.IMapValue=} [properties] Properties to set + */ + function MapValue(properties) { + this.fields = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MapValue fields. + * @member {Object.} fields + * @memberof google.firestore.v1beta1.MapValue + * @instance + */ + MapValue.prototype.fields = $util.emptyObject; + + /** + * Creates a MapValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.MapValue + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.MapValue} MapValue + */ + MapValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.MapValue) + return object; + var message = new $root.google.firestore.v1beta1.MapValue(); + if (object.fields) { + if (typeof object.fields !== "object") + throw TypeError(".google.firestore.v1beta1.MapValue.fields: object expected"); + message.fields = {}; + for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { + if (typeof object.fields[keys[i]] !== "object") + throw TypeError(".google.firestore.v1beta1.MapValue.fields: object expected"); + message.fields[keys[i]] = $root.google.firestore.v1beta1.Value.fromObject(object.fields[keys[i]]); + } + } + return message; + }; + + /** + * Creates a plain object from a MapValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.MapValue + * @static + * @param {google.firestore.v1beta1.MapValue} message MapValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MapValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.fields = {}; + var keys2; + if (message.fields && (keys2 = Object.keys(message.fields)).length) { + object.fields = {}; + for (var j = 0; j < keys2.length; ++j) + object.fields[keys2[j]] = $root.google.firestore.v1beta1.Value.toObject(message.fields[keys2[j]], options); + } + return object; + }; + + /** + * Converts this MapValue to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.MapValue + * @instance + * @returns {Object.} JSON object + */ + MapValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MapValue + * @function getTypeUrl + * @memberof google.firestore.v1beta1.MapValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MapValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.MapValue"; + }; + + return MapValue; + })(); + + v1beta1.Firestore = (function() { + + /** + * Constructs a new Firestore service. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a Firestore + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function Firestore(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (Firestore.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = Firestore; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#getDocument}. + * @memberof google.firestore.v1beta1.Firestore + * @typedef GetDocumentCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1beta1.Document} [response] Document + */ + + /** + * Calls GetDocument. + * @function getDocument + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IGetDocumentRequest} request GetDocumentRequest message or plain object + * @param {google.firestore.v1beta1.Firestore.GetDocumentCallback} callback Node-style callback called with the error, if any, and Document + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.getDocument = function getDocument(request, callback) { + return this.rpcCall(getDocument, $root.google.firestore.v1beta1.GetDocumentRequest, $root.google.firestore.v1beta1.Document, request, callback); + }, "name", { value: "GetDocument" }); + + /** + * Calls GetDocument. + * @function getDocument + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IGetDocumentRequest} request GetDocumentRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#listDocuments}. + * @memberof google.firestore.v1beta1.Firestore + * @typedef ListDocumentsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1beta1.ListDocumentsResponse} [response] ListDocumentsResponse + */ + + /** + * Calls ListDocuments. + * @function listDocuments + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IListDocumentsRequest} request ListDocumentsRequest message or plain object + * @param {google.firestore.v1beta1.Firestore.ListDocumentsCallback} callback Node-style callback called with the error, if any, and ListDocumentsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.listDocuments = function listDocuments(request, callback) { + return this.rpcCall(listDocuments, $root.google.firestore.v1beta1.ListDocumentsRequest, $root.google.firestore.v1beta1.ListDocumentsResponse, request, callback); + }, "name", { value: "ListDocuments" }); + + /** + * Calls ListDocuments. + * @function listDocuments + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IListDocumentsRequest} request ListDocumentsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#updateDocument}. + * @memberof google.firestore.v1beta1.Firestore + * @typedef UpdateDocumentCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1beta1.Document} [response] Document + */ + + /** + * Calls UpdateDocument. + * @function updateDocument + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IUpdateDocumentRequest} request UpdateDocumentRequest message or plain object + * @param {google.firestore.v1beta1.Firestore.UpdateDocumentCallback} callback Node-style callback called with the error, if any, and Document + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.updateDocument = function updateDocument(request, callback) { + return this.rpcCall(updateDocument, $root.google.firestore.v1beta1.UpdateDocumentRequest, $root.google.firestore.v1beta1.Document, request, callback); + }, "name", { value: "UpdateDocument" }); + + /** + * Calls UpdateDocument. + * @function updateDocument + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IUpdateDocumentRequest} request UpdateDocumentRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#deleteDocument}. + * @memberof google.firestore.v1beta1.Firestore + * @typedef DeleteDocumentCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteDocument. + * @function deleteDocument + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IDeleteDocumentRequest} request DeleteDocumentRequest message or plain object + * @param {google.firestore.v1beta1.Firestore.DeleteDocumentCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.deleteDocument = function deleteDocument(request, callback) { + return this.rpcCall(deleteDocument, $root.google.firestore.v1beta1.DeleteDocumentRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteDocument" }); + + /** + * Calls DeleteDocument. + * @function deleteDocument + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IDeleteDocumentRequest} request DeleteDocumentRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#batchGetDocuments}. + * @memberof google.firestore.v1beta1.Firestore + * @typedef BatchGetDocumentsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1beta1.BatchGetDocumentsResponse} [response] BatchGetDocumentsResponse + */ + + /** + * Calls BatchGetDocuments. + * @function batchGetDocuments + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IBatchGetDocumentsRequest} request BatchGetDocumentsRequest message or plain object + * @param {google.firestore.v1beta1.Firestore.BatchGetDocumentsCallback} callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.batchGetDocuments = function batchGetDocuments(request, callback) { + return this.rpcCall(batchGetDocuments, $root.google.firestore.v1beta1.BatchGetDocumentsRequest, $root.google.firestore.v1beta1.BatchGetDocumentsResponse, request, callback); + }, "name", { value: "BatchGetDocuments" }); + + /** + * Calls BatchGetDocuments. + * @function batchGetDocuments + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IBatchGetDocumentsRequest} request BatchGetDocumentsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#beginTransaction}. + * @memberof google.firestore.v1beta1.Firestore + * @typedef BeginTransactionCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1beta1.BeginTransactionResponse} [response] BeginTransactionResponse + */ + + /** + * Calls BeginTransaction. + * @function beginTransaction + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IBeginTransactionRequest} request BeginTransactionRequest message or plain object + * @param {google.firestore.v1beta1.Firestore.BeginTransactionCallback} callback Node-style callback called with the error, if any, and BeginTransactionResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.beginTransaction = function beginTransaction(request, callback) { + return this.rpcCall(beginTransaction, $root.google.firestore.v1beta1.BeginTransactionRequest, $root.google.firestore.v1beta1.BeginTransactionResponse, request, callback); + }, "name", { value: "BeginTransaction" }); + + /** + * Calls BeginTransaction. + * @function beginTransaction + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IBeginTransactionRequest} request BeginTransactionRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#commit}. + * @memberof google.firestore.v1beta1.Firestore + * @typedef CommitCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1beta1.CommitResponse} [response] CommitResponse + */ + + /** + * Calls Commit. + * @function commit + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.ICommitRequest} request CommitRequest message or plain object + * @param {google.firestore.v1beta1.Firestore.CommitCallback} callback Node-style callback called with the error, if any, and CommitResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.commit = function commit(request, callback) { + return this.rpcCall(commit, $root.google.firestore.v1beta1.CommitRequest, $root.google.firestore.v1beta1.CommitResponse, request, callback); + }, "name", { value: "Commit" }); + + /** + * Calls Commit. + * @function commit + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.ICommitRequest} request CommitRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#rollback}. + * @memberof google.firestore.v1beta1.Firestore + * @typedef RollbackCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls Rollback. + * @function rollback + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IRollbackRequest} request RollbackRequest message or plain object + * @param {google.firestore.v1beta1.Firestore.RollbackCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.rollback = function rollback(request, callback) { + return this.rpcCall(rollback, $root.google.firestore.v1beta1.RollbackRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "Rollback" }); + + /** + * Calls Rollback. + * @function rollback + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IRollbackRequest} request RollbackRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#runQuery}. + * @memberof google.firestore.v1beta1.Firestore + * @typedef RunQueryCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1beta1.RunQueryResponse} [response] RunQueryResponse + */ + + /** + * Calls RunQuery. + * @function runQuery + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IRunQueryRequest} request RunQueryRequest message or plain object + * @param {google.firestore.v1beta1.Firestore.RunQueryCallback} callback Node-style callback called with the error, if any, and RunQueryResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.runQuery = function runQuery(request, callback) { + return this.rpcCall(runQuery, $root.google.firestore.v1beta1.RunQueryRequest, $root.google.firestore.v1beta1.RunQueryResponse, request, callback); + }, "name", { value: "RunQuery" }); + + /** + * Calls RunQuery. + * @function runQuery + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IRunQueryRequest} request RunQueryRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#partitionQuery}. + * @memberof google.firestore.v1beta1.Firestore + * @typedef PartitionQueryCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1beta1.PartitionQueryResponse} [response] PartitionQueryResponse + */ + + /** + * Calls PartitionQuery. + * @function partitionQuery + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IPartitionQueryRequest} request PartitionQueryRequest message or plain object + * @param {google.firestore.v1beta1.Firestore.PartitionQueryCallback} callback Node-style callback called with the error, if any, and PartitionQueryResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.partitionQuery = function partitionQuery(request, callback) { + return this.rpcCall(partitionQuery, $root.google.firestore.v1beta1.PartitionQueryRequest, $root.google.firestore.v1beta1.PartitionQueryResponse, request, callback); + }, "name", { value: "PartitionQuery" }); + + /** + * Calls PartitionQuery. + * @function partitionQuery + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IPartitionQueryRequest} request PartitionQueryRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#write}. + * @memberof google.firestore.v1beta1.Firestore + * @typedef WriteCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1beta1.WriteResponse} [response] WriteResponse + */ + + /** + * Calls Write. + * @function write + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IWriteRequest} request WriteRequest message or plain object + * @param {google.firestore.v1beta1.Firestore.WriteCallback} callback Node-style callback called with the error, if any, and WriteResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.write = function write(request, callback) { + return this.rpcCall(write, $root.google.firestore.v1beta1.WriteRequest, $root.google.firestore.v1beta1.WriteResponse, request, callback); + }, "name", { value: "Write" }); + + /** + * Calls Write. + * @function write + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IWriteRequest} request WriteRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#listen}. + * @memberof google.firestore.v1beta1.Firestore + * @typedef ListenCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1beta1.ListenResponse} [response] ListenResponse + */ + + /** + * Calls Listen. + * @function listen + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IListenRequest} request ListenRequest message or plain object + * @param {google.firestore.v1beta1.Firestore.ListenCallback} callback Node-style callback called with the error, if any, and ListenResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.listen = function listen(request, callback) { + return this.rpcCall(listen, $root.google.firestore.v1beta1.ListenRequest, $root.google.firestore.v1beta1.ListenResponse, request, callback); + }, "name", { value: "Listen" }); + + /** + * Calls Listen. + * @function listen + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IListenRequest} request ListenRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#listCollectionIds}. + * @memberof google.firestore.v1beta1.Firestore + * @typedef ListCollectionIdsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1beta1.ListCollectionIdsResponse} [response] ListCollectionIdsResponse + */ + + /** + * Calls ListCollectionIds. + * @function listCollectionIds + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IListCollectionIdsRequest} request ListCollectionIdsRequest message or plain object + * @param {google.firestore.v1beta1.Firestore.ListCollectionIdsCallback} callback Node-style callback called with the error, if any, and ListCollectionIdsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.listCollectionIds = function listCollectionIds(request, callback) { + return this.rpcCall(listCollectionIds, $root.google.firestore.v1beta1.ListCollectionIdsRequest, $root.google.firestore.v1beta1.ListCollectionIdsResponse, request, callback); + }, "name", { value: "ListCollectionIds" }); + + /** + * Calls ListCollectionIds. + * @function listCollectionIds + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IListCollectionIdsRequest} request ListCollectionIdsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#batchWrite}. + * @memberof google.firestore.v1beta1.Firestore + * @typedef BatchWriteCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1beta1.BatchWriteResponse} [response] BatchWriteResponse + */ + + /** + * Calls BatchWrite. + * @function batchWrite + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IBatchWriteRequest} request BatchWriteRequest message or plain object + * @param {google.firestore.v1beta1.Firestore.BatchWriteCallback} callback Node-style callback called with the error, if any, and BatchWriteResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.batchWrite = function batchWrite(request, callback) { + return this.rpcCall(batchWrite, $root.google.firestore.v1beta1.BatchWriteRequest, $root.google.firestore.v1beta1.BatchWriteResponse, request, callback); + }, "name", { value: "BatchWrite" }); + + /** + * Calls BatchWrite. + * @function batchWrite + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.IBatchWriteRequest} request BatchWriteRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#createDocument}. + * @memberof google.firestore.v1beta1.Firestore + * @typedef CreateDocumentCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1beta1.Document} [response] Document + */ + + /** + * Calls CreateDocument. + * @function createDocument + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.ICreateDocumentRequest} request CreateDocumentRequest message or plain object + * @param {google.firestore.v1beta1.Firestore.CreateDocumentCallback} callback Node-style callback called with the error, if any, and Document + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.createDocument = function createDocument(request, callback) { + return this.rpcCall(createDocument, $root.google.firestore.v1beta1.CreateDocumentRequest, $root.google.firestore.v1beta1.Document, request, callback); + }, "name", { value: "CreateDocument" }); + + /** + * Calls CreateDocument. + * @function createDocument + * @memberof google.firestore.v1beta1.Firestore + * @instance + * @param {google.firestore.v1beta1.ICreateDocumentRequest} request CreateDocumentRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return Firestore; + })(); + + v1beta1.GetDocumentRequest = (function() { + + /** + * Properties of a GetDocumentRequest. + * @memberof google.firestore.v1beta1 + * @interface IGetDocumentRequest + * @property {string|null} [name] GetDocumentRequest name + * @property {google.firestore.v1beta1.IDocumentMask|null} [mask] GetDocumentRequest mask + * @property {Uint8Array|null} [transaction] GetDocumentRequest transaction + * @property {google.protobuf.ITimestamp|null} [readTime] GetDocumentRequest readTime + */ + + /** + * Constructs a new GetDocumentRequest. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a GetDocumentRequest. + * @implements IGetDocumentRequest + * @constructor + * @param {google.firestore.v1beta1.IGetDocumentRequest=} [properties] Properties to set + */ + function GetDocumentRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetDocumentRequest name. + * @member {string} name + * @memberof google.firestore.v1beta1.GetDocumentRequest + * @instance + */ + GetDocumentRequest.prototype.name = ""; + + /** + * GetDocumentRequest mask. + * @member {google.firestore.v1beta1.IDocumentMask|null|undefined} mask + * @memberof google.firestore.v1beta1.GetDocumentRequest + * @instance + */ + GetDocumentRequest.prototype.mask = null; + + /** + * GetDocumentRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1beta1.GetDocumentRequest + * @instance + */ + GetDocumentRequest.prototype.transaction = null; + + /** + * GetDocumentRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1beta1.GetDocumentRequest + * @instance + */ + GetDocumentRequest.prototype.readTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * GetDocumentRequest consistencySelector. + * @member {"transaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1beta1.GetDocumentRequest + * @instance + */ + Object.defineProperty(GetDocumentRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.GetDocumentRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.GetDocumentRequest} GetDocumentRequest + */ + GetDocumentRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.GetDocumentRequest) + return object; + var message = new $root.google.firestore.v1beta1.GetDocumentRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.mask != null) { + if (typeof object.mask !== "object") + throw TypeError(".google.firestore.v1beta1.GetDocumentRequest.mask: object expected"); + message.mask = $root.google.firestore.v1beta1.DocumentMask.fromObject(object.mask); + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1beta1.GetDocumentRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.GetDocumentRequest + * @static + * @param {google.firestore.v1beta1.GetDocumentRequest} message GetDocumentRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetDocumentRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.mask = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.mask != null && message.hasOwnProperty("mask")) + object.mask = $root.google.firestore.v1beta1.DocumentMask.toObject(message.mask, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + return object; + }; + + /** + * Converts this GetDocumentRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.GetDocumentRequest + * @instance + * @returns {Object.} JSON object + */ + GetDocumentRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetDocumentRequest + * @function getTypeUrl + * @memberof google.firestore.v1beta1.GetDocumentRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetDocumentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.GetDocumentRequest"; + }; + + return GetDocumentRequest; + })(); + + v1beta1.ListDocumentsRequest = (function() { + + /** + * Properties of a ListDocumentsRequest. + * @memberof google.firestore.v1beta1 + * @interface IListDocumentsRequest + * @property {string|null} [parent] ListDocumentsRequest parent + * @property {string|null} [collectionId] ListDocumentsRequest collectionId + * @property {number|null} [pageSize] ListDocumentsRequest pageSize + * @property {string|null} [pageToken] ListDocumentsRequest pageToken + * @property {string|null} [orderBy] ListDocumentsRequest orderBy + * @property {google.firestore.v1beta1.IDocumentMask|null} [mask] ListDocumentsRequest mask + * @property {Uint8Array|null} [transaction] ListDocumentsRequest transaction + * @property {google.protobuf.ITimestamp|null} [readTime] ListDocumentsRequest readTime + * @property {boolean|null} [showMissing] ListDocumentsRequest showMissing + */ + + /** + * Constructs a new ListDocumentsRequest. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a ListDocumentsRequest. + * @implements IListDocumentsRequest + * @constructor + * @param {google.firestore.v1beta1.IListDocumentsRequest=} [properties] Properties to set + */ + function ListDocumentsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListDocumentsRequest parent. + * @member {string} parent + * @memberof google.firestore.v1beta1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.parent = ""; + + /** + * ListDocumentsRequest collectionId. + * @member {string} collectionId + * @memberof google.firestore.v1beta1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.collectionId = ""; + + /** + * ListDocumentsRequest pageSize. + * @member {number} pageSize + * @memberof google.firestore.v1beta1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.pageSize = 0; + + /** + * ListDocumentsRequest pageToken. + * @member {string} pageToken + * @memberof google.firestore.v1beta1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.pageToken = ""; + + /** + * ListDocumentsRequest orderBy. + * @member {string} orderBy + * @memberof google.firestore.v1beta1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.orderBy = ""; + + /** + * ListDocumentsRequest mask. + * @member {google.firestore.v1beta1.IDocumentMask|null|undefined} mask + * @memberof google.firestore.v1beta1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.mask = null; + + /** + * ListDocumentsRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1beta1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.transaction = null; + + /** + * ListDocumentsRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1beta1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.readTime = null; + + /** + * ListDocumentsRequest showMissing. + * @member {boolean} showMissing + * @memberof google.firestore.v1beta1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.showMissing = false; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ListDocumentsRequest consistencySelector. + * @member {"transaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1beta1.ListDocumentsRequest + * @instance + */ + Object.defineProperty(ListDocumentsRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.ListDocumentsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.ListDocumentsRequest} ListDocumentsRequest + */ + ListDocumentsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.ListDocumentsRequest) + return object; + var message = new $root.google.firestore.v1beta1.ListDocumentsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.collectionId != null) + message.collectionId = String(object.collectionId); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.orderBy != null) + message.orderBy = String(object.orderBy); + if (object.mask != null) { + if (typeof object.mask !== "object") + throw TypeError(".google.firestore.v1beta1.ListDocumentsRequest.mask: object expected"); + message.mask = $root.google.firestore.v1beta1.DocumentMask.fromObject(object.mask); + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1beta1.ListDocumentsRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.showMissing != null) + message.showMissing = Boolean(object.showMissing); + return message; + }; + + /** + * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.ListDocumentsRequest + * @static + * @param {google.firestore.v1beta1.ListDocumentsRequest} message ListDocumentsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListDocumentsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.collectionId = ""; + object.pageSize = 0; + object.pageToken = ""; + object.orderBy = ""; + object.mask = null; + object.showMissing = false; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.collectionId != null && message.hasOwnProperty("collectionId")) + object.collectionId = message.collectionId; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.orderBy != null && message.hasOwnProperty("orderBy")) + object.orderBy = message.orderBy; + if (message.mask != null && message.hasOwnProperty("mask")) + object.mask = $root.google.firestore.v1beta1.DocumentMask.toObject(message.mask, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + if (message.showMissing != null && message.hasOwnProperty("showMissing")) + object.showMissing = message.showMissing; + return object; + }; + + /** + * Converts this ListDocumentsRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.ListDocumentsRequest + * @instance + * @returns {Object.} JSON object + */ + ListDocumentsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListDocumentsRequest + * @function getTypeUrl + * @memberof google.firestore.v1beta1.ListDocumentsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListDocumentsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.ListDocumentsRequest"; + }; + + return ListDocumentsRequest; + })(); + + v1beta1.ListDocumentsResponse = (function() { + + /** + * Properties of a ListDocumentsResponse. + * @memberof google.firestore.v1beta1 + * @interface IListDocumentsResponse + * @property {Array.|null} [documents] ListDocumentsResponse documents + * @property {string|null} [nextPageToken] ListDocumentsResponse nextPageToken + */ + + /** + * Constructs a new ListDocumentsResponse. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a ListDocumentsResponse. + * @implements IListDocumentsResponse + * @constructor + * @param {google.firestore.v1beta1.IListDocumentsResponse=} [properties] Properties to set + */ + function ListDocumentsResponse(properties) { + this.documents = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListDocumentsResponse documents. + * @member {Array.} documents + * @memberof google.firestore.v1beta1.ListDocumentsResponse + * @instance + */ + ListDocumentsResponse.prototype.documents = $util.emptyArray; + + /** + * ListDocumentsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.firestore.v1beta1.ListDocumentsResponse + * @instance + */ + ListDocumentsResponse.prototype.nextPageToken = ""; + + /** + * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.ListDocumentsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.ListDocumentsResponse} ListDocumentsResponse + */ + ListDocumentsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.ListDocumentsResponse) + return object; + var message = new $root.google.firestore.v1beta1.ListDocumentsResponse(); + if (object.documents) { + if (!Array.isArray(object.documents)) + throw TypeError(".google.firestore.v1beta1.ListDocumentsResponse.documents: array expected"); + message.documents = []; + for (var i = 0; i < object.documents.length; ++i) { + if (typeof object.documents[i] !== "object") + throw TypeError(".google.firestore.v1beta1.ListDocumentsResponse.documents: object expected"); + message.documents[i] = $root.google.firestore.v1beta1.Document.fromObject(object.documents[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.ListDocumentsResponse + * @static + * @param {google.firestore.v1beta1.ListDocumentsResponse} message ListDocumentsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListDocumentsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.documents = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.documents && message.documents.length) { + object.documents = []; + for (var j = 0; j < message.documents.length; ++j) + object.documents[j] = $root.google.firestore.v1beta1.Document.toObject(message.documents[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListDocumentsResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.ListDocumentsResponse + * @instance + * @returns {Object.} JSON object + */ + ListDocumentsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListDocumentsResponse + * @function getTypeUrl + * @memberof google.firestore.v1beta1.ListDocumentsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListDocumentsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.ListDocumentsResponse"; + }; + + return ListDocumentsResponse; + })(); + + v1beta1.CreateDocumentRequest = (function() { + + /** + * Properties of a CreateDocumentRequest. + * @memberof google.firestore.v1beta1 + * @interface ICreateDocumentRequest + * @property {string|null} [parent] CreateDocumentRequest parent + * @property {string|null} [collectionId] CreateDocumentRequest collectionId + * @property {string|null} [documentId] CreateDocumentRequest documentId + * @property {google.firestore.v1beta1.IDocument|null} [document] CreateDocumentRequest document + * @property {google.firestore.v1beta1.IDocumentMask|null} [mask] CreateDocumentRequest mask + */ + + /** + * Constructs a new CreateDocumentRequest. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a CreateDocumentRequest. + * @implements ICreateDocumentRequest + * @constructor + * @param {google.firestore.v1beta1.ICreateDocumentRequest=} [properties] Properties to set + */ + function CreateDocumentRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateDocumentRequest parent. + * @member {string} parent + * @memberof google.firestore.v1beta1.CreateDocumentRequest + * @instance + */ + CreateDocumentRequest.prototype.parent = ""; + + /** + * CreateDocumentRequest collectionId. + * @member {string} collectionId + * @memberof google.firestore.v1beta1.CreateDocumentRequest + * @instance + */ + CreateDocumentRequest.prototype.collectionId = ""; + + /** + * CreateDocumentRequest documentId. + * @member {string} documentId + * @memberof google.firestore.v1beta1.CreateDocumentRequest + * @instance + */ + CreateDocumentRequest.prototype.documentId = ""; + + /** + * CreateDocumentRequest document. + * @member {google.firestore.v1beta1.IDocument|null|undefined} document + * @memberof google.firestore.v1beta1.CreateDocumentRequest + * @instance + */ + CreateDocumentRequest.prototype.document = null; + + /** + * CreateDocumentRequest mask. + * @member {google.firestore.v1beta1.IDocumentMask|null|undefined} mask + * @memberof google.firestore.v1beta1.CreateDocumentRequest + * @instance + */ + CreateDocumentRequest.prototype.mask = null; + + /** + * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.CreateDocumentRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.CreateDocumentRequest} CreateDocumentRequest + */ + CreateDocumentRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.CreateDocumentRequest) + return object; + var message = new $root.google.firestore.v1beta1.CreateDocumentRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.collectionId != null) + message.collectionId = String(object.collectionId); + if (object.documentId != null) + message.documentId = String(object.documentId); + if (object.document != null) { + if (typeof object.document !== "object") + throw TypeError(".google.firestore.v1beta1.CreateDocumentRequest.document: object expected"); + message.document = $root.google.firestore.v1beta1.Document.fromObject(object.document); + } + if (object.mask != null) { + if (typeof object.mask !== "object") + throw TypeError(".google.firestore.v1beta1.CreateDocumentRequest.mask: object expected"); + message.mask = $root.google.firestore.v1beta1.DocumentMask.fromObject(object.mask); + } + return message; + }; + + /** + * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.CreateDocumentRequest + * @static + * @param {google.firestore.v1beta1.CreateDocumentRequest} message CreateDocumentRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateDocumentRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.collectionId = ""; + object.documentId = ""; + object.document = null; + object.mask = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.collectionId != null && message.hasOwnProperty("collectionId")) + object.collectionId = message.collectionId; + if (message.documentId != null && message.hasOwnProperty("documentId")) + object.documentId = message.documentId; + if (message.document != null && message.hasOwnProperty("document")) + object.document = $root.google.firestore.v1beta1.Document.toObject(message.document, options); + if (message.mask != null && message.hasOwnProperty("mask")) + object.mask = $root.google.firestore.v1beta1.DocumentMask.toObject(message.mask, options); + return object; + }; + + /** + * Converts this CreateDocumentRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.CreateDocumentRequest + * @instance + * @returns {Object.} JSON object + */ + CreateDocumentRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateDocumentRequest + * @function getTypeUrl + * @memberof google.firestore.v1beta1.CreateDocumentRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateDocumentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.CreateDocumentRequest"; + }; + + return CreateDocumentRequest; + })(); + + v1beta1.UpdateDocumentRequest = (function() { + + /** + * Properties of an UpdateDocumentRequest. + * @memberof google.firestore.v1beta1 + * @interface IUpdateDocumentRequest + * @property {google.firestore.v1beta1.IDocument|null} [document] UpdateDocumentRequest document + * @property {google.firestore.v1beta1.IDocumentMask|null} [updateMask] UpdateDocumentRequest updateMask + * @property {google.firestore.v1beta1.IDocumentMask|null} [mask] UpdateDocumentRequest mask + * @property {google.firestore.v1beta1.IPrecondition|null} [currentDocument] UpdateDocumentRequest currentDocument + */ + + /** + * Constructs a new UpdateDocumentRequest. + * @memberof google.firestore.v1beta1 + * @classdesc Represents an UpdateDocumentRequest. + * @implements IUpdateDocumentRequest + * @constructor + * @param {google.firestore.v1beta1.IUpdateDocumentRequest=} [properties] Properties to set + */ + function UpdateDocumentRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateDocumentRequest document. + * @member {google.firestore.v1beta1.IDocument|null|undefined} document + * @memberof google.firestore.v1beta1.UpdateDocumentRequest + * @instance + */ + UpdateDocumentRequest.prototype.document = null; + + /** + * UpdateDocumentRequest updateMask. + * @member {google.firestore.v1beta1.IDocumentMask|null|undefined} updateMask + * @memberof google.firestore.v1beta1.UpdateDocumentRequest + * @instance + */ + UpdateDocumentRequest.prototype.updateMask = null; + + /** + * UpdateDocumentRequest mask. + * @member {google.firestore.v1beta1.IDocumentMask|null|undefined} mask + * @memberof google.firestore.v1beta1.UpdateDocumentRequest + * @instance + */ + UpdateDocumentRequest.prototype.mask = null; + + /** + * UpdateDocumentRequest currentDocument. + * @member {google.firestore.v1beta1.IPrecondition|null|undefined} currentDocument + * @memberof google.firestore.v1beta1.UpdateDocumentRequest + * @instance + */ + UpdateDocumentRequest.prototype.currentDocument = null; + + /** + * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.UpdateDocumentRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.UpdateDocumentRequest} UpdateDocumentRequest + */ + UpdateDocumentRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.UpdateDocumentRequest) + return object; + var message = new $root.google.firestore.v1beta1.UpdateDocumentRequest(); + if (object.document != null) { + if (typeof object.document !== "object") + throw TypeError(".google.firestore.v1beta1.UpdateDocumentRequest.document: object expected"); + message.document = $root.google.firestore.v1beta1.Document.fromObject(object.document); + } + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.firestore.v1beta1.UpdateDocumentRequest.updateMask: object expected"); + message.updateMask = $root.google.firestore.v1beta1.DocumentMask.fromObject(object.updateMask); + } + if (object.mask != null) { + if (typeof object.mask !== "object") + throw TypeError(".google.firestore.v1beta1.UpdateDocumentRequest.mask: object expected"); + message.mask = $root.google.firestore.v1beta1.DocumentMask.fromObject(object.mask); + } + if (object.currentDocument != null) { + if (typeof object.currentDocument !== "object") + throw TypeError(".google.firestore.v1beta1.UpdateDocumentRequest.currentDocument: object expected"); + message.currentDocument = $root.google.firestore.v1beta1.Precondition.fromObject(object.currentDocument); + } + return message; + }; + + /** + * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.UpdateDocumentRequest + * @static + * @param {google.firestore.v1beta1.UpdateDocumentRequest} message UpdateDocumentRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateDocumentRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.document = null; + object.updateMask = null; + object.mask = null; + object.currentDocument = null; + } + if (message.document != null && message.hasOwnProperty("document")) + object.document = $root.google.firestore.v1beta1.Document.toObject(message.document, options); + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.firestore.v1beta1.DocumentMask.toObject(message.updateMask, options); + if (message.mask != null && message.hasOwnProperty("mask")) + object.mask = $root.google.firestore.v1beta1.DocumentMask.toObject(message.mask, options); + if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) + object.currentDocument = $root.google.firestore.v1beta1.Precondition.toObject(message.currentDocument, options); + return object; + }; + + /** + * Converts this UpdateDocumentRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.UpdateDocumentRequest + * @instance + * @returns {Object.} JSON object + */ + UpdateDocumentRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateDocumentRequest + * @function getTypeUrl + * @memberof google.firestore.v1beta1.UpdateDocumentRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateDocumentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.UpdateDocumentRequest"; + }; + + return UpdateDocumentRequest; + })(); + + v1beta1.DeleteDocumentRequest = (function() { + + /** + * Properties of a DeleteDocumentRequest. + * @memberof google.firestore.v1beta1 + * @interface IDeleteDocumentRequest + * @property {string|null} [name] DeleteDocumentRequest name + * @property {google.firestore.v1beta1.IPrecondition|null} [currentDocument] DeleteDocumentRequest currentDocument + */ + + /** + * Constructs a new DeleteDocumentRequest. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a DeleteDocumentRequest. + * @implements IDeleteDocumentRequest + * @constructor + * @param {google.firestore.v1beta1.IDeleteDocumentRequest=} [properties] Properties to set + */ + function DeleteDocumentRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteDocumentRequest name. + * @member {string} name + * @memberof google.firestore.v1beta1.DeleteDocumentRequest + * @instance + */ + DeleteDocumentRequest.prototype.name = ""; + + /** + * DeleteDocumentRequest currentDocument. + * @member {google.firestore.v1beta1.IPrecondition|null|undefined} currentDocument + * @memberof google.firestore.v1beta1.DeleteDocumentRequest + * @instance + */ + DeleteDocumentRequest.prototype.currentDocument = null; + + /** + * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.DeleteDocumentRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.DeleteDocumentRequest} DeleteDocumentRequest + */ + DeleteDocumentRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.DeleteDocumentRequest) + return object; + var message = new $root.google.firestore.v1beta1.DeleteDocumentRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.currentDocument != null) { + if (typeof object.currentDocument !== "object") + throw TypeError(".google.firestore.v1beta1.DeleteDocumentRequest.currentDocument: object expected"); + message.currentDocument = $root.google.firestore.v1beta1.Precondition.fromObject(object.currentDocument); + } + return message; + }; + + /** + * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.DeleteDocumentRequest + * @static + * @param {google.firestore.v1beta1.DeleteDocumentRequest} message DeleteDocumentRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteDocumentRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.currentDocument = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) + object.currentDocument = $root.google.firestore.v1beta1.Precondition.toObject(message.currentDocument, options); + return object; + }; + + /** + * Converts this DeleteDocumentRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.DeleteDocumentRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteDocumentRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteDocumentRequest + * @function getTypeUrl + * @memberof google.firestore.v1beta1.DeleteDocumentRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteDocumentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.DeleteDocumentRequest"; + }; + + return DeleteDocumentRequest; + })(); + + v1beta1.BatchGetDocumentsRequest = (function() { + + /** + * Properties of a BatchGetDocumentsRequest. + * @memberof google.firestore.v1beta1 + * @interface IBatchGetDocumentsRequest + * @property {string|null} [database] BatchGetDocumentsRequest database + * @property {Array.|null} [documents] BatchGetDocumentsRequest documents + * @property {google.firestore.v1beta1.IDocumentMask|null} [mask] BatchGetDocumentsRequest mask + * @property {Uint8Array|null} [transaction] BatchGetDocumentsRequest transaction + * @property {google.firestore.v1beta1.ITransactionOptions|null} [newTransaction] BatchGetDocumentsRequest newTransaction + * @property {google.protobuf.ITimestamp|null} [readTime] BatchGetDocumentsRequest readTime + */ + + /** + * Constructs a new BatchGetDocumentsRequest. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a BatchGetDocumentsRequest. + * @implements IBatchGetDocumentsRequest + * @constructor + * @param {google.firestore.v1beta1.IBatchGetDocumentsRequest=} [properties] Properties to set + */ + function BatchGetDocumentsRequest(properties) { + this.documents = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BatchGetDocumentsRequest database. + * @member {string} database + * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.database = ""; + + /** + * BatchGetDocumentsRequest documents. + * @member {Array.} documents + * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.documents = $util.emptyArray; + + /** + * BatchGetDocumentsRequest mask. + * @member {google.firestore.v1beta1.IDocumentMask|null|undefined} mask + * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.mask = null; + + /** + * BatchGetDocumentsRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.transaction = null; + + /** + * BatchGetDocumentsRequest newTransaction. + * @member {google.firestore.v1beta1.ITransactionOptions|null|undefined} newTransaction + * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.newTransaction = null; + + /** + * BatchGetDocumentsRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.readTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * BatchGetDocumentsRequest consistencySelector. + * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest + * @instance + */ + Object.defineProperty(BatchGetDocumentsRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.BatchGetDocumentsRequest} BatchGetDocumentsRequest + */ + BatchGetDocumentsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.BatchGetDocumentsRequest) + return object; + var message = new $root.google.firestore.v1beta1.BatchGetDocumentsRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.documents) { + if (!Array.isArray(object.documents)) + throw TypeError(".google.firestore.v1beta1.BatchGetDocumentsRequest.documents: array expected"); + message.documents = []; + for (var i = 0; i < object.documents.length; ++i) + message.documents[i] = String(object.documents[i]); + } + if (object.mask != null) { + if (typeof object.mask !== "object") + throw TypeError(".google.firestore.v1beta1.BatchGetDocumentsRequest.mask: object expected"); + message.mask = $root.google.firestore.v1beta1.DocumentMask.fromObject(object.mask); + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.newTransaction != null) { + if (typeof object.newTransaction !== "object") + throw TypeError(".google.firestore.v1beta1.BatchGetDocumentsRequest.newTransaction: object expected"); + message.newTransaction = $root.google.firestore.v1beta1.TransactionOptions.fromObject(object.newTransaction); + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1beta1.BatchGetDocumentsRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest + * @static + * @param {google.firestore.v1beta1.BatchGetDocumentsRequest} message BatchGetDocumentsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchGetDocumentsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.documents = []; + if (options.defaults) { + object.database = ""; + object.mask = null; + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.documents && message.documents.length) { + object.documents = []; + for (var j = 0; j < message.documents.length; ++j) + object.documents[j] = message.documents[j]; + } + if (message.mask != null && message.hasOwnProperty("mask")) + object.mask = $root.google.firestore.v1beta1.DocumentMask.toObject(message.mask, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; + } + if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { + object.newTransaction = $root.google.firestore.v1beta1.TransactionOptions.toObject(message.newTransaction, options); + if (options.oneofs) + object.consistencySelector = "newTransaction"; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + return object; + }; + + /** + * Converts this BatchGetDocumentsRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest + * @instance + * @returns {Object.} JSON object + */ + BatchGetDocumentsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchGetDocumentsRequest + * @function getTypeUrl + * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchGetDocumentsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.BatchGetDocumentsRequest"; + }; + + return BatchGetDocumentsRequest; + })(); + + v1beta1.BatchGetDocumentsResponse = (function() { + + /** + * Properties of a BatchGetDocumentsResponse. + * @memberof google.firestore.v1beta1 + * @interface IBatchGetDocumentsResponse + * @property {google.firestore.v1beta1.IDocument|null} [found] BatchGetDocumentsResponse found + * @property {string|null} [missing] BatchGetDocumentsResponse missing + * @property {Uint8Array|null} [transaction] BatchGetDocumentsResponse transaction + * @property {google.protobuf.ITimestamp|null} [readTime] BatchGetDocumentsResponse readTime + */ + + /** + * Constructs a new BatchGetDocumentsResponse. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a BatchGetDocumentsResponse. + * @implements IBatchGetDocumentsResponse + * @constructor + * @param {google.firestore.v1beta1.IBatchGetDocumentsResponse=} [properties] Properties to set + */ + function BatchGetDocumentsResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BatchGetDocumentsResponse found. + * @member {google.firestore.v1beta1.IDocument|null|undefined} found + * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse + * @instance + */ + BatchGetDocumentsResponse.prototype.found = null; + + /** + * BatchGetDocumentsResponse missing. + * @member {string|null|undefined} missing + * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse + * @instance + */ + BatchGetDocumentsResponse.prototype.missing = null; + + /** + * BatchGetDocumentsResponse transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse + * @instance + */ + BatchGetDocumentsResponse.prototype.transaction = $util.newBuffer([]); + + /** + * BatchGetDocumentsResponse readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse + * @instance + */ + BatchGetDocumentsResponse.prototype.readTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * BatchGetDocumentsResponse result. + * @member {"found"|"missing"|undefined} result + * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse + * @instance + */ + Object.defineProperty(BatchGetDocumentsResponse.prototype, "result", { + get: $util.oneOfGetter($oneOfFields = ["found", "missing"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.BatchGetDocumentsResponse} BatchGetDocumentsResponse + */ + BatchGetDocumentsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.BatchGetDocumentsResponse) + return object; + var message = new $root.google.firestore.v1beta1.BatchGetDocumentsResponse(); + if (object.found != null) { + if (typeof object.found !== "object") + throw TypeError(".google.firestore.v1beta1.BatchGetDocumentsResponse.found: object expected"); + message.found = $root.google.firestore.v1beta1.Document.fromObject(object.found); + } + if (object.missing != null) + message.missing = String(object.missing); + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1beta1.BatchGetDocumentsResponse.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse + * @static + * @param {google.firestore.v1beta1.BatchGetDocumentsResponse} message BatchGetDocumentsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchGetDocumentsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + object.readTime = null; + } + if (message.found != null && message.hasOwnProperty("found")) { + object.found = $root.google.firestore.v1beta1.Document.toObject(message.found, options); + if (options.oneofs) + object.result = "found"; + } + if (message.missing != null && message.hasOwnProperty("missing")) { + object.missing = message.missing; + if (options.oneofs) + object.result = "missing"; + } + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + return object; + }; + + /** + * Converts this BatchGetDocumentsResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse + * @instance + * @returns {Object.} JSON object + */ + BatchGetDocumentsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchGetDocumentsResponse + * @function getTypeUrl + * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchGetDocumentsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.BatchGetDocumentsResponse"; + }; + + return BatchGetDocumentsResponse; + })(); + + v1beta1.BeginTransactionRequest = (function() { + + /** + * Properties of a BeginTransactionRequest. + * @memberof google.firestore.v1beta1 + * @interface IBeginTransactionRequest + * @property {string|null} [database] BeginTransactionRequest database + * @property {google.firestore.v1beta1.ITransactionOptions|null} [options] BeginTransactionRequest options + */ + + /** + * Constructs a new BeginTransactionRequest. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a BeginTransactionRequest. + * @implements IBeginTransactionRequest + * @constructor + * @param {google.firestore.v1beta1.IBeginTransactionRequest=} [properties] Properties to set + */ + function BeginTransactionRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BeginTransactionRequest database. + * @member {string} database + * @memberof google.firestore.v1beta1.BeginTransactionRequest + * @instance + */ + BeginTransactionRequest.prototype.database = ""; + + /** + * BeginTransactionRequest options. + * @member {google.firestore.v1beta1.ITransactionOptions|null|undefined} options + * @memberof google.firestore.v1beta1.BeginTransactionRequest + * @instance + */ + BeginTransactionRequest.prototype.options = null; + + /** + * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.BeginTransactionRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.BeginTransactionRequest} BeginTransactionRequest + */ + BeginTransactionRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.BeginTransactionRequest) + return object; + var message = new $root.google.firestore.v1beta1.BeginTransactionRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.firestore.v1beta1.BeginTransactionRequest.options: object expected"); + message.options = $root.google.firestore.v1beta1.TransactionOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.BeginTransactionRequest + * @static + * @param {google.firestore.v1beta1.BeginTransactionRequest} message BeginTransactionRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BeginTransactionRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.database = ""; + object.options = null; + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.firestore.v1beta1.TransactionOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this BeginTransactionRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.BeginTransactionRequest + * @instance + * @returns {Object.} JSON object + */ + BeginTransactionRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BeginTransactionRequest + * @function getTypeUrl + * @memberof google.firestore.v1beta1.BeginTransactionRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BeginTransactionRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.BeginTransactionRequest"; + }; + + return BeginTransactionRequest; + })(); + + v1beta1.BeginTransactionResponse = (function() { + + /** + * Properties of a BeginTransactionResponse. + * @memberof google.firestore.v1beta1 + * @interface IBeginTransactionResponse + * @property {Uint8Array|null} [transaction] BeginTransactionResponse transaction + */ + + /** + * Constructs a new BeginTransactionResponse. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a BeginTransactionResponse. + * @implements IBeginTransactionResponse + * @constructor + * @param {google.firestore.v1beta1.IBeginTransactionResponse=} [properties] Properties to set + */ + function BeginTransactionResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BeginTransactionResponse transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1beta1.BeginTransactionResponse + * @instance + */ + BeginTransactionResponse.prototype.transaction = $util.newBuffer([]); + + /** + * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.BeginTransactionResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.BeginTransactionResponse} BeginTransactionResponse + */ + BeginTransactionResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.BeginTransactionResponse) + return object; + var message = new $root.google.firestore.v1beta1.BeginTransactionResponse(); + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + return message; + }; + + /** + * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.BeginTransactionResponse + * @static + * @param {google.firestore.v1beta1.BeginTransactionResponse} message BeginTransactionResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BeginTransactionResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + return object; + }; + + /** + * Converts this BeginTransactionResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.BeginTransactionResponse + * @instance + * @returns {Object.} JSON object + */ + BeginTransactionResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BeginTransactionResponse + * @function getTypeUrl + * @memberof google.firestore.v1beta1.BeginTransactionResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BeginTransactionResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.BeginTransactionResponse"; + }; + + return BeginTransactionResponse; + })(); + + v1beta1.CommitRequest = (function() { + + /** + * Properties of a CommitRequest. + * @memberof google.firestore.v1beta1 + * @interface ICommitRequest + * @property {string|null} [database] CommitRequest database + * @property {Array.|null} [writes] CommitRequest writes + * @property {Uint8Array|null} [transaction] CommitRequest transaction + */ + + /** + * Constructs a new CommitRequest. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a CommitRequest. + * @implements ICommitRequest + * @constructor + * @param {google.firestore.v1beta1.ICommitRequest=} [properties] Properties to set + */ + function CommitRequest(properties) { + this.writes = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CommitRequest database. + * @member {string} database + * @memberof google.firestore.v1beta1.CommitRequest + * @instance + */ + CommitRequest.prototype.database = ""; + + /** + * CommitRequest writes. + * @member {Array.} writes + * @memberof google.firestore.v1beta1.CommitRequest + * @instance + */ + CommitRequest.prototype.writes = $util.emptyArray; + + /** + * CommitRequest transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1beta1.CommitRequest + * @instance + */ + CommitRequest.prototype.transaction = $util.newBuffer([]); + + /** + * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.CommitRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.CommitRequest} CommitRequest + */ + CommitRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.CommitRequest) + return object; + var message = new $root.google.firestore.v1beta1.CommitRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.writes) { + if (!Array.isArray(object.writes)) + throw TypeError(".google.firestore.v1beta1.CommitRequest.writes: array expected"); + message.writes = []; + for (var i = 0; i < object.writes.length; ++i) { + if (typeof object.writes[i] !== "object") + throw TypeError(".google.firestore.v1beta1.CommitRequest.writes: object expected"); + message.writes[i] = $root.google.firestore.v1beta1.Write.fromObject(object.writes[i]); + } + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + return message; + }; + + /** + * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.CommitRequest + * @static + * @param {google.firestore.v1beta1.CommitRequest} message CommitRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CommitRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.writes = []; + if (options.defaults) { + object.database = ""; + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.writes && message.writes.length) { + object.writes = []; + for (var j = 0; j < message.writes.length; ++j) + object.writes[j] = $root.google.firestore.v1beta1.Write.toObject(message.writes[j], options); + } + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + return object; + }; + + /** + * Converts this CommitRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.CommitRequest + * @instance + * @returns {Object.} JSON object + */ + CommitRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CommitRequest + * @function getTypeUrl + * @memberof google.firestore.v1beta1.CommitRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CommitRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.CommitRequest"; + }; + + return CommitRequest; + })(); + + v1beta1.CommitResponse = (function() { + + /** + * Properties of a CommitResponse. + * @memberof google.firestore.v1beta1 + * @interface ICommitResponse + * @property {Array.|null} [writeResults] CommitResponse writeResults + * @property {google.protobuf.ITimestamp|null} [commitTime] CommitResponse commitTime + */ + + /** + * Constructs a new CommitResponse. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a CommitResponse. + * @implements ICommitResponse + * @constructor + * @param {google.firestore.v1beta1.ICommitResponse=} [properties] Properties to set + */ + function CommitResponse(properties) { + this.writeResults = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CommitResponse writeResults. + * @member {Array.} writeResults + * @memberof google.firestore.v1beta1.CommitResponse + * @instance + */ + CommitResponse.prototype.writeResults = $util.emptyArray; + + /** + * CommitResponse commitTime. + * @member {google.protobuf.ITimestamp|null|undefined} commitTime + * @memberof google.firestore.v1beta1.CommitResponse + * @instance + */ + CommitResponse.prototype.commitTime = null; + + /** + * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.CommitResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.CommitResponse} CommitResponse + */ + CommitResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.CommitResponse) + return object; + var message = new $root.google.firestore.v1beta1.CommitResponse(); + if (object.writeResults) { + if (!Array.isArray(object.writeResults)) + throw TypeError(".google.firestore.v1beta1.CommitResponse.writeResults: array expected"); + message.writeResults = []; + for (var i = 0; i < object.writeResults.length; ++i) { + if (typeof object.writeResults[i] !== "object") + throw TypeError(".google.firestore.v1beta1.CommitResponse.writeResults: object expected"); + message.writeResults[i] = $root.google.firestore.v1beta1.WriteResult.fromObject(object.writeResults[i]); + } + } + if (object.commitTime != null) { + if (typeof object.commitTime !== "object") + throw TypeError(".google.firestore.v1beta1.CommitResponse.commitTime: object expected"); + message.commitTime = $root.google.protobuf.Timestamp.fromObject(object.commitTime); + } + return message; + }; + + /** + * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.CommitResponse + * @static + * @param {google.firestore.v1beta1.CommitResponse} message CommitResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CommitResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.writeResults = []; + if (options.defaults) + object.commitTime = null; + if (message.writeResults && message.writeResults.length) { + object.writeResults = []; + for (var j = 0; j < message.writeResults.length; ++j) + object.writeResults[j] = $root.google.firestore.v1beta1.WriteResult.toObject(message.writeResults[j], options); + } + if (message.commitTime != null && message.hasOwnProperty("commitTime")) + object.commitTime = $root.google.protobuf.Timestamp.toObject(message.commitTime, options); + return object; + }; + + /** + * Converts this CommitResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.CommitResponse + * @instance + * @returns {Object.} JSON object + */ + CommitResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CommitResponse + * @function getTypeUrl + * @memberof google.firestore.v1beta1.CommitResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CommitResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.CommitResponse"; + }; + + return CommitResponse; + })(); + + v1beta1.RollbackRequest = (function() { + + /** + * Properties of a RollbackRequest. + * @memberof google.firestore.v1beta1 + * @interface IRollbackRequest + * @property {string|null} [database] RollbackRequest database + * @property {Uint8Array|null} [transaction] RollbackRequest transaction + */ + + /** + * Constructs a new RollbackRequest. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a RollbackRequest. + * @implements IRollbackRequest + * @constructor + * @param {google.firestore.v1beta1.IRollbackRequest=} [properties] Properties to set + */ + function RollbackRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RollbackRequest database. + * @member {string} database + * @memberof google.firestore.v1beta1.RollbackRequest + * @instance + */ + RollbackRequest.prototype.database = ""; + + /** + * RollbackRequest transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1beta1.RollbackRequest + * @instance + */ + RollbackRequest.prototype.transaction = $util.newBuffer([]); + + /** + * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.RollbackRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.RollbackRequest} RollbackRequest + */ + RollbackRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.RollbackRequest) + return object; + var message = new $root.google.firestore.v1beta1.RollbackRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + return message; + }; + + /** + * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.RollbackRequest + * @static + * @param {google.firestore.v1beta1.RollbackRequest} message RollbackRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RollbackRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.database = ""; + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + return object; + }; + + /** + * Converts this RollbackRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.RollbackRequest + * @instance + * @returns {Object.} JSON object + */ + RollbackRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RollbackRequest + * @function getTypeUrl + * @memberof google.firestore.v1beta1.RollbackRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RollbackRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.RollbackRequest"; + }; + + return RollbackRequest; + })(); + + v1beta1.RunQueryRequest = (function() { + + /** + * Properties of a RunQueryRequest. + * @memberof google.firestore.v1beta1 + * @interface IRunQueryRequest + * @property {string|null} [parent] RunQueryRequest parent + * @property {google.firestore.v1beta1.IStructuredQuery|null} [structuredQuery] RunQueryRequest structuredQuery + * @property {Uint8Array|null} [transaction] RunQueryRequest transaction + * @property {google.firestore.v1beta1.ITransactionOptions|null} [newTransaction] RunQueryRequest newTransaction + * @property {google.protobuf.ITimestamp|null} [readTime] RunQueryRequest readTime + */ + + /** + * Constructs a new RunQueryRequest. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a RunQueryRequest. + * @implements IRunQueryRequest + * @constructor + * @param {google.firestore.v1beta1.IRunQueryRequest=} [properties] Properties to set + */ + function RunQueryRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RunQueryRequest parent. + * @member {string} parent + * @memberof google.firestore.v1beta1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.parent = ""; + + /** + * RunQueryRequest structuredQuery. + * @member {google.firestore.v1beta1.IStructuredQuery|null|undefined} structuredQuery + * @memberof google.firestore.v1beta1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.structuredQuery = null; + + /** + * RunQueryRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1beta1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.transaction = null; + + /** + * RunQueryRequest newTransaction. + * @member {google.firestore.v1beta1.ITransactionOptions|null|undefined} newTransaction + * @memberof google.firestore.v1beta1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.newTransaction = null; + + /** + * RunQueryRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1beta1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.readTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * RunQueryRequest queryType. + * @member {"structuredQuery"|undefined} queryType + * @memberof google.firestore.v1beta1.RunQueryRequest + * @instance + */ + Object.defineProperty(RunQueryRequest.prototype, "queryType", { + get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * RunQueryRequest consistencySelector. + * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1beta1.RunQueryRequest + * @instance + */ + Object.defineProperty(RunQueryRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.RunQueryRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.RunQueryRequest} RunQueryRequest + */ + RunQueryRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.RunQueryRequest) + return object; + var message = new $root.google.firestore.v1beta1.RunQueryRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.structuredQuery != null) { + if (typeof object.structuredQuery !== "object") + throw TypeError(".google.firestore.v1beta1.RunQueryRequest.structuredQuery: object expected"); + message.structuredQuery = $root.google.firestore.v1beta1.StructuredQuery.fromObject(object.structuredQuery); + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.newTransaction != null) { + if (typeof object.newTransaction !== "object") + throw TypeError(".google.firestore.v1beta1.RunQueryRequest.newTransaction: object expected"); + message.newTransaction = $root.google.firestore.v1beta1.TransactionOptions.fromObject(object.newTransaction); + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1beta1.RunQueryRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.RunQueryRequest + * @static + * @param {google.firestore.v1beta1.RunQueryRequest} message RunQueryRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RunQueryRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.parent = ""; + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { + object.structuredQuery = $root.google.firestore.v1beta1.StructuredQuery.toObject(message.structuredQuery, options); + if (options.oneofs) + object.queryType = "structuredQuery"; + } + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; + } + if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { + object.newTransaction = $root.google.firestore.v1beta1.TransactionOptions.toObject(message.newTransaction, options); + if (options.oneofs) + object.consistencySelector = "newTransaction"; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + return object; + }; + + /** + * Converts this RunQueryRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.RunQueryRequest + * @instance + * @returns {Object.} JSON object + */ + RunQueryRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RunQueryRequest + * @function getTypeUrl + * @memberof google.firestore.v1beta1.RunQueryRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RunQueryRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.RunQueryRequest"; + }; + + return RunQueryRequest; + })(); + + v1beta1.RunQueryResponse = (function() { + + /** + * Properties of a RunQueryResponse. + * @memberof google.firestore.v1beta1 + * @interface IRunQueryResponse + * @property {Uint8Array|null} [transaction] RunQueryResponse transaction + * @property {google.firestore.v1beta1.IDocument|null} [document] RunQueryResponse document + * @property {google.protobuf.ITimestamp|null} [readTime] RunQueryResponse readTime + * @property {number|null} [skippedResults] RunQueryResponse skippedResults + */ + + /** + * Constructs a new RunQueryResponse. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a RunQueryResponse. + * @implements IRunQueryResponse + * @constructor + * @param {google.firestore.v1beta1.IRunQueryResponse=} [properties] Properties to set + */ + function RunQueryResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RunQueryResponse transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1beta1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.transaction = $util.newBuffer([]); + + /** + * RunQueryResponse document. + * @member {google.firestore.v1beta1.IDocument|null|undefined} document + * @memberof google.firestore.v1beta1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.document = null; + + /** + * RunQueryResponse readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1beta1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.readTime = null; + + /** + * RunQueryResponse skippedResults. + * @member {number} skippedResults + * @memberof google.firestore.v1beta1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.skippedResults = 0; + + /** + * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.RunQueryResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.RunQueryResponse} RunQueryResponse + */ + RunQueryResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.RunQueryResponse) + return object; + var message = new $root.google.firestore.v1beta1.RunQueryResponse(); + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.document != null) { + if (typeof object.document !== "object") + throw TypeError(".google.firestore.v1beta1.RunQueryResponse.document: object expected"); + message.document = $root.google.firestore.v1beta1.Document.fromObject(object.document); + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1beta1.RunQueryResponse.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.skippedResults != null) + message.skippedResults = object.skippedResults | 0; + return message; + }; + + /** + * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.RunQueryResponse + * @static + * @param {google.firestore.v1beta1.RunQueryResponse} message RunQueryResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RunQueryResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.document = null; + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + object.readTime = null; + object.skippedResults = 0; + } + if (message.document != null && message.hasOwnProperty("document")) + object.document = $root.google.firestore.v1beta1.Document.toObject(message.document, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (message.skippedResults != null && message.hasOwnProperty("skippedResults")) + object.skippedResults = message.skippedResults; + return object; + }; + + /** + * Converts this RunQueryResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.RunQueryResponse + * @instance + * @returns {Object.} JSON object + */ + RunQueryResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RunQueryResponse + * @function getTypeUrl + * @memberof google.firestore.v1beta1.RunQueryResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RunQueryResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.RunQueryResponse"; + }; + + return RunQueryResponse; + })(); + + v1beta1.PartitionQueryRequest = (function() { + + /** + * Properties of a PartitionQueryRequest. + * @memberof google.firestore.v1beta1 + * @interface IPartitionQueryRequest + * @property {string|null} [parent] PartitionQueryRequest parent + * @property {google.firestore.v1beta1.IStructuredQuery|null} [structuredQuery] PartitionQueryRequest structuredQuery + * @property {number|string|null} [partitionCount] PartitionQueryRequest partitionCount + * @property {string|null} [pageToken] PartitionQueryRequest pageToken + * @property {number|null} [pageSize] PartitionQueryRequest pageSize + */ + + /** + * Constructs a new PartitionQueryRequest. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a PartitionQueryRequest. + * @implements IPartitionQueryRequest + * @constructor + * @param {google.firestore.v1beta1.IPartitionQueryRequest=} [properties] Properties to set + */ + function PartitionQueryRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PartitionQueryRequest parent. + * @member {string} parent + * @memberof google.firestore.v1beta1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.parent = ""; + + /** + * PartitionQueryRequest structuredQuery. + * @member {google.firestore.v1beta1.IStructuredQuery|null|undefined} structuredQuery + * @memberof google.firestore.v1beta1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.structuredQuery = null; + + /** + * PartitionQueryRequest partitionCount. + * @member {number|string} partitionCount + * @memberof google.firestore.v1beta1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.partitionCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * PartitionQueryRequest pageToken. + * @member {string} pageToken + * @memberof google.firestore.v1beta1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.pageToken = ""; + + /** + * PartitionQueryRequest pageSize. + * @member {number} pageSize + * @memberof google.firestore.v1beta1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.pageSize = 0; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * PartitionQueryRequest queryType. + * @member {"structuredQuery"|undefined} queryType + * @memberof google.firestore.v1beta1.PartitionQueryRequest + * @instance + */ + Object.defineProperty(PartitionQueryRequest.prototype, "queryType", { + get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.PartitionQueryRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.PartitionQueryRequest} PartitionQueryRequest + */ + PartitionQueryRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.PartitionQueryRequest) + return object; + var message = new $root.google.firestore.v1beta1.PartitionQueryRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.structuredQuery != null) { + if (typeof object.structuredQuery !== "object") + throw TypeError(".google.firestore.v1beta1.PartitionQueryRequest.structuredQuery: object expected"); + message.structuredQuery = $root.google.firestore.v1beta1.StructuredQuery.fromObject(object.structuredQuery); + } + if (object.partitionCount != null) + if ($util.Long) + (message.partitionCount = $util.Long.fromValue(object.partitionCount)).unsigned = false; + else if (typeof object.partitionCount === "string") + message.partitionCount = parseInt(object.partitionCount, 10); + else if (typeof object.partitionCount === "number") + message.partitionCount = object.partitionCount; + else if (typeof object.partitionCount === "object") + message.partitionCount = new $util.LongBits(object.partitionCount.low >>> 0, object.partitionCount.high >>> 0).toNumber(); + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + return message; + }; + + /** + * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.PartitionQueryRequest + * @static + * @param {google.firestore.v1beta1.PartitionQueryRequest} message PartitionQueryRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartitionQueryRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.partitionCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.partitionCount = options.longs === String ? "0" : 0; + object.pageToken = ""; + object.pageSize = 0; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { + object.structuredQuery = $root.google.firestore.v1beta1.StructuredQuery.toObject(message.structuredQuery, options); + if (options.oneofs) + object.queryType = "structuredQuery"; + } + if (message.partitionCount != null && message.hasOwnProperty("partitionCount")) + if (typeof message.partitionCount === "number") + object.partitionCount = options.longs === String ? String(message.partitionCount) : message.partitionCount; + else + object.partitionCount = options.longs === String ? $util.Long.prototype.toString.call(message.partitionCount) : options.longs === Number ? new $util.LongBits(message.partitionCount.low >>> 0, message.partitionCount.high >>> 0).toNumber() : message.partitionCount; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + return object; + }; + + /** + * Converts this PartitionQueryRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.PartitionQueryRequest + * @instance + * @returns {Object.} JSON object + */ + PartitionQueryRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartitionQueryRequest + * @function getTypeUrl + * @memberof google.firestore.v1beta1.PartitionQueryRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartitionQueryRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.PartitionQueryRequest"; + }; + + return PartitionQueryRequest; + })(); + + v1beta1.PartitionQueryResponse = (function() { + + /** + * Properties of a PartitionQueryResponse. + * @memberof google.firestore.v1beta1 + * @interface IPartitionQueryResponse + * @property {Array.|null} [partitions] PartitionQueryResponse partitions + * @property {string|null} [nextPageToken] PartitionQueryResponse nextPageToken + */ + + /** + * Constructs a new PartitionQueryResponse. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a PartitionQueryResponse. + * @implements IPartitionQueryResponse + * @constructor + * @param {google.firestore.v1beta1.IPartitionQueryResponse=} [properties] Properties to set + */ + function PartitionQueryResponse(properties) { + this.partitions = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PartitionQueryResponse partitions. + * @member {Array.} partitions + * @memberof google.firestore.v1beta1.PartitionQueryResponse + * @instance + */ + PartitionQueryResponse.prototype.partitions = $util.emptyArray; + + /** + * PartitionQueryResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.firestore.v1beta1.PartitionQueryResponse + * @instance + */ + PartitionQueryResponse.prototype.nextPageToken = ""; + + /** + * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.PartitionQueryResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.PartitionQueryResponse} PartitionQueryResponse + */ + PartitionQueryResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.PartitionQueryResponse) + return object; + var message = new $root.google.firestore.v1beta1.PartitionQueryResponse(); + if (object.partitions) { + if (!Array.isArray(object.partitions)) + throw TypeError(".google.firestore.v1beta1.PartitionQueryResponse.partitions: array expected"); + message.partitions = []; + for (var i = 0; i < object.partitions.length; ++i) { + if (typeof object.partitions[i] !== "object") + throw TypeError(".google.firestore.v1beta1.PartitionQueryResponse.partitions: object expected"); + message.partitions[i] = $root.google.firestore.v1beta1.Cursor.fromObject(object.partitions[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.PartitionQueryResponse + * @static + * @param {google.firestore.v1beta1.PartitionQueryResponse} message PartitionQueryResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartitionQueryResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.partitions = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.partitions && message.partitions.length) { + object.partitions = []; + for (var j = 0; j < message.partitions.length; ++j) + object.partitions[j] = $root.google.firestore.v1beta1.Cursor.toObject(message.partitions[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this PartitionQueryResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.PartitionQueryResponse + * @instance + * @returns {Object.} JSON object + */ + PartitionQueryResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartitionQueryResponse + * @function getTypeUrl + * @memberof google.firestore.v1beta1.PartitionQueryResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartitionQueryResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.PartitionQueryResponse"; + }; + + return PartitionQueryResponse; + })(); + + v1beta1.WriteRequest = (function() { + + /** + * Properties of a WriteRequest. + * @memberof google.firestore.v1beta1 + * @interface IWriteRequest + * @property {string|null} [database] WriteRequest database + * @property {string|null} [streamId] WriteRequest streamId + * @property {Array.|null} [writes] WriteRequest writes + * @property {Uint8Array|null} [streamToken] WriteRequest streamToken + * @property {Object.|null} [labels] WriteRequest labels + */ + + /** + * Constructs a new WriteRequest. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a WriteRequest. + * @implements IWriteRequest + * @constructor + * @param {google.firestore.v1beta1.IWriteRequest=} [properties] Properties to set + */ + function WriteRequest(properties) { + this.writes = []; + this.labels = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * WriteRequest database. + * @member {string} database + * @memberof google.firestore.v1beta1.WriteRequest + * @instance + */ + WriteRequest.prototype.database = ""; + + /** + * WriteRequest streamId. + * @member {string} streamId + * @memberof google.firestore.v1beta1.WriteRequest + * @instance + */ + WriteRequest.prototype.streamId = ""; + + /** + * WriteRequest writes. + * @member {Array.} writes + * @memberof google.firestore.v1beta1.WriteRequest + * @instance + */ + WriteRequest.prototype.writes = $util.emptyArray; + + /** + * WriteRequest streamToken. + * @member {Uint8Array} streamToken + * @memberof google.firestore.v1beta1.WriteRequest + * @instance + */ + WriteRequest.prototype.streamToken = $util.newBuffer([]); + + /** + * WriteRequest labels. + * @member {Object.} labels + * @memberof google.firestore.v1beta1.WriteRequest + * @instance + */ + WriteRequest.prototype.labels = $util.emptyObject; + + /** + * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.WriteRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.WriteRequest} WriteRequest + */ + WriteRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.WriteRequest) + return object; + var message = new $root.google.firestore.v1beta1.WriteRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.streamId != null) + message.streamId = String(object.streamId); + if (object.writes) { + if (!Array.isArray(object.writes)) + throw TypeError(".google.firestore.v1beta1.WriteRequest.writes: array expected"); + message.writes = []; + for (var i = 0; i < object.writes.length; ++i) { + if (typeof object.writes[i] !== "object") + throw TypeError(".google.firestore.v1beta1.WriteRequest.writes: object expected"); + message.writes[i] = $root.google.firestore.v1beta1.Write.fromObject(object.writes[i]); + } + } + if (object.streamToken != null) + if (typeof object.streamToken === "string") + $util.base64.decode(object.streamToken, message.streamToken = $util.newBuffer($util.base64.length(object.streamToken)), 0); + else if (object.streamToken.length >= 0) + message.streamToken = object.streamToken; + if (object.labels) { + if (typeof object.labels !== "object") + throw TypeError(".google.firestore.v1beta1.WriteRequest.labels: object expected"); + message.labels = {}; + for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) + message.labels[keys[i]] = String(object.labels[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.WriteRequest + * @static + * @param {google.firestore.v1beta1.WriteRequest} message WriteRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WriteRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.writes = []; + if (options.objects || options.defaults) + object.labels = {}; + if (options.defaults) { + object.database = ""; + object.streamId = ""; + if (options.bytes === String) + object.streamToken = ""; + else { + object.streamToken = []; + if (options.bytes !== Array) + object.streamToken = $util.newBuffer(object.streamToken); + } + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.streamId != null && message.hasOwnProperty("streamId")) + object.streamId = message.streamId; + if (message.writes && message.writes.length) { + object.writes = []; + for (var j = 0; j < message.writes.length; ++j) + object.writes[j] = $root.google.firestore.v1beta1.Write.toObject(message.writes[j], options); + } + if (message.streamToken != null && message.hasOwnProperty("streamToken")) + object.streamToken = options.bytes === String ? $util.base64.encode(message.streamToken, 0, message.streamToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.streamToken) : message.streamToken; + var keys2; + if (message.labels && (keys2 = Object.keys(message.labels)).length) { + object.labels = {}; + for (var j = 0; j < keys2.length; ++j) + object.labels[keys2[j]] = message.labels[keys2[j]]; + } + return object; + }; + + /** + * Converts this WriteRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.WriteRequest + * @instance + * @returns {Object.} JSON object + */ + WriteRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for WriteRequest + * @function getTypeUrl + * @memberof google.firestore.v1beta1.WriteRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WriteRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.WriteRequest"; + }; + + return WriteRequest; + })(); + + v1beta1.WriteResponse = (function() { + + /** + * Properties of a WriteResponse. + * @memberof google.firestore.v1beta1 + * @interface IWriteResponse + * @property {string|null} [streamId] WriteResponse streamId + * @property {Uint8Array|null} [streamToken] WriteResponse streamToken + * @property {Array.|null} [writeResults] WriteResponse writeResults + * @property {google.protobuf.ITimestamp|null} [commitTime] WriteResponse commitTime + */ + + /** + * Constructs a new WriteResponse. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a WriteResponse. + * @implements IWriteResponse + * @constructor + * @param {google.firestore.v1beta1.IWriteResponse=} [properties] Properties to set + */ + function WriteResponse(properties) { + this.writeResults = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * WriteResponse streamId. + * @member {string} streamId + * @memberof google.firestore.v1beta1.WriteResponse + * @instance + */ + WriteResponse.prototype.streamId = ""; + + /** + * WriteResponse streamToken. + * @member {Uint8Array} streamToken + * @memberof google.firestore.v1beta1.WriteResponse + * @instance + */ + WriteResponse.prototype.streamToken = $util.newBuffer([]); + + /** + * WriteResponse writeResults. + * @member {Array.} writeResults + * @memberof google.firestore.v1beta1.WriteResponse + * @instance + */ + WriteResponse.prototype.writeResults = $util.emptyArray; + + /** + * WriteResponse commitTime. + * @member {google.protobuf.ITimestamp|null|undefined} commitTime + * @memberof google.firestore.v1beta1.WriteResponse + * @instance + */ + WriteResponse.prototype.commitTime = null; + + /** + * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.WriteResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.WriteResponse} WriteResponse + */ + WriteResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.WriteResponse) + return object; + var message = new $root.google.firestore.v1beta1.WriteResponse(); + if (object.streamId != null) + message.streamId = String(object.streamId); + if (object.streamToken != null) + if (typeof object.streamToken === "string") + $util.base64.decode(object.streamToken, message.streamToken = $util.newBuffer($util.base64.length(object.streamToken)), 0); + else if (object.streamToken.length >= 0) + message.streamToken = object.streamToken; + if (object.writeResults) { + if (!Array.isArray(object.writeResults)) + throw TypeError(".google.firestore.v1beta1.WriteResponse.writeResults: array expected"); + message.writeResults = []; + for (var i = 0; i < object.writeResults.length; ++i) { + if (typeof object.writeResults[i] !== "object") + throw TypeError(".google.firestore.v1beta1.WriteResponse.writeResults: object expected"); + message.writeResults[i] = $root.google.firestore.v1beta1.WriteResult.fromObject(object.writeResults[i]); + } + } + if (object.commitTime != null) { + if (typeof object.commitTime !== "object") + throw TypeError(".google.firestore.v1beta1.WriteResponse.commitTime: object expected"); + message.commitTime = $root.google.protobuf.Timestamp.fromObject(object.commitTime); + } + return message; + }; + + /** + * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.WriteResponse + * @static + * @param {google.firestore.v1beta1.WriteResponse} message WriteResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WriteResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.writeResults = []; + if (options.defaults) { + object.streamId = ""; + if (options.bytes === String) + object.streamToken = ""; + else { + object.streamToken = []; + if (options.bytes !== Array) + object.streamToken = $util.newBuffer(object.streamToken); + } + object.commitTime = null; + } + if (message.streamId != null && message.hasOwnProperty("streamId")) + object.streamId = message.streamId; + if (message.streamToken != null && message.hasOwnProperty("streamToken")) + object.streamToken = options.bytes === String ? $util.base64.encode(message.streamToken, 0, message.streamToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.streamToken) : message.streamToken; + if (message.writeResults && message.writeResults.length) { + object.writeResults = []; + for (var j = 0; j < message.writeResults.length; ++j) + object.writeResults[j] = $root.google.firestore.v1beta1.WriteResult.toObject(message.writeResults[j], options); + } + if (message.commitTime != null && message.hasOwnProperty("commitTime")) + object.commitTime = $root.google.protobuf.Timestamp.toObject(message.commitTime, options); + return object; + }; + + /** + * Converts this WriteResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.WriteResponse + * @instance + * @returns {Object.} JSON object + */ + WriteResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for WriteResponse + * @function getTypeUrl + * @memberof google.firestore.v1beta1.WriteResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WriteResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.WriteResponse"; + }; + + return WriteResponse; + })(); + + v1beta1.ListenRequest = (function() { + + /** + * Properties of a ListenRequest. + * @memberof google.firestore.v1beta1 + * @interface IListenRequest + * @property {string|null} [database] ListenRequest database + * @property {google.firestore.v1beta1.ITarget|null} [addTarget] ListenRequest addTarget + * @property {number|null} [removeTarget] ListenRequest removeTarget + * @property {Object.|null} [labels] ListenRequest labels + */ + + /** + * Constructs a new ListenRequest. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a ListenRequest. + * @implements IListenRequest + * @constructor + * @param {google.firestore.v1beta1.IListenRequest=} [properties] Properties to set + */ + function ListenRequest(properties) { + this.labels = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListenRequest database. + * @member {string} database + * @memberof google.firestore.v1beta1.ListenRequest + * @instance + */ + ListenRequest.prototype.database = ""; + + /** + * ListenRequest addTarget. + * @member {google.firestore.v1beta1.ITarget|null|undefined} addTarget + * @memberof google.firestore.v1beta1.ListenRequest + * @instance + */ + ListenRequest.prototype.addTarget = null; + + /** + * ListenRequest removeTarget. + * @member {number|null|undefined} removeTarget + * @memberof google.firestore.v1beta1.ListenRequest + * @instance + */ + ListenRequest.prototype.removeTarget = null; + + /** + * ListenRequest labels. + * @member {Object.} labels + * @memberof google.firestore.v1beta1.ListenRequest + * @instance + */ + ListenRequest.prototype.labels = $util.emptyObject; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ListenRequest targetChange. + * @member {"addTarget"|"removeTarget"|undefined} targetChange + * @memberof google.firestore.v1beta1.ListenRequest + * @instance + */ + Object.defineProperty(ListenRequest.prototype, "targetChange", { + get: $util.oneOfGetter($oneOfFields = ["addTarget", "removeTarget"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.ListenRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.ListenRequest} ListenRequest + */ + ListenRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.ListenRequest) + return object; + var message = new $root.google.firestore.v1beta1.ListenRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.addTarget != null) { + if (typeof object.addTarget !== "object") + throw TypeError(".google.firestore.v1beta1.ListenRequest.addTarget: object expected"); + message.addTarget = $root.google.firestore.v1beta1.Target.fromObject(object.addTarget); + } + if (object.removeTarget != null) + message.removeTarget = object.removeTarget | 0; + if (object.labels) { + if (typeof object.labels !== "object") + throw TypeError(".google.firestore.v1beta1.ListenRequest.labels: object expected"); + message.labels = {}; + for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) + message.labels[keys[i]] = String(object.labels[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.ListenRequest + * @static + * @param {google.firestore.v1beta1.ListenRequest} message ListenRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListenRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.labels = {}; + if (options.defaults) + object.database = ""; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.addTarget != null && message.hasOwnProperty("addTarget")) { + object.addTarget = $root.google.firestore.v1beta1.Target.toObject(message.addTarget, options); + if (options.oneofs) + object.targetChange = "addTarget"; + } + if (message.removeTarget != null && message.hasOwnProperty("removeTarget")) { + object.removeTarget = message.removeTarget; + if (options.oneofs) + object.targetChange = "removeTarget"; + } + var keys2; + if (message.labels && (keys2 = Object.keys(message.labels)).length) { + object.labels = {}; + for (var j = 0; j < keys2.length; ++j) + object.labels[keys2[j]] = message.labels[keys2[j]]; + } + return object; + }; + + /** + * Converts this ListenRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.ListenRequest + * @instance + * @returns {Object.} JSON object + */ + ListenRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListenRequest + * @function getTypeUrl + * @memberof google.firestore.v1beta1.ListenRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListenRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.ListenRequest"; + }; + + return ListenRequest; + })(); + + v1beta1.ListenResponse = (function() { + + /** + * Properties of a ListenResponse. + * @memberof google.firestore.v1beta1 + * @interface IListenResponse + * @property {google.firestore.v1beta1.ITargetChange|null} [targetChange] ListenResponse targetChange + * @property {google.firestore.v1beta1.IDocumentChange|null} [documentChange] ListenResponse documentChange + * @property {google.firestore.v1beta1.IDocumentDelete|null} [documentDelete] ListenResponse documentDelete + * @property {google.firestore.v1beta1.IDocumentRemove|null} [documentRemove] ListenResponse documentRemove + * @property {google.firestore.v1beta1.IExistenceFilter|null} [filter] ListenResponse filter + */ + + /** + * Constructs a new ListenResponse. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a ListenResponse. + * @implements IListenResponse + * @constructor + * @param {google.firestore.v1beta1.IListenResponse=} [properties] Properties to set + */ + function ListenResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListenResponse targetChange. + * @member {google.firestore.v1beta1.ITargetChange|null|undefined} targetChange + * @memberof google.firestore.v1beta1.ListenResponse + * @instance + */ + ListenResponse.prototype.targetChange = null; + + /** + * ListenResponse documentChange. + * @member {google.firestore.v1beta1.IDocumentChange|null|undefined} documentChange + * @memberof google.firestore.v1beta1.ListenResponse + * @instance + */ + ListenResponse.prototype.documentChange = null; + + /** + * ListenResponse documentDelete. + * @member {google.firestore.v1beta1.IDocumentDelete|null|undefined} documentDelete + * @memberof google.firestore.v1beta1.ListenResponse + * @instance + */ + ListenResponse.prototype.documentDelete = null; + + /** + * ListenResponse documentRemove. + * @member {google.firestore.v1beta1.IDocumentRemove|null|undefined} documentRemove + * @memberof google.firestore.v1beta1.ListenResponse + * @instance + */ + ListenResponse.prototype.documentRemove = null; + + /** + * ListenResponse filter. + * @member {google.firestore.v1beta1.IExistenceFilter|null|undefined} filter + * @memberof google.firestore.v1beta1.ListenResponse + * @instance + */ + ListenResponse.prototype.filter = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ListenResponse responseType. + * @member {"targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"|undefined} responseType + * @memberof google.firestore.v1beta1.ListenResponse + * @instance + */ + Object.defineProperty(ListenResponse.prototype, "responseType", { + get: $util.oneOfGetter($oneOfFields = ["targetChange", "documentChange", "documentDelete", "documentRemove", "filter"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.ListenResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.ListenResponse} ListenResponse + */ + ListenResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.ListenResponse) + return object; + var message = new $root.google.firestore.v1beta1.ListenResponse(); + if (object.targetChange != null) { + if (typeof object.targetChange !== "object") + throw TypeError(".google.firestore.v1beta1.ListenResponse.targetChange: object expected"); + message.targetChange = $root.google.firestore.v1beta1.TargetChange.fromObject(object.targetChange); + } + if (object.documentChange != null) { + if (typeof object.documentChange !== "object") + throw TypeError(".google.firestore.v1beta1.ListenResponse.documentChange: object expected"); + message.documentChange = $root.google.firestore.v1beta1.DocumentChange.fromObject(object.documentChange); + } + if (object.documentDelete != null) { + if (typeof object.documentDelete !== "object") + throw TypeError(".google.firestore.v1beta1.ListenResponse.documentDelete: object expected"); + message.documentDelete = $root.google.firestore.v1beta1.DocumentDelete.fromObject(object.documentDelete); + } + if (object.documentRemove != null) { + if (typeof object.documentRemove !== "object") + throw TypeError(".google.firestore.v1beta1.ListenResponse.documentRemove: object expected"); + message.documentRemove = $root.google.firestore.v1beta1.DocumentRemove.fromObject(object.documentRemove); + } + if (object.filter != null) { + if (typeof object.filter !== "object") + throw TypeError(".google.firestore.v1beta1.ListenResponse.filter: object expected"); + message.filter = $root.google.firestore.v1beta1.ExistenceFilter.fromObject(object.filter); + } + return message; + }; + + /** + * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.ListenResponse + * @static + * @param {google.firestore.v1beta1.ListenResponse} message ListenResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListenResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.targetChange != null && message.hasOwnProperty("targetChange")) { + object.targetChange = $root.google.firestore.v1beta1.TargetChange.toObject(message.targetChange, options); + if (options.oneofs) + object.responseType = "targetChange"; + } + if (message.documentChange != null && message.hasOwnProperty("documentChange")) { + object.documentChange = $root.google.firestore.v1beta1.DocumentChange.toObject(message.documentChange, options); + if (options.oneofs) + object.responseType = "documentChange"; + } + if (message.documentDelete != null && message.hasOwnProperty("documentDelete")) { + object.documentDelete = $root.google.firestore.v1beta1.DocumentDelete.toObject(message.documentDelete, options); + if (options.oneofs) + object.responseType = "documentDelete"; + } + if (message.filter != null && message.hasOwnProperty("filter")) { + object.filter = $root.google.firestore.v1beta1.ExistenceFilter.toObject(message.filter, options); + if (options.oneofs) + object.responseType = "filter"; + } + if (message.documentRemove != null && message.hasOwnProperty("documentRemove")) { + object.documentRemove = $root.google.firestore.v1beta1.DocumentRemove.toObject(message.documentRemove, options); + if (options.oneofs) + object.responseType = "documentRemove"; + } + return object; + }; + + /** + * Converts this ListenResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.ListenResponse + * @instance + * @returns {Object.} JSON object + */ + ListenResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListenResponse + * @function getTypeUrl + * @memberof google.firestore.v1beta1.ListenResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListenResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.ListenResponse"; + }; + + return ListenResponse; + })(); + + v1beta1.Target = (function() { + + /** + * Properties of a Target. + * @memberof google.firestore.v1beta1 + * @interface ITarget + * @property {google.firestore.v1beta1.Target.IQueryTarget|null} [query] Target query + * @property {google.firestore.v1beta1.Target.IDocumentsTarget|null} [documents] Target documents + * @property {Uint8Array|null} [resumeToken] Target resumeToken + * @property {google.protobuf.ITimestamp|null} [readTime] Target readTime + * @property {number|null} [targetId] Target targetId + * @property {boolean|null} [once] Target once + */ + + /** + * Constructs a new Target. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a Target. + * @implements ITarget + * @constructor + * @param {google.firestore.v1beta1.ITarget=} [properties] Properties to set + */ + function Target(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Target query. + * @member {google.firestore.v1beta1.Target.IQueryTarget|null|undefined} query + * @memberof google.firestore.v1beta1.Target + * @instance + */ + Target.prototype.query = null; + + /** + * Target documents. + * @member {google.firestore.v1beta1.Target.IDocumentsTarget|null|undefined} documents + * @memberof google.firestore.v1beta1.Target + * @instance + */ + Target.prototype.documents = null; + + /** + * Target resumeToken. + * @member {Uint8Array|null|undefined} resumeToken + * @memberof google.firestore.v1beta1.Target + * @instance + */ + Target.prototype.resumeToken = null; + + /** + * Target readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1beta1.Target + * @instance + */ + Target.prototype.readTime = null; + + /** + * Target targetId. + * @member {number} targetId + * @memberof google.firestore.v1beta1.Target + * @instance + */ + Target.prototype.targetId = 0; + + /** + * Target once. + * @member {boolean} once + * @memberof google.firestore.v1beta1.Target + * @instance + */ + Target.prototype.once = false; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Target targetType. + * @member {"query"|"documents"|undefined} targetType + * @memberof google.firestore.v1beta1.Target + * @instance + */ + Object.defineProperty(Target.prototype, "targetType", { + get: $util.oneOfGetter($oneOfFields = ["query", "documents"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Target resumeType. + * @member {"resumeToken"|"readTime"|undefined} resumeType + * @memberof google.firestore.v1beta1.Target + * @instance + */ + Object.defineProperty(Target.prototype, "resumeType", { + get: $util.oneOfGetter($oneOfFields = ["resumeToken", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a Target message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.Target + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.Target} Target + */ + Target.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.Target) + return object; + var message = new $root.google.firestore.v1beta1.Target(); + if (object.query != null) { + if (typeof object.query !== "object") + throw TypeError(".google.firestore.v1beta1.Target.query: object expected"); + message.query = $root.google.firestore.v1beta1.Target.QueryTarget.fromObject(object.query); + } + if (object.documents != null) { + if (typeof object.documents !== "object") + throw TypeError(".google.firestore.v1beta1.Target.documents: object expected"); + message.documents = $root.google.firestore.v1beta1.Target.DocumentsTarget.fromObject(object.documents); + } + if (object.resumeToken != null) + if (typeof object.resumeToken === "string") + $util.base64.decode(object.resumeToken, message.resumeToken = $util.newBuffer($util.base64.length(object.resumeToken)), 0); + else if (object.resumeToken.length >= 0) + message.resumeToken = object.resumeToken; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1beta1.Target.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.targetId != null) + message.targetId = object.targetId | 0; + if (object.once != null) + message.once = Boolean(object.once); + return message; + }; + + /** + * Creates a plain object from a Target message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.Target + * @static + * @param {google.firestore.v1beta1.Target} message Target + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Target.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.targetId = 0; + object.once = false; + } + if (message.query != null && message.hasOwnProperty("query")) { + object.query = $root.google.firestore.v1beta1.Target.QueryTarget.toObject(message.query, options); + if (options.oneofs) + object.targetType = "query"; + } + if (message.documents != null && message.hasOwnProperty("documents")) { + object.documents = $root.google.firestore.v1beta1.Target.DocumentsTarget.toObject(message.documents, options); + if (options.oneofs) + object.targetType = "documents"; + } + if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) { + object.resumeToken = options.bytes === String ? $util.base64.encode(message.resumeToken, 0, message.resumeToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.resumeToken) : message.resumeToken; + if (options.oneofs) + object.resumeType = "resumeToken"; + } + if (message.targetId != null && message.hasOwnProperty("targetId")) + object.targetId = message.targetId; + if (message.once != null && message.hasOwnProperty("once")) + object.once = message.once; + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.resumeType = "readTime"; + } + return object; + }; + + /** + * Converts this Target to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.Target + * @instance + * @returns {Object.} JSON object + */ + Target.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Target + * @function getTypeUrl + * @memberof google.firestore.v1beta1.Target + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Target.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.Target"; + }; + + Target.DocumentsTarget = (function() { + + /** + * Properties of a DocumentsTarget. + * @memberof google.firestore.v1beta1.Target + * @interface IDocumentsTarget + * @property {Array.|null} [documents] DocumentsTarget documents + */ + + /** + * Constructs a new DocumentsTarget. + * @memberof google.firestore.v1beta1.Target + * @classdesc Represents a DocumentsTarget. + * @implements IDocumentsTarget + * @constructor + * @param {google.firestore.v1beta1.Target.IDocumentsTarget=} [properties] Properties to set + */ + function DocumentsTarget(properties) { + this.documents = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DocumentsTarget documents. + * @member {Array.} documents + * @memberof google.firestore.v1beta1.Target.DocumentsTarget + * @instance + */ + DocumentsTarget.prototype.documents = $util.emptyArray; + + /** + * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.Target.DocumentsTarget + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.Target.DocumentsTarget} DocumentsTarget + */ + DocumentsTarget.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.Target.DocumentsTarget) + return object; + var message = new $root.google.firestore.v1beta1.Target.DocumentsTarget(); + if (object.documents) { + if (!Array.isArray(object.documents)) + throw TypeError(".google.firestore.v1beta1.Target.DocumentsTarget.documents: array expected"); + message.documents = []; + for (var i = 0; i < object.documents.length; ++i) + message.documents[i] = String(object.documents[i]); + } + return message; + }; + + /** + * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.Target.DocumentsTarget + * @static + * @param {google.firestore.v1beta1.Target.DocumentsTarget} message DocumentsTarget + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DocumentsTarget.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.documents = []; + if (message.documents && message.documents.length) { + object.documents = []; + for (var j = 0; j < message.documents.length; ++j) + object.documents[j] = message.documents[j]; + } + return object; + }; + + /** + * Converts this DocumentsTarget to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.Target.DocumentsTarget + * @instance + * @returns {Object.} JSON object + */ + DocumentsTarget.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DocumentsTarget + * @function getTypeUrl + * @memberof google.firestore.v1beta1.Target.DocumentsTarget + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DocumentsTarget.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.Target.DocumentsTarget"; + }; + + return DocumentsTarget; + })(); + + Target.QueryTarget = (function() { + + /** + * Properties of a QueryTarget. + * @memberof google.firestore.v1beta1.Target + * @interface IQueryTarget + * @property {string|null} [parent] QueryTarget parent + * @property {google.firestore.v1beta1.IStructuredQuery|null} [structuredQuery] QueryTarget structuredQuery + */ + + /** + * Constructs a new QueryTarget. + * @memberof google.firestore.v1beta1.Target + * @classdesc Represents a QueryTarget. + * @implements IQueryTarget + * @constructor + * @param {google.firestore.v1beta1.Target.IQueryTarget=} [properties] Properties to set + */ + function QueryTarget(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * QueryTarget parent. + * @member {string} parent + * @memberof google.firestore.v1beta1.Target.QueryTarget + * @instance + */ + QueryTarget.prototype.parent = ""; + + /** + * QueryTarget structuredQuery. + * @member {google.firestore.v1beta1.IStructuredQuery|null|undefined} structuredQuery + * @memberof google.firestore.v1beta1.Target.QueryTarget + * @instance + */ + QueryTarget.prototype.structuredQuery = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * QueryTarget queryType. + * @member {"structuredQuery"|undefined} queryType + * @memberof google.firestore.v1beta1.Target.QueryTarget + * @instance + */ + Object.defineProperty(QueryTarget.prototype, "queryType", { + get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.Target.QueryTarget + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.Target.QueryTarget} QueryTarget + */ + QueryTarget.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.Target.QueryTarget) + return object; + var message = new $root.google.firestore.v1beta1.Target.QueryTarget(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.structuredQuery != null) { + if (typeof object.structuredQuery !== "object") + throw TypeError(".google.firestore.v1beta1.Target.QueryTarget.structuredQuery: object expected"); + message.structuredQuery = $root.google.firestore.v1beta1.StructuredQuery.fromObject(object.structuredQuery); + } + return message; + }; + + /** + * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.Target.QueryTarget + * @static + * @param {google.firestore.v1beta1.Target.QueryTarget} message QueryTarget + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + QueryTarget.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.parent = ""; + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { + object.structuredQuery = $root.google.firestore.v1beta1.StructuredQuery.toObject(message.structuredQuery, options); + if (options.oneofs) + object.queryType = "structuredQuery"; + } + return object; + }; + + /** + * Converts this QueryTarget to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.Target.QueryTarget + * @instance + * @returns {Object.} JSON object + */ + QueryTarget.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for QueryTarget + * @function getTypeUrl + * @memberof google.firestore.v1beta1.Target.QueryTarget + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + QueryTarget.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.Target.QueryTarget"; + }; + + return QueryTarget; + })(); + + return Target; + })(); + + v1beta1.TargetChange = (function() { + + /** + * Properties of a TargetChange. + * @memberof google.firestore.v1beta1 + * @interface ITargetChange + * @property {google.firestore.v1beta1.TargetChange.TargetChangeType|null} [targetChangeType] TargetChange targetChangeType + * @property {Array.|null} [targetIds] TargetChange targetIds + * @property {google.rpc.IStatus|null} [cause] TargetChange cause + * @property {Uint8Array|null} [resumeToken] TargetChange resumeToken + * @property {google.protobuf.ITimestamp|null} [readTime] TargetChange readTime + */ + + /** + * Constructs a new TargetChange. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a TargetChange. + * @implements ITargetChange + * @constructor + * @param {google.firestore.v1beta1.ITargetChange=} [properties] Properties to set + */ + function TargetChange(properties) { + this.targetIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TargetChange targetChangeType. + * @member {google.firestore.v1beta1.TargetChange.TargetChangeType} targetChangeType + * @memberof google.firestore.v1beta1.TargetChange + * @instance + */ + TargetChange.prototype.targetChangeType = 0; + + /** + * TargetChange targetIds. + * @member {Array.} targetIds + * @memberof google.firestore.v1beta1.TargetChange + * @instance + */ + TargetChange.prototype.targetIds = $util.emptyArray; + + /** + * TargetChange cause. + * @member {google.rpc.IStatus|null|undefined} cause + * @memberof google.firestore.v1beta1.TargetChange + * @instance + */ + TargetChange.prototype.cause = null; + + /** + * TargetChange resumeToken. + * @member {Uint8Array} resumeToken + * @memberof google.firestore.v1beta1.TargetChange + * @instance + */ + TargetChange.prototype.resumeToken = $util.newBuffer([]); + + /** + * TargetChange readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1beta1.TargetChange + * @instance + */ + TargetChange.prototype.readTime = null; + + /** + * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.TargetChange + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.TargetChange} TargetChange + */ + TargetChange.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.TargetChange) + return object; + var message = new $root.google.firestore.v1beta1.TargetChange(); + switch (object.targetChangeType) { + default: + if (typeof object.targetChangeType === "number") { + message.targetChangeType = object.targetChangeType; + break; + } + break; + case "NO_CHANGE": + case 0: + message.targetChangeType = 0; + break; + case "ADD": + case 1: + message.targetChangeType = 1; + break; + case "REMOVE": + case 2: + message.targetChangeType = 2; + break; + case "CURRENT": + case 3: + message.targetChangeType = 3; + break; + case "RESET": + case 4: + message.targetChangeType = 4; + break; + } + if (object.targetIds) { + if (!Array.isArray(object.targetIds)) + throw TypeError(".google.firestore.v1beta1.TargetChange.targetIds: array expected"); + message.targetIds = []; + for (var i = 0; i < object.targetIds.length; ++i) + message.targetIds[i] = object.targetIds[i] | 0; + } + if (object.cause != null) { + if (typeof object.cause !== "object") + throw TypeError(".google.firestore.v1beta1.TargetChange.cause: object expected"); + message.cause = $root.google.rpc.Status.fromObject(object.cause); + } + if (object.resumeToken != null) + if (typeof object.resumeToken === "string") + $util.base64.decode(object.resumeToken, message.resumeToken = $util.newBuffer($util.base64.length(object.resumeToken)), 0); + else if (object.resumeToken.length >= 0) + message.resumeToken = object.resumeToken; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1beta1.TargetChange.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a TargetChange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.TargetChange + * @static + * @param {google.firestore.v1beta1.TargetChange} message TargetChange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TargetChange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.targetIds = []; + if (options.defaults) { + object.targetChangeType = options.enums === String ? "NO_CHANGE" : 0; + object.cause = null; + if (options.bytes === String) + object.resumeToken = ""; + else { + object.resumeToken = []; + if (options.bytes !== Array) + object.resumeToken = $util.newBuffer(object.resumeToken); + } + object.readTime = null; + } + if (message.targetChangeType != null && message.hasOwnProperty("targetChangeType")) + object.targetChangeType = options.enums === String ? $root.google.firestore.v1beta1.TargetChange.TargetChangeType[message.targetChangeType] === undefined ? message.targetChangeType : $root.google.firestore.v1beta1.TargetChange.TargetChangeType[message.targetChangeType] : message.targetChangeType; + if (message.targetIds && message.targetIds.length) { + object.targetIds = []; + for (var j = 0; j < message.targetIds.length; ++j) + object.targetIds[j] = message.targetIds[j]; + } + if (message.cause != null && message.hasOwnProperty("cause")) + object.cause = $root.google.rpc.Status.toObject(message.cause, options); + if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) + object.resumeToken = options.bytes === String ? $util.base64.encode(message.resumeToken, 0, message.resumeToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.resumeToken) : message.resumeToken; + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + return object; + }; + + /** + * Converts this TargetChange to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.TargetChange + * @instance + * @returns {Object.} JSON object + */ + TargetChange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TargetChange + * @function getTypeUrl + * @memberof google.firestore.v1beta1.TargetChange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TargetChange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.TargetChange"; + }; + + /** + * TargetChangeType enum. + * @name google.firestore.v1beta1.TargetChange.TargetChangeType + * @enum {string} + * @property {string} NO_CHANGE=NO_CHANGE NO_CHANGE value + * @property {string} ADD=ADD ADD value + * @property {string} REMOVE=REMOVE REMOVE value + * @property {string} CURRENT=CURRENT CURRENT value + * @property {string} RESET=RESET RESET value + */ + TargetChange.TargetChangeType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "NO_CHANGE"] = "NO_CHANGE"; + values[valuesById[1] = "ADD"] = "ADD"; + values[valuesById[2] = "REMOVE"] = "REMOVE"; + values[valuesById[3] = "CURRENT"] = "CURRENT"; + values[valuesById[4] = "RESET"] = "RESET"; + return values; + })(); + + return TargetChange; + })(); + + v1beta1.ListCollectionIdsRequest = (function() { + + /** + * Properties of a ListCollectionIdsRequest. + * @memberof google.firestore.v1beta1 + * @interface IListCollectionIdsRequest + * @property {string|null} [parent] ListCollectionIdsRequest parent + * @property {number|null} [pageSize] ListCollectionIdsRequest pageSize + * @property {string|null} [pageToken] ListCollectionIdsRequest pageToken + */ + + /** + * Constructs a new ListCollectionIdsRequest. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a ListCollectionIdsRequest. + * @implements IListCollectionIdsRequest + * @constructor + * @param {google.firestore.v1beta1.IListCollectionIdsRequest=} [properties] Properties to set + */ + function ListCollectionIdsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListCollectionIdsRequest parent. + * @member {string} parent + * @memberof google.firestore.v1beta1.ListCollectionIdsRequest + * @instance + */ + ListCollectionIdsRequest.prototype.parent = ""; + + /** + * ListCollectionIdsRequest pageSize. + * @member {number} pageSize + * @memberof google.firestore.v1beta1.ListCollectionIdsRequest + * @instance + */ + ListCollectionIdsRequest.prototype.pageSize = 0; + + /** + * ListCollectionIdsRequest pageToken. + * @member {string} pageToken + * @memberof google.firestore.v1beta1.ListCollectionIdsRequest + * @instance + */ + ListCollectionIdsRequest.prototype.pageToken = ""; + + /** + * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.ListCollectionIdsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.ListCollectionIdsRequest} ListCollectionIdsRequest + */ + ListCollectionIdsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.ListCollectionIdsRequest) + return object; + var message = new $root.google.firestore.v1beta1.ListCollectionIdsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.ListCollectionIdsRequest + * @static + * @param {google.firestore.v1beta1.ListCollectionIdsRequest} message ListCollectionIdsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListCollectionIdsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListCollectionIdsRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.ListCollectionIdsRequest + * @instance + * @returns {Object.} JSON object + */ + ListCollectionIdsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListCollectionIdsRequest + * @function getTypeUrl + * @memberof google.firestore.v1beta1.ListCollectionIdsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListCollectionIdsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.ListCollectionIdsRequest"; + }; + + return ListCollectionIdsRequest; + })(); + + v1beta1.ListCollectionIdsResponse = (function() { + + /** + * Properties of a ListCollectionIdsResponse. + * @memberof google.firestore.v1beta1 + * @interface IListCollectionIdsResponse + * @property {Array.|null} [collectionIds] ListCollectionIdsResponse collectionIds + * @property {string|null} [nextPageToken] ListCollectionIdsResponse nextPageToken + */ + + /** + * Constructs a new ListCollectionIdsResponse. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a ListCollectionIdsResponse. + * @implements IListCollectionIdsResponse + * @constructor + * @param {google.firestore.v1beta1.IListCollectionIdsResponse=} [properties] Properties to set + */ + function ListCollectionIdsResponse(properties) { + this.collectionIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListCollectionIdsResponse collectionIds. + * @member {Array.} collectionIds + * @memberof google.firestore.v1beta1.ListCollectionIdsResponse + * @instance + */ + ListCollectionIdsResponse.prototype.collectionIds = $util.emptyArray; + + /** + * ListCollectionIdsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.firestore.v1beta1.ListCollectionIdsResponse + * @instance + */ + ListCollectionIdsResponse.prototype.nextPageToken = ""; + + /** + * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.ListCollectionIdsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.ListCollectionIdsResponse} ListCollectionIdsResponse + */ + ListCollectionIdsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.ListCollectionIdsResponse) + return object; + var message = new $root.google.firestore.v1beta1.ListCollectionIdsResponse(); + if (object.collectionIds) { + if (!Array.isArray(object.collectionIds)) + throw TypeError(".google.firestore.v1beta1.ListCollectionIdsResponse.collectionIds: array expected"); + message.collectionIds = []; + for (var i = 0; i < object.collectionIds.length; ++i) + message.collectionIds[i] = String(object.collectionIds[i]); + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.ListCollectionIdsResponse + * @static + * @param {google.firestore.v1beta1.ListCollectionIdsResponse} message ListCollectionIdsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListCollectionIdsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.collectionIds = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.collectionIds && message.collectionIds.length) { + object.collectionIds = []; + for (var j = 0; j < message.collectionIds.length; ++j) + object.collectionIds[j] = message.collectionIds[j]; + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListCollectionIdsResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.ListCollectionIdsResponse + * @instance + * @returns {Object.} JSON object + */ + ListCollectionIdsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListCollectionIdsResponse + * @function getTypeUrl + * @memberof google.firestore.v1beta1.ListCollectionIdsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListCollectionIdsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.ListCollectionIdsResponse"; + }; + + return ListCollectionIdsResponse; + })(); + + v1beta1.BatchWriteRequest = (function() { + + /** + * Properties of a BatchWriteRequest. + * @memberof google.firestore.v1beta1 + * @interface IBatchWriteRequest + * @property {string|null} [database] BatchWriteRequest database + * @property {Array.|null} [writes] BatchWriteRequest writes + * @property {Object.|null} [labels] BatchWriteRequest labels + */ + + /** + * Constructs a new BatchWriteRequest. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a BatchWriteRequest. + * @implements IBatchWriteRequest + * @constructor + * @param {google.firestore.v1beta1.IBatchWriteRequest=} [properties] Properties to set + */ + function BatchWriteRequest(properties) { + this.writes = []; + this.labels = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BatchWriteRequest database. + * @member {string} database + * @memberof google.firestore.v1beta1.BatchWriteRequest + * @instance + */ + BatchWriteRequest.prototype.database = ""; + + /** + * BatchWriteRequest writes. + * @member {Array.} writes + * @memberof google.firestore.v1beta1.BatchWriteRequest + * @instance + */ + BatchWriteRequest.prototype.writes = $util.emptyArray; + + /** + * BatchWriteRequest labels. + * @member {Object.} labels + * @memberof google.firestore.v1beta1.BatchWriteRequest + * @instance + */ + BatchWriteRequest.prototype.labels = $util.emptyObject; + + /** + * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.BatchWriteRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.BatchWriteRequest} BatchWriteRequest + */ + BatchWriteRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.BatchWriteRequest) + return object; + var message = new $root.google.firestore.v1beta1.BatchWriteRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.writes) { + if (!Array.isArray(object.writes)) + throw TypeError(".google.firestore.v1beta1.BatchWriteRequest.writes: array expected"); + message.writes = []; + for (var i = 0; i < object.writes.length; ++i) { + if (typeof object.writes[i] !== "object") + throw TypeError(".google.firestore.v1beta1.BatchWriteRequest.writes: object expected"); + message.writes[i] = $root.google.firestore.v1beta1.Write.fromObject(object.writes[i]); + } + } + if (object.labels) { + if (typeof object.labels !== "object") + throw TypeError(".google.firestore.v1beta1.BatchWriteRequest.labels: object expected"); + message.labels = {}; + for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) + message.labels[keys[i]] = String(object.labels[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.BatchWriteRequest + * @static + * @param {google.firestore.v1beta1.BatchWriteRequest} message BatchWriteRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchWriteRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.writes = []; + if (options.objects || options.defaults) + object.labels = {}; + if (options.defaults) + object.database = ""; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.writes && message.writes.length) { + object.writes = []; + for (var j = 0; j < message.writes.length; ++j) + object.writes[j] = $root.google.firestore.v1beta1.Write.toObject(message.writes[j], options); + } + var keys2; + if (message.labels && (keys2 = Object.keys(message.labels)).length) { + object.labels = {}; + for (var j = 0; j < keys2.length; ++j) + object.labels[keys2[j]] = message.labels[keys2[j]]; + } + return object; + }; + + /** + * Converts this BatchWriteRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.BatchWriteRequest + * @instance + * @returns {Object.} JSON object + */ + BatchWriteRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchWriteRequest + * @function getTypeUrl + * @memberof google.firestore.v1beta1.BatchWriteRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchWriteRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.BatchWriteRequest"; + }; + + return BatchWriteRequest; + })(); + + v1beta1.BatchWriteResponse = (function() { + + /** + * Properties of a BatchWriteResponse. + * @memberof google.firestore.v1beta1 + * @interface IBatchWriteResponse + * @property {Array.|null} [writeResults] BatchWriteResponse writeResults + * @property {Array.|null} [status] BatchWriteResponse status + */ + + /** + * Constructs a new BatchWriteResponse. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a BatchWriteResponse. + * @implements IBatchWriteResponse + * @constructor + * @param {google.firestore.v1beta1.IBatchWriteResponse=} [properties] Properties to set + */ + function BatchWriteResponse(properties) { + this.writeResults = []; + this.status = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BatchWriteResponse writeResults. + * @member {Array.} writeResults + * @memberof google.firestore.v1beta1.BatchWriteResponse + * @instance + */ + BatchWriteResponse.prototype.writeResults = $util.emptyArray; + + /** + * BatchWriteResponse status. + * @member {Array.} status + * @memberof google.firestore.v1beta1.BatchWriteResponse + * @instance + */ + BatchWriteResponse.prototype.status = $util.emptyArray; + + /** + * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.BatchWriteResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.BatchWriteResponse} BatchWriteResponse + */ + BatchWriteResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.BatchWriteResponse) + return object; + var message = new $root.google.firestore.v1beta1.BatchWriteResponse(); + if (object.writeResults) { + if (!Array.isArray(object.writeResults)) + throw TypeError(".google.firestore.v1beta1.BatchWriteResponse.writeResults: array expected"); + message.writeResults = []; + for (var i = 0; i < object.writeResults.length; ++i) { + if (typeof object.writeResults[i] !== "object") + throw TypeError(".google.firestore.v1beta1.BatchWriteResponse.writeResults: object expected"); + message.writeResults[i] = $root.google.firestore.v1beta1.WriteResult.fromObject(object.writeResults[i]); + } + } + if (object.status) { + if (!Array.isArray(object.status)) + throw TypeError(".google.firestore.v1beta1.BatchWriteResponse.status: array expected"); + message.status = []; + for (var i = 0; i < object.status.length; ++i) { + if (typeof object.status[i] !== "object") + throw TypeError(".google.firestore.v1beta1.BatchWriteResponse.status: object expected"); + message.status[i] = $root.google.rpc.Status.fromObject(object.status[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.BatchWriteResponse + * @static + * @param {google.firestore.v1beta1.BatchWriteResponse} message BatchWriteResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchWriteResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.writeResults = []; + object.status = []; + } + if (message.writeResults && message.writeResults.length) { + object.writeResults = []; + for (var j = 0; j < message.writeResults.length; ++j) + object.writeResults[j] = $root.google.firestore.v1beta1.WriteResult.toObject(message.writeResults[j], options); + } + if (message.status && message.status.length) { + object.status = []; + for (var j = 0; j < message.status.length; ++j) + object.status[j] = $root.google.rpc.Status.toObject(message.status[j], options); + } + return object; + }; + + /** + * Converts this BatchWriteResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.BatchWriteResponse + * @instance + * @returns {Object.} JSON object + */ + BatchWriteResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchWriteResponse + * @function getTypeUrl + * @memberof google.firestore.v1beta1.BatchWriteResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchWriteResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.BatchWriteResponse"; + }; + + return BatchWriteResponse; + })(); + + v1beta1.StructuredQuery = (function() { + + /** + * Properties of a StructuredQuery. + * @memberof google.firestore.v1beta1 + * @interface IStructuredQuery + * @property {google.firestore.v1beta1.StructuredQuery.IProjection|null} [select] StructuredQuery select + * @property {Array.|null} [from] StructuredQuery from + * @property {google.firestore.v1beta1.StructuredQuery.IFilter|null} [where] StructuredQuery where + * @property {Array.|null} [orderBy] StructuredQuery orderBy + * @property {google.firestore.v1beta1.ICursor|null} [startAt] StructuredQuery startAt + * @property {google.firestore.v1beta1.ICursor|null} [endAt] StructuredQuery endAt + * @property {number|null} [offset] StructuredQuery offset + * @property {google.protobuf.IInt32Value|null} [limit] StructuredQuery limit + */ + + /** + * Constructs a new StructuredQuery. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a StructuredQuery. + * @implements IStructuredQuery + * @constructor + * @param {google.firestore.v1beta1.IStructuredQuery=} [properties] Properties to set + */ + function StructuredQuery(properties) { + this.from = []; + this.orderBy = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * StructuredQuery select. + * @member {google.firestore.v1beta1.StructuredQuery.IProjection|null|undefined} select + * @memberof google.firestore.v1beta1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.select = null; + + /** + * StructuredQuery from. + * @member {Array.} from + * @memberof google.firestore.v1beta1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.from = $util.emptyArray; + + /** + * StructuredQuery where. + * @member {google.firestore.v1beta1.StructuredQuery.IFilter|null|undefined} where + * @memberof google.firestore.v1beta1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.where = null; + + /** + * StructuredQuery orderBy. + * @member {Array.} orderBy + * @memberof google.firestore.v1beta1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.orderBy = $util.emptyArray; + + /** + * StructuredQuery startAt. + * @member {google.firestore.v1beta1.ICursor|null|undefined} startAt + * @memberof google.firestore.v1beta1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.startAt = null; + + /** + * StructuredQuery endAt. + * @member {google.firestore.v1beta1.ICursor|null|undefined} endAt + * @memberof google.firestore.v1beta1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.endAt = null; + + /** + * StructuredQuery offset. + * @member {number} offset + * @memberof google.firestore.v1beta1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.offset = 0; + + /** + * StructuredQuery limit. + * @member {google.protobuf.IInt32Value|null|undefined} limit + * @memberof google.firestore.v1beta1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.limit = null; + + /** + * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.StructuredQuery + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.StructuredQuery} StructuredQuery + */ + StructuredQuery.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.StructuredQuery) + return object; + var message = new $root.google.firestore.v1beta1.StructuredQuery(); + if (object.select != null) { + if (typeof object.select !== "object") + throw TypeError(".google.firestore.v1beta1.StructuredQuery.select: object expected"); + message.select = $root.google.firestore.v1beta1.StructuredQuery.Projection.fromObject(object.select); + } + if (object.from) { + if (!Array.isArray(object.from)) + throw TypeError(".google.firestore.v1beta1.StructuredQuery.from: array expected"); + message.from = []; + for (var i = 0; i < object.from.length; ++i) { + if (typeof object.from[i] !== "object") + throw TypeError(".google.firestore.v1beta1.StructuredQuery.from: object expected"); + message.from[i] = $root.google.firestore.v1beta1.StructuredQuery.CollectionSelector.fromObject(object.from[i]); + } + } + if (object.where != null) { + if (typeof object.where !== "object") + throw TypeError(".google.firestore.v1beta1.StructuredQuery.where: object expected"); + message.where = $root.google.firestore.v1beta1.StructuredQuery.Filter.fromObject(object.where); + } + if (object.orderBy) { + if (!Array.isArray(object.orderBy)) + throw TypeError(".google.firestore.v1beta1.StructuredQuery.orderBy: array expected"); + message.orderBy = []; + for (var i = 0; i < object.orderBy.length; ++i) { + if (typeof object.orderBy[i] !== "object") + throw TypeError(".google.firestore.v1beta1.StructuredQuery.orderBy: object expected"); + message.orderBy[i] = $root.google.firestore.v1beta1.StructuredQuery.Order.fromObject(object.orderBy[i]); + } + } + if (object.startAt != null) { + if (typeof object.startAt !== "object") + throw TypeError(".google.firestore.v1beta1.StructuredQuery.startAt: object expected"); + message.startAt = $root.google.firestore.v1beta1.Cursor.fromObject(object.startAt); + } + if (object.endAt != null) { + if (typeof object.endAt !== "object") + throw TypeError(".google.firestore.v1beta1.StructuredQuery.endAt: object expected"); + message.endAt = $root.google.firestore.v1beta1.Cursor.fromObject(object.endAt); + } + if (object.offset != null) + message.offset = object.offset | 0; + if (object.limit != null) { + if (typeof object.limit !== "object") + throw TypeError(".google.firestore.v1beta1.StructuredQuery.limit: object expected"); + message.limit = $root.google.protobuf.Int32Value.fromObject(object.limit); + } + return message; + }; + + /** + * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.StructuredQuery + * @static + * @param {google.firestore.v1beta1.StructuredQuery} message StructuredQuery + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + StructuredQuery.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.from = []; + object.orderBy = []; + } + if (options.defaults) { + object.select = null; + object.where = null; + object.limit = null; + object.offset = 0; + object.startAt = null; + object.endAt = null; + } + if (message.select != null && message.hasOwnProperty("select")) + object.select = $root.google.firestore.v1beta1.StructuredQuery.Projection.toObject(message.select, options); + if (message.from && message.from.length) { + object.from = []; + for (var j = 0; j < message.from.length; ++j) + object.from[j] = $root.google.firestore.v1beta1.StructuredQuery.CollectionSelector.toObject(message.from[j], options); + } + if (message.where != null && message.hasOwnProperty("where")) + object.where = $root.google.firestore.v1beta1.StructuredQuery.Filter.toObject(message.where, options); + if (message.orderBy && message.orderBy.length) { + object.orderBy = []; + for (var j = 0; j < message.orderBy.length; ++j) + object.orderBy[j] = $root.google.firestore.v1beta1.StructuredQuery.Order.toObject(message.orderBy[j], options); + } + if (message.limit != null && message.hasOwnProperty("limit")) + object.limit = $root.google.protobuf.Int32Value.toObject(message.limit, options); + if (message.offset != null && message.hasOwnProperty("offset")) + object.offset = message.offset; + if (message.startAt != null && message.hasOwnProperty("startAt")) + object.startAt = $root.google.firestore.v1beta1.Cursor.toObject(message.startAt, options); + if (message.endAt != null && message.hasOwnProperty("endAt")) + object.endAt = $root.google.firestore.v1beta1.Cursor.toObject(message.endAt, options); + return object; + }; + + /** + * Converts this StructuredQuery to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.StructuredQuery + * @instance + * @returns {Object.} JSON object + */ + StructuredQuery.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for StructuredQuery + * @function getTypeUrl + * @memberof google.firestore.v1beta1.StructuredQuery + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + StructuredQuery.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.StructuredQuery"; + }; + + StructuredQuery.CollectionSelector = (function() { + + /** + * Properties of a CollectionSelector. + * @memberof google.firestore.v1beta1.StructuredQuery + * @interface ICollectionSelector + * @property {string|null} [collectionId] CollectionSelector collectionId + * @property {boolean|null} [allDescendants] CollectionSelector allDescendants + */ + + /** + * Constructs a new CollectionSelector. + * @memberof google.firestore.v1beta1.StructuredQuery + * @classdesc Represents a CollectionSelector. + * @implements ICollectionSelector + * @constructor + * @param {google.firestore.v1beta1.StructuredQuery.ICollectionSelector=} [properties] Properties to set + */ + function CollectionSelector(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CollectionSelector collectionId. + * @member {string} collectionId + * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector + * @instance + */ + CollectionSelector.prototype.collectionId = ""; + + /** + * CollectionSelector allDescendants. + * @member {boolean} allDescendants + * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector + * @instance + */ + CollectionSelector.prototype.allDescendants = false; + + /** + * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.StructuredQuery.CollectionSelector} CollectionSelector + */ + CollectionSelector.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.StructuredQuery.CollectionSelector) + return object; + var message = new $root.google.firestore.v1beta1.StructuredQuery.CollectionSelector(); + if (object.collectionId != null) + message.collectionId = String(object.collectionId); + if (object.allDescendants != null) + message.allDescendants = Boolean(object.allDescendants); + return message; + }; + + /** + * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector + * @static + * @param {google.firestore.v1beta1.StructuredQuery.CollectionSelector} message CollectionSelector + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CollectionSelector.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.collectionId = ""; + object.allDescendants = false; + } + if (message.collectionId != null && message.hasOwnProperty("collectionId")) + object.collectionId = message.collectionId; + if (message.allDescendants != null && message.hasOwnProperty("allDescendants")) + object.allDescendants = message.allDescendants; + return object; + }; + + /** + * Converts this CollectionSelector to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector + * @instance + * @returns {Object.} JSON object + */ + CollectionSelector.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CollectionSelector + * @function getTypeUrl + * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CollectionSelector.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.StructuredQuery.CollectionSelector"; + }; + + return CollectionSelector; + })(); + + StructuredQuery.Filter = (function() { + + /** + * Properties of a Filter. + * @memberof google.firestore.v1beta1.StructuredQuery + * @interface IFilter + * @property {google.firestore.v1beta1.StructuredQuery.ICompositeFilter|null} [compositeFilter] Filter compositeFilter + * @property {google.firestore.v1beta1.StructuredQuery.IFieldFilter|null} [fieldFilter] Filter fieldFilter + * @property {google.firestore.v1beta1.StructuredQuery.IUnaryFilter|null} [unaryFilter] Filter unaryFilter + */ + + /** + * Constructs a new Filter. + * @memberof google.firestore.v1beta1.StructuredQuery + * @classdesc Represents a Filter. + * @implements IFilter + * @constructor + * @param {google.firestore.v1beta1.StructuredQuery.IFilter=} [properties] Properties to set + */ + function Filter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Filter compositeFilter. + * @member {google.firestore.v1beta1.StructuredQuery.ICompositeFilter|null|undefined} compositeFilter + * @memberof google.firestore.v1beta1.StructuredQuery.Filter + * @instance + */ + Filter.prototype.compositeFilter = null; + + /** + * Filter fieldFilter. + * @member {google.firestore.v1beta1.StructuredQuery.IFieldFilter|null|undefined} fieldFilter + * @memberof google.firestore.v1beta1.StructuredQuery.Filter + * @instance + */ + Filter.prototype.fieldFilter = null; + + /** + * Filter unaryFilter. + * @member {google.firestore.v1beta1.StructuredQuery.IUnaryFilter|null|undefined} unaryFilter + * @memberof google.firestore.v1beta1.StructuredQuery.Filter + * @instance + */ + Filter.prototype.unaryFilter = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Filter filterType. + * @member {"compositeFilter"|"fieldFilter"|"unaryFilter"|undefined} filterType + * @memberof google.firestore.v1beta1.StructuredQuery.Filter + * @instance + */ + Object.defineProperty(Filter.prototype, "filterType", { + get: $util.oneOfGetter($oneOfFields = ["compositeFilter", "fieldFilter", "unaryFilter"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a Filter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.StructuredQuery.Filter + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.StructuredQuery.Filter} Filter + */ + Filter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.StructuredQuery.Filter) + return object; + var message = new $root.google.firestore.v1beta1.StructuredQuery.Filter(); + if (object.compositeFilter != null) { + if (typeof object.compositeFilter !== "object") + throw TypeError(".google.firestore.v1beta1.StructuredQuery.Filter.compositeFilter: object expected"); + message.compositeFilter = $root.google.firestore.v1beta1.StructuredQuery.CompositeFilter.fromObject(object.compositeFilter); + } + if (object.fieldFilter != null) { + if (typeof object.fieldFilter !== "object") + throw TypeError(".google.firestore.v1beta1.StructuredQuery.Filter.fieldFilter: object expected"); + message.fieldFilter = $root.google.firestore.v1beta1.StructuredQuery.FieldFilter.fromObject(object.fieldFilter); + } + if (object.unaryFilter != null) { + if (typeof object.unaryFilter !== "object") + throw TypeError(".google.firestore.v1beta1.StructuredQuery.Filter.unaryFilter: object expected"); + message.unaryFilter = $root.google.firestore.v1beta1.StructuredQuery.UnaryFilter.fromObject(object.unaryFilter); + } + return message; + }; + + /** + * Creates a plain object from a Filter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.StructuredQuery.Filter + * @static + * @param {google.firestore.v1beta1.StructuredQuery.Filter} message Filter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Filter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.compositeFilter != null && message.hasOwnProperty("compositeFilter")) { + object.compositeFilter = $root.google.firestore.v1beta1.StructuredQuery.CompositeFilter.toObject(message.compositeFilter, options); + if (options.oneofs) + object.filterType = "compositeFilter"; + } + if (message.fieldFilter != null && message.hasOwnProperty("fieldFilter")) { + object.fieldFilter = $root.google.firestore.v1beta1.StructuredQuery.FieldFilter.toObject(message.fieldFilter, options); + if (options.oneofs) + object.filterType = "fieldFilter"; + } + if (message.unaryFilter != null && message.hasOwnProperty("unaryFilter")) { + object.unaryFilter = $root.google.firestore.v1beta1.StructuredQuery.UnaryFilter.toObject(message.unaryFilter, options); + if (options.oneofs) + object.filterType = "unaryFilter"; + } + return object; + }; + + /** + * Converts this Filter to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.StructuredQuery.Filter + * @instance + * @returns {Object.} JSON object + */ + Filter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Filter + * @function getTypeUrl + * @memberof google.firestore.v1beta1.StructuredQuery.Filter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Filter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.StructuredQuery.Filter"; + }; + + return Filter; + })(); + + StructuredQuery.CompositeFilter = (function() { + + /** + * Properties of a CompositeFilter. + * @memberof google.firestore.v1beta1.StructuredQuery + * @interface ICompositeFilter + * @property {google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator|null} [op] CompositeFilter op + * @property {Array.|null} [filters] CompositeFilter filters + */ + + /** + * Constructs a new CompositeFilter. + * @memberof google.firestore.v1beta1.StructuredQuery + * @classdesc Represents a CompositeFilter. + * @implements ICompositeFilter + * @constructor + * @param {google.firestore.v1beta1.StructuredQuery.ICompositeFilter=} [properties] Properties to set + */ + function CompositeFilter(properties) { + this.filters = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CompositeFilter op. + * @member {google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator} op + * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter + * @instance + */ + CompositeFilter.prototype.op = 0; + + /** + * CompositeFilter filters. + * @member {Array.} filters + * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter + * @instance + */ + CompositeFilter.prototype.filters = $util.emptyArray; + + /** + * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.StructuredQuery.CompositeFilter} CompositeFilter + */ + CompositeFilter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.StructuredQuery.CompositeFilter) + return object; + var message = new $root.google.firestore.v1beta1.StructuredQuery.CompositeFilter(); + switch (object.op) { + default: + if (typeof object.op === "number") { + message.op = object.op; + break; + } + break; + case "OPERATOR_UNSPECIFIED": + case 0: + message.op = 0; + break; + case "AND": + case 1: + message.op = 1; + break; + } + if (object.filters) { + if (!Array.isArray(object.filters)) + throw TypeError(".google.firestore.v1beta1.StructuredQuery.CompositeFilter.filters: array expected"); + message.filters = []; + for (var i = 0; i < object.filters.length; ++i) { + if (typeof object.filters[i] !== "object") + throw TypeError(".google.firestore.v1beta1.StructuredQuery.CompositeFilter.filters: object expected"); + message.filters[i] = $root.google.firestore.v1beta1.StructuredQuery.Filter.fromObject(object.filters[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter + * @static + * @param {google.firestore.v1beta1.StructuredQuery.CompositeFilter} message CompositeFilter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CompositeFilter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.filters = []; + if (options.defaults) + object.op = options.enums === String ? "OPERATOR_UNSPECIFIED" : 0; + if (message.op != null && message.hasOwnProperty("op")) + object.op = options.enums === String ? $root.google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator[message.op] === undefined ? message.op : $root.google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator[message.op] : message.op; + if (message.filters && message.filters.length) { + object.filters = []; + for (var j = 0; j < message.filters.length; ++j) + object.filters[j] = $root.google.firestore.v1beta1.StructuredQuery.Filter.toObject(message.filters[j], options); + } + return object; + }; + + /** + * Converts this CompositeFilter to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter + * @instance + * @returns {Object.} JSON object + */ + CompositeFilter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CompositeFilter + * @function getTypeUrl + * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CompositeFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.StructuredQuery.CompositeFilter"; + }; + + /** + * Operator enum. + * @name google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator + * @enum {string} + * @property {string} OPERATOR_UNSPECIFIED=OPERATOR_UNSPECIFIED OPERATOR_UNSPECIFIED value + * @property {string} AND=AND AND value + */ + CompositeFilter.Operator = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "OPERATOR_UNSPECIFIED"] = "OPERATOR_UNSPECIFIED"; + values[valuesById[1] = "AND"] = "AND"; + return values; + })(); + + return CompositeFilter; + })(); + + StructuredQuery.FieldFilter = (function() { + + /** + * Properties of a FieldFilter. + * @memberof google.firestore.v1beta1.StructuredQuery + * @interface IFieldFilter + * @property {google.firestore.v1beta1.StructuredQuery.IFieldReference|null} [field] FieldFilter field + * @property {google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator|null} [op] FieldFilter op + * @property {google.firestore.v1beta1.IValue|null} [value] FieldFilter value + */ + + /** + * Constructs a new FieldFilter. + * @memberof google.firestore.v1beta1.StructuredQuery + * @classdesc Represents a FieldFilter. + * @implements IFieldFilter + * @constructor + * @param {google.firestore.v1beta1.StructuredQuery.IFieldFilter=} [properties] Properties to set + */ + function FieldFilter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldFilter field. + * @member {google.firestore.v1beta1.StructuredQuery.IFieldReference|null|undefined} field + * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter + * @instance + */ + FieldFilter.prototype.field = null; + + /** + * FieldFilter op. + * @member {google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator} op + * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter + * @instance + */ + FieldFilter.prototype.op = 0; + + /** + * FieldFilter value. + * @member {google.firestore.v1beta1.IValue|null|undefined} value + * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter + * @instance + */ + FieldFilter.prototype.value = null; + + /** + * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.StructuredQuery.FieldFilter} FieldFilter + */ + FieldFilter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.StructuredQuery.FieldFilter) + return object; + var message = new $root.google.firestore.v1beta1.StructuredQuery.FieldFilter(); + if (object.field != null) { + if (typeof object.field !== "object") + throw TypeError(".google.firestore.v1beta1.StructuredQuery.FieldFilter.field: object expected"); + message.field = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.fromObject(object.field); + } + switch (object.op) { + default: + if (typeof object.op === "number") { + message.op = object.op; + break; + } + break; + case "OPERATOR_UNSPECIFIED": + case 0: + message.op = 0; + break; + case "LESS_THAN": + case 1: + message.op = 1; + break; + case "LESS_THAN_OR_EQUAL": + case 2: + message.op = 2; + break; + case "GREATER_THAN": + case 3: + message.op = 3; + break; + case "GREATER_THAN_OR_EQUAL": + case 4: + message.op = 4; + break; + case "EQUAL": + case 5: + message.op = 5; + break; + case "NOT_EQUAL": + case 6: + message.op = 6; + break; + case "ARRAY_CONTAINS": + case 7: + message.op = 7; + break; + case "IN": + case 8: + message.op = 8; + break; + case "ARRAY_CONTAINS_ANY": + case 9: + message.op = 9; + break; + case "NOT_IN": + case 10: + message.op = 10; + break; + } + if (object.value != null) { + if (typeof object.value !== "object") + throw TypeError(".google.firestore.v1beta1.StructuredQuery.FieldFilter.value: object expected"); + message.value = $root.google.firestore.v1beta1.Value.fromObject(object.value); + } + return message; + }; + + /** + * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter + * @static + * @param {google.firestore.v1beta1.StructuredQuery.FieldFilter} message FieldFilter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldFilter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.field = null; + object.op = options.enums === String ? "OPERATOR_UNSPECIFIED" : 0; + object.value = null; + } + if (message.field != null && message.hasOwnProperty("field")) + object.field = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.toObject(message.field, options); + if (message.op != null && message.hasOwnProperty("op")) + object.op = options.enums === String ? $root.google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator[message.op] === undefined ? message.op : $root.google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator[message.op] : message.op; + if (message.value != null && message.hasOwnProperty("value")) + object.value = $root.google.firestore.v1beta1.Value.toObject(message.value, options); + return object; + }; + + /** + * Converts this FieldFilter to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter + * @instance + * @returns {Object.} JSON object + */ + FieldFilter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldFilter + * @function getTypeUrl + * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.StructuredQuery.FieldFilter"; + }; + + /** + * Operator enum. + * @name google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator + * @enum {string} + * @property {string} OPERATOR_UNSPECIFIED=OPERATOR_UNSPECIFIED OPERATOR_UNSPECIFIED value + * @property {string} LESS_THAN=LESS_THAN LESS_THAN value + * @property {string} LESS_THAN_OR_EQUAL=LESS_THAN_OR_EQUAL LESS_THAN_OR_EQUAL value + * @property {string} GREATER_THAN=GREATER_THAN GREATER_THAN value + * @property {string} GREATER_THAN_OR_EQUAL=GREATER_THAN_OR_EQUAL GREATER_THAN_OR_EQUAL value + * @property {string} EQUAL=EQUAL EQUAL value + * @property {string} NOT_EQUAL=NOT_EQUAL NOT_EQUAL value + * @property {string} ARRAY_CONTAINS=ARRAY_CONTAINS ARRAY_CONTAINS value + * @property {string} IN=IN IN value + * @property {string} ARRAY_CONTAINS_ANY=ARRAY_CONTAINS_ANY ARRAY_CONTAINS_ANY value + * @property {string} NOT_IN=NOT_IN NOT_IN value + */ + FieldFilter.Operator = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "OPERATOR_UNSPECIFIED"] = "OPERATOR_UNSPECIFIED"; + values[valuesById[1] = "LESS_THAN"] = "LESS_THAN"; + values[valuesById[2] = "LESS_THAN_OR_EQUAL"] = "LESS_THAN_OR_EQUAL"; + values[valuesById[3] = "GREATER_THAN"] = "GREATER_THAN"; + values[valuesById[4] = "GREATER_THAN_OR_EQUAL"] = "GREATER_THAN_OR_EQUAL"; + values[valuesById[5] = "EQUAL"] = "EQUAL"; + values[valuesById[6] = "NOT_EQUAL"] = "NOT_EQUAL"; + values[valuesById[7] = "ARRAY_CONTAINS"] = "ARRAY_CONTAINS"; + values[valuesById[8] = "IN"] = "IN"; + values[valuesById[9] = "ARRAY_CONTAINS_ANY"] = "ARRAY_CONTAINS_ANY"; + values[valuesById[10] = "NOT_IN"] = "NOT_IN"; + return values; + })(); + + return FieldFilter; + })(); + + StructuredQuery.UnaryFilter = (function() { + + /** + * Properties of an UnaryFilter. + * @memberof google.firestore.v1beta1.StructuredQuery + * @interface IUnaryFilter + * @property {google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator|null} [op] UnaryFilter op + * @property {google.firestore.v1beta1.StructuredQuery.IFieldReference|null} [field] UnaryFilter field + */ + + /** + * Constructs a new UnaryFilter. + * @memberof google.firestore.v1beta1.StructuredQuery + * @classdesc Represents an UnaryFilter. + * @implements IUnaryFilter + * @constructor + * @param {google.firestore.v1beta1.StructuredQuery.IUnaryFilter=} [properties] Properties to set + */ + function UnaryFilter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UnaryFilter op. + * @member {google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator} op + * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter + * @instance + */ + UnaryFilter.prototype.op = 0; + + /** + * UnaryFilter field. + * @member {google.firestore.v1beta1.StructuredQuery.IFieldReference|null|undefined} field + * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter + * @instance + */ + UnaryFilter.prototype.field = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * UnaryFilter operandType. + * @member {"field"|undefined} operandType + * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter + * @instance + */ + Object.defineProperty(UnaryFilter.prototype, "operandType", { + get: $util.oneOfGetter($oneOfFields = ["field"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.StructuredQuery.UnaryFilter} UnaryFilter + */ + UnaryFilter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.StructuredQuery.UnaryFilter) + return object; + var message = new $root.google.firestore.v1beta1.StructuredQuery.UnaryFilter(); + switch (object.op) { + default: + if (typeof object.op === "number") { + message.op = object.op; + break; + } + break; + case "OPERATOR_UNSPECIFIED": + case 0: + message.op = 0; + break; + case "IS_NAN": + case 2: + message.op = 2; + break; + case "IS_NULL": + case 3: + message.op = 3; + break; + case "IS_NOT_NAN": + case 4: + message.op = 4; + break; + case "IS_NOT_NULL": + case 5: + message.op = 5; + break; + } + if (object.field != null) { + if (typeof object.field !== "object") + throw TypeError(".google.firestore.v1beta1.StructuredQuery.UnaryFilter.field: object expected"); + message.field = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.fromObject(object.field); + } + return message; + }; + + /** + * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter + * @static + * @param {google.firestore.v1beta1.StructuredQuery.UnaryFilter} message UnaryFilter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UnaryFilter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.op = options.enums === String ? "OPERATOR_UNSPECIFIED" : 0; + if (message.op != null && message.hasOwnProperty("op")) + object.op = options.enums === String ? $root.google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator[message.op] === undefined ? message.op : $root.google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator[message.op] : message.op; + if (message.field != null && message.hasOwnProperty("field")) { + object.field = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.toObject(message.field, options); + if (options.oneofs) + object.operandType = "field"; + } + return object; + }; + + /** + * Converts this UnaryFilter to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter + * @instance + * @returns {Object.} JSON object + */ + UnaryFilter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UnaryFilter + * @function getTypeUrl + * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UnaryFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.StructuredQuery.UnaryFilter"; + }; + + /** + * Operator enum. + * @name google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator + * @enum {string} + * @property {string} OPERATOR_UNSPECIFIED=OPERATOR_UNSPECIFIED OPERATOR_UNSPECIFIED value + * @property {string} IS_NAN=IS_NAN IS_NAN value + * @property {string} IS_NULL=IS_NULL IS_NULL value + * @property {string} IS_NOT_NAN=IS_NOT_NAN IS_NOT_NAN value + * @property {string} IS_NOT_NULL=IS_NOT_NULL IS_NOT_NULL value + */ + UnaryFilter.Operator = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "OPERATOR_UNSPECIFIED"] = "OPERATOR_UNSPECIFIED"; + values[valuesById[2] = "IS_NAN"] = "IS_NAN"; + values[valuesById[3] = "IS_NULL"] = "IS_NULL"; + values[valuesById[4] = "IS_NOT_NAN"] = "IS_NOT_NAN"; + values[valuesById[5] = "IS_NOT_NULL"] = "IS_NOT_NULL"; + return values; + })(); + + return UnaryFilter; + })(); + + StructuredQuery.FieldReference = (function() { + + /** + * Properties of a FieldReference. + * @memberof google.firestore.v1beta1.StructuredQuery + * @interface IFieldReference + * @property {string|null} [fieldPath] FieldReference fieldPath + */ + + /** + * Constructs a new FieldReference. + * @memberof google.firestore.v1beta1.StructuredQuery + * @classdesc Represents a FieldReference. + * @implements IFieldReference + * @constructor + * @param {google.firestore.v1beta1.StructuredQuery.IFieldReference=} [properties] Properties to set + */ + function FieldReference(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldReference fieldPath. + * @member {string} fieldPath + * @memberof google.firestore.v1beta1.StructuredQuery.FieldReference + * @instance + */ + FieldReference.prototype.fieldPath = ""; + + /** + * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.StructuredQuery.FieldReference + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.StructuredQuery.FieldReference} FieldReference + */ + FieldReference.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.StructuredQuery.FieldReference) + return object; + var message = new $root.google.firestore.v1beta1.StructuredQuery.FieldReference(); + if (object.fieldPath != null) + message.fieldPath = String(object.fieldPath); + return message; + }; + + /** + * Creates a plain object from a FieldReference message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.StructuredQuery.FieldReference + * @static + * @param {google.firestore.v1beta1.StructuredQuery.FieldReference} message FieldReference + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldReference.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.fieldPath = ""; + if (message.fieldPath != null && message.hasOwnProperty("fieldPath")) + object.fieldPath = message.fieldPath; + return object; + }; + + /** + * Converts this FieldReference to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.StructuredQuery.FieldReference + * @instance + * @returns {Object.} JSON object + */ + FieldReference.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldReference + * @function getTypeUrl + * @memberof google.firestore.v1beta1.StructuredQuery.FieldReference + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldReference.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.StructuredQuery.FieldReference"; + }; + + return FieldReference; + })(); + + StructuredQuery.Order = (function() { + + /** + * Properties of an Order. + * @memberof google.firestore.v1beta1.StructuredQuery + * @interface IOrder + * @property {google.firestore.v1beta1.StructuredQuery.IFieldReference|null} [field] Order field + * @property {google.firestore.v1beta1.StructuredQuery.Direction|null} [direction] Order direction + */ + + /** + * Constructs a new Order. + * @memberof google.firestore.v1beta1.StructuredQuery + * @classdesc Represents an Order. + * @implements IOrder + * @constructor + * @param {google.firestore.v1beta1.StructuredQuery.IOrder=} [properties] Properties to set + */ + function Order(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Order field. + * @member {google.firestore.v1beta1.StructuredQuery.IFieldReference|null|undefined} field + * @memberof google.firestore.v1beta1.StructuredQuery.Order + * @instance + */ + Order.prototype.field = null; + + /** + * Order direction. + * @member {google.firestore.v1beta1.StructuredQuery.Direction} direction + * @memberof google.firestore.v1beta1.StructuredQuery.Order + * @instance + */ + Order.prototype.direction = 0; + + /** + * Creates an Order message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.StructuredQuery.Order + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.StructuredQuery.Order} Order + */ + Order.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.StructuredQuery.Order) + return object; + var message = new $root.google.firestore.v1beta1.StructuredQuery.Order(); + if (object.field != null) { + if (typeof object.field !== "object") + throw TypeError(".google.firestore.v1beta1.StructuredQuery.Order.field: object expected"); + message.field = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.fromObject(object.field); + } + switch (object.direction) { + default: + if (typeof object.direction === "number") { + message.direction = object.direction; + break; + } + break; + case "DIRECTION_UNSPECIFIED": + case 0: + message.direction = 0; + break; + case "ASCENDING": + case 1: + message.direction = 1; + break; + case "DESCENDING": + case 2: + message.direction = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from an Order message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.StructuredQuery.Order + * @static + * @param {google.firestore.v1beta1.StructuredQuery.Order} message Order + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Order.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.field = null; + object.direction = options.enums === String ? "DIRECTION_UNSPECIFIED" : 0; + } + if (message.field != null && message.hasOwnProperty("field")) + object.field = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.toObject(message.field, options); + if (message.direction != null && message.hasOwnProperty("direction")) + object.direction = options.enums === String ? $root.google.firestore.v1beta1.StructuredQuery.Direction[message.direction] === undefined ? message.direction : $root.google.firestore.v1beta1.StructuredQuery.Direction[message.direction] : message.direction; + return object; + }; + + /** + * Converts this Order to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.StructuredQuery.Order + * @instance + * @returns {Object.} JSON object + */ + Order.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Order + * @function getTypeUrl + * @memberof google.firestore.v1beta1.StructuredQuery.Order + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Order.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.StructuredQuery.Order"; + }; + + return Order; + })(); + + StructuredQuery.Projection = (function() { + + /** + * Properties of a Projection. + * @memberof google.firestore.v1beta1.StructuredQuery + * @interface IProjection + * @property {Array.|null} [fields] Projection fields + */ + + /** + * Constructs a new Projection. + * @memberof google.firestore.v1beta1.StructuredQuery + * @classdesc Represents a Projection. + * @implements IProjection + * @constructor + * @param {google.firestore.v1beta1.StructuredQuery.IProjection=} [properties] Properties to set + */ + function Projection(properties) { + this.fields = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Projection fields. + * @member {Array.} fields + * @memberof google.firestore.v1beta1.StructuredQuery.Projection + * @instance + */ + Projection.prototype.fields = $util.emptyArray; + + /** + * Creates a Projection message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.StructuredQuery.Projection + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.StructuredQuery.Projection} Projection + */ + Projection.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.StructuredQuery.Projection) + return object; + var message = new $root.google.firestore.v1beta1.StructuredQuery.Projection(); + if (object.fields) { + if (!Array.isArray(object.fields)) + throw TypeError(".google.firestore.v1beta1.StructuredQuery.Projection.fields: array expected"); + message.fields = []; + for (var i = 0; i < object.fields.length; ++i) { + if (typeof object.fields[i] !== "object") + throw TypeError(".google.firestore.v1beta1.StructuredQuery.Projection.fields: object expected"); + message.fields[i] = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.fromObject(object.fields[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a Projection message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.StructuredQuery.Projection + * @static + * @param {google.firestore.v1beta1.StructuredQuery.Projection} message Projection + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Projection.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.fields = []; + if (message.fields && message.fields.length) { + object.fields = []; + for (var j = 0; j < message.fields.length; ++j) + object.fields[j] = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.toObject(message.fields[j], options); + } + return object; + }; + + /** + * Converts this Projection to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.StructuredQuery.Projection + * @instance + * @returns {Object.} JSON object + */ + Projection.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Projection + * @function getTypeUrl + * @memberof google.firestore.v1beta1.StructuredQuery.Projection + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Projection.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.StructuredQuery.Projection"; + }; + + return Projection; + })(); + + /** + * Direction enum. + * @name google.firestore.v1beta1.StructuredQuery.Direction + * @enum {string} + * @property {string} DIRECTION_UNSPECIFIED=DIRECTION_UNSPECIFIED DIRECTION_UNSPECIFIED value + * @property {string} ASCENDING=ASCENDING ASCENDING value + * @property {string} DESCENDING=DESCENDING DESCENDING value + */ + StructuredQuery.Direction = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DIRECTION_UNSPECIFIED"] = "DIRECTION_UNSPECIFIED"; + values[valuesById[1] = "ASCENDING"] = "ASCENDING"; + values[valuesById[2] = "DESCENDING"] = "DESCENDING"; + return values; + })(); + + return StructuredQuery; + })(); + + v1beta1.Cursor = (function() { + + /** + * Properties of a Cursor. + * @memberof google.firestore.v1beta1 + * @interface ICursor + * @property {Array.|null} [values] Cursor values + * @property {boolean|null} [before] Cursor before + */ + + /** + * Constructs a new Cursor. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a Cursor. + * @implements ICursor + * @constructor + * @param {google.firestore.v1beta1.ICursor=} [properties] Properties to set + */ + function Cursor(properties) { + this.values = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Cursor values. + * @member {Array.} values + * @memberof google.firestore.v1beta1.Cursor + * @instance + */ + Cursor.prototype.values = $util.emptyArray; + + /** + * Cursor before. + * @member {boolean} before + * @memberof google.firestore.v1beta1.Cursor + * @instance + */ + Cursor.prototype.before = false; + + /** + * Creates a Cursor message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.Cursor + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.Cursor} Cursor + */ + Cursor.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.Cursor) + return object; + var message = new $root.google.firestore.v1beta1.Cursor(); + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".google.firestore.v1beta1.Cursor.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".google.firestore.v1beta1.Cursor.values: object expected"); + message.values[i] = $root.google.firestore.v1beta1.Value.fromObject(object.values[i]); + } + } + if (object.before != null) + message.before = Boolean(object.before); + return message; + }; + + /** + * Creates a plain object from a Cursor message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.Cursor + * @static + * @param {google.firestore.v1beta1.Cursor} message Cursor + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Cursor.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.values = []; + if (options.defaults) + object.before = false; + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.google.firestore.v1beta1.Value.toObject(message.values[j], options); + } + if (message.before != null && message.hasOwnProperty("before")) + object.before = message.before; + return object; + }; + + /** + * Converts this Cursor to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.Cursor + * @instance + * @returns {Object.} JSON object + */ + Cursor.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Cursor + * @function getTypeUrl + * @memberof google.firestore.v1beta1.Cursor + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Cursor.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.Cursor"; + }; + + return Cursor; + })(); + + v1beta1.Write = (function() { + + /** + * Properties of a Write. + * @memberof google.firestore.v1beta1 + * @interface IWrite + * @property {google.firestore.v1beta1.IDocument|null} [update] Write update + * @property {string|null} ["delete"] Write delete + * @property {google.firestore.v1beta1.IDocumentTransform|null} [transform] Write transform + * @property {google.firestore.v1beta1.IDocumentMask|null} [updateMask] Write updateMask + * @property {Array.|null} [updateTransforms] Write updateTransforms + * @property {google.firestore.v1beta1.IPrecondition|null} [currentDocument] Write currentDocument + */ + + /** + * Constructs a new Write. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a Write. + * @implements IWrite + * @constructor + * @param {google.firestore.v1beta1.IWrite=} [properties] Properties to set + */ + function Write(properties) { + this.updateTransforms = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Write update. + * @member {google.firestore.v1beta1.IDocument|null|undefined} update + * @memberof google.firestore.v1beta1.Write + * @instance + */ + Write.prototype.update = null; + + /** + * Write delete. + * @member {string|null|undefined} delete + * @memberof google.firestore.v1beta1.Write + * @instance + */ + Write.prototype["delete"] = null; + + /** + * Write transform. + * @member {google.firestore.v1beta1.IDocumentTransform|null|undefined} transform + * @memberof google.firestore.v1beta1.Write + * @instance + */ + Write.prototype.transform = null; + + /** + * Write updateMask. + * @member {google.firestore.v1beta1.IDocumentMask|null|undefined} updateMask + * @memberof google.firestore.v1beta1.Write + * @instance + */ + Write.prototype.updateMask = null; + + /** + * Write updateTransforms. + * @member {Array.} updateTransforms + * @memberof google.firestore.v1beta1.Write + * @instance + */ + Write.prototype.updateTransforms = $util.emptyArray; + + /** + * Write currentDocument. + * @member {google.firestore.v1beta1.IPrecondition|null|undefined} currentDocument + * @memberof google.firestore.v1beta1.Write + * @instance + */ + Write.prototype.currentDocument = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Write operation. + * @member {"update"|"delete"|"transform"|undefined} operation + * @memberof google.firestore.v1beta1.Write + * @instance + */ + Object.defineProperty(Write.prototype, "operation", { + get: $util.oneOfGetter($oneOfFields = ["update", "delete", "transform"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a Write message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.Write + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.Write} Write + */ + Write.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.Write) + return object; + var message = new $root.google.firestore.v1beta1.Write(); + if (object.update != null) { + if (typeof object.update !== "object") + throw TypeError(".google.firestore.v1beta1.Write.update: object expected"); + message.update = $root.google.firestore.v1beta1.Document.fromObject(object.update); + } + if (object["delete"] != null) + message["delete"] = String(object["delete"]); + if (object.transform != null) { + if (typeof object.transform !== "object") + throw TypeError(".google.firestore.v1beta1.Write.transform: object expected"); + message.transform = $root.google.firestore.v1beta1.DocumentTransform.fromObject(object.transform); + } + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.firestore.v1beta1.Write.updateMask: object expected"); + message.updateMask = $root.google.firestore.v1beta1.DocumentMask.fromObject(object.updateMask); + } + if (object.updateTransforms) { + if (!Array.isArray(object.updateTransforms)) + throw TypeError(".google.firestore.v1beta1.Write.updateTransforms: array expected"); + message.updateTransforms = []; + for (var i = 0; i < object.updateTransforms.length; ++i) { + if (typeof object.updateTransforms[i] !== "object") + throw TypeError(".google.firestore.v1beta1.Write.updateTransforms: object expected"); + message.updateTransforms[i] = $root.google.firestore.v1beta1.DocumentTransform.FieldTransform.fromObject(object.updateTransforms[i]); + } + } + if (object.currentDocument != null) { + if (typeof object.currentDocument !== "object") + throw TypeError(".google.firestore.v1beta1.Write.currentDocument: object expected"); + message.currentDocument = $root.google.firestore.v1beta1.Precondition.fromObject(object.currentDocument); + } + return message; + }; + + /** + * Creates a plain object from a Write message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.Write + * @static + * @param {google.firestore.v1beta1.Write} message Write + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Write.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.updateTransforms = []; + if (options.defaults) { + object.updateMask = null; + object.currentDocument = null; + } + if (message.update != null && message.hasOwnProperty("update")) { + object.update = $root.google.firestore.v1beta1.Document.toObject(message.update, options); + if (options.oneofs) + object.operation = "update"; + } + if (message["delete"] != null && message.hasOwnProperty("delete")) { + object["delete"] = message["delete"]; + if (options.oneofs) + object.operation = "delete"; + } + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.firestore.v1beta1.DocumentMask.toObject(message.updateMask, options); + if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) + object.currentDocument = $root.google.firestore.v1beta1.Precondition.toObject(message.currentDocument, options); + if (message.transform != null && message.hasOwnProperty("transform")) { + object.transform = $root.google.firestore.v1beta1.DocumentTransform.toObject(message.transform, options); + if (options.oneofs) + object.operation = "transform"; + } + if (message.updateTransforms && message.updateTransforms.length) { + object.updateTransforms = []; + for (var j = 0; j < message.updateTransforms.length; ++j) + object.updateTransforms[j] = $root.google.firestore.v1beta1.DocumentTransform.FieldTransform.toObject(message.updateTransforms[j], options); + } + return object; + }; + + /** + * Converts this Write to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.Write + * @instance + * @returns {Object.} JSON object + */ + Write.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Write + * @function getTypeUrl + * @memberof google.firestore.v1beta1.Write + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Write.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.Write"; + }; + + return Write; + })(); + + v1beta1.DocumentTransform = (function() { + + /** + * Properties of a DocumentTransform. + * @memberof google.firestore.v1beta1 + * @interface IDocumentTransform + * @property {string|null} [document] DocumentTransform document + * @property {Array.|null} [fieldTransforms] DocumentTransform fieldTransforms + */ + + /** + * Constructs a new DocumentTransform. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a DocumentTransform. + * @implements IDocumentTransform + * @constructor + * @param {google.firestore.v1beta1.IDocumentTransform=} [properties] Properties to set + */ + function DocumentTransform(properties) { + this.fieldTransforms = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DocumentTransform document. + * @member {string} document + * @memberof google.firestore.v1beta1.DocumentTransform + * @instance + */ + DocumentTransform.prototype.document = ""; + + /** + * DocumentTransform fieldTransforms. + * @member {Array.} fieldTransforms + * @memberof google.firestore.v1beta1.DocumentTransform + * @instance + */ + DocumentTransform.prototype.fieldTransforms = $util.emptyArray; + + /** + * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.DocumentTransform + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.DocumentTransform} DocumentTransform + */ + DocumentTransform.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.DocumentTransform) + return object; + var message = new $root.google.firestore.v1beta1.DocumentTransform(); + if (object.document != null) + message.document = String(object.document); + if (object.fieldTransforms) { + if (!Array.isArray(object.fieldTransforms)) + throw TypeError(".google.firestore.v1beta1.DocumentTransform.fieldTransforms: array expected"); + message.fieldTransforms = []; + for (var i = 0; i < object.fieldTransforms.length; ++i) { + if (typeof object.fieldTransforms[i] !== "object") + throw TypeError(".google.firestore.v1beta1.DocumentTransform.fieldTransforms: object expected"); + message.fieldTransforms[i] = $root.google.firestore.v1beta1.DocumentTransform.FieldTransform.fromObject(object.fieldTransforms[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.DocumentTransform + * @static + * @param {google.firestore.v1beta1.DocumentTransform} message DocumentTransform + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DocumentTransform.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.fieldTransforms = []; + if (options.defaults) + object.document = ""; + if (message.document != null && message.hasOwnProperty("document")) + object.document = message.document; + if (message.fieldTransforms && message.fieldTransforms.length) { + object.fieldTransforms = []; + for (var j = 0; j < message.fieldTransforms.length; ++j) + object.fieldTransforms[j] = $root.google.firestore.v1beta1.DocumentTransform.FieldTransform.toObject(message.fieldTransforms[j], options); + } + return object; + }; + + /** + * Converts this DocumentTransform to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.DocumentTransform + * @instance + * @returns {Object.} JSON object + */ + DocumentTransform.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DocumentTransform + * @function getTypeUrl + * @memberof google.firestore.v1beta1.DocumentTransform + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DocumentTransform.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.DocumentTransform"; + }; + + DocumentTransform.FieldTransform = (function() { + + /** + * Properties of a FieldTransform. + * @memberof google.firestore.v1beta1.DocumentTransform + * @interface IFieldTransform + * @property {string|null} [fieldPath] FieldTransform fieldPath + * @property {google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue|null} [setToServerValue] FieldTransform setToServerValue + * @property {google.firestore.v1beta1.IValue|null} [increment] FieldTransform increment + * @property {google.firestore.v1beta1.IValue|null} [maximum] FieldTransform maximum + * @property {google.firestore.v1beta1.IValue|null} [minimum] FieldTransform minimum + * @property {google.firestore.v1beta1.IArrayValue|null} [appendMissingElements] FieldTransform appendMissingElements + * @property {google.firestore.v1beta1.IArrayValue|null} [removeAllFromArray] FieldTransform removeAllFromArray + */ + + /** + * Constructs a new FieldTransform. + * @memberof google.firestore.v1beta1.DocumentTransform + * @classdesc Represents a FieldTransform. + * @implements IFieldTransform + * @constructor + * @param {google.firestore.v1beta1.DocumentTransform.IFieldTransform=} [properties] Properties to set + */ + function FieldTransform(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldTransform fieldPath. + * @member {string} fieldPath + * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.fieldPath = ""; + + /** + * FieldTransform setToServerValue. + * @member {google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue|null|undefined} setToServerValue + * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.setToServerValue = null; + + /** + * FieldTransform increment. + * @member {google.firestore.v1beta1.IValue|null|undefined} increment + * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.increment = null; + + /** + * FieldTransform maximum. + * @member {google.firestore.v1beta1.IValue|null|undefined} maximum + * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.maximum = null; + + /** + * FieldTransform minimum. + * @member {google.firestore.v1beta1.IValue|null|undefined} minimum + * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.minimum = null; + + /** + * FieldTransform appendMissingElements. + * @member {google.firestore.v1beta1.IArrayValue|null|undefined} appendMissingElements + * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.appendMissingElements = null; + + /** + * FieldTransform removeAllFromArray. + * @member {google.firestore.v1beta1.IArrayValue|null|undefined} removeAllFromArray + * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.removeAllFromArray = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * FieldTransform transformType. + * @member {"setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"|undefined} transformType + * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform + * @instance + */ + Object.defineProperty(FieldTransform.prototype, "transformType", { + get: $util.oneOfGetter($oneOfFields = ["setToServerValue", "increment", "maximum", "minimum", "appendMissingElements", "removeAllFromArray"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.DocumentTransform.FieldTransform} FieldTransform + */ + FieldTransform.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.DocumentTransform.FieldTransform) + return object; + var message = new $root.google.firestore.v1beta1.DocumentTransform.FieldTransform(); + if (object.fieldPath != null) + message.fieldPath = String(object.fieldPath); + switch (object.setToServerValue) { + default: + if (typeof object.setToServerValue === "number") { + message.setToServerValue = object.setToServerValue; + break; + } + break; + case "SERVER_VALUE_UNSPECIFIED": + case 0: + message.setToServerValue = 0; + break; + case "REQUEST_TIME": + case 1: + message.setToServerValue = 1; + break; + } + if (object.increment != null) { + if (typeof object.increment !== "object") + throw TypeError(".google.firestore.v1beta1.DocumentTransform.FieldTransform.increment: object expected"); + message.increment = $root.google.firestore.v1beta1.Value.fromObject(object.increment); + } + if (object.maximum != null) { + if (typeof object.maximum !== "object") + throw TypeError(".google.firestore.v1beta1.DocumentTransform.FieldTransform.maximum: object expected"); + message.maximum = $root.google.firestore.v1beta1.Value.fromObject(object.maximum); + } + if (object.minimum != null) { + if (typeof object.minimum !== "object") + throw TypeError(".google.firestore.v1beta1.DocumentTransform.FieldTransform.minimum: object expected"); + message.minimum = $root.google.firestore.v1beta1.Value.fromObject(object.minimum); + } + if (object.appendMissingElements != null) { + if (typeof object.appendMissingElements !== "object") + throw TypeError(".google.firestore.v1beta1.DocumentTransform.FieldTransform.appendMissingElements: object expected"); + message.appendMissingElements = $root.google.firestore.v1beta1.ArrayValue.fromObject(object.appendMissingElements); + } + if (object.removeAllFromArray != null) { + if (typeof object.removeAllFromArray !== "object") + throw TypeError(".google.firestore.v1beta1.DocumentTransform.FieldTransform.removeAllFromArray: object expected"); + message.removeAllFromArray = $root.google.firestore.v1beta1.ArrayValue.fromObject(object.removeAllFromArray); + } + return message; + }; + + /** + * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform + * @static + * @param {google.firestore.v1beta1.DocumentTransform.FieldTransform} message FieldTransform + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldTransform.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.fieldPath = ""; + if (message.fieldPath != null && message.hasOwnProperty("fieldPath")) + object.fieldPath = message.fieldPath; + if (message.setToServerValue != null && message.hasOwnProperty("setToServerValue")) { + object.setToServerValue = options.enums === String ? $root.google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue[message.setToServerValue] === undefined ? message.setToServerValue : $root.google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue[message.setToServerValue] : message.setToServerValue; + if (options.oneofs) + object.transformType = "setToServerValue"; + } + if (message.increment != null && message.hasOwnProperty("increment")) { + object.increment = $root.google.firestore.v1beta1.Value.toObject(message.increment, options); + if (options.oneofs) + object.transformType = "increment"; + } + if (message.maximum != null && message.hasOwnProperty("maximum")) { + object.maximum = $root.google.firestore.v1beta1.Value.toObject(message.maximum, options); + if (options.oneofs) + object.transformType = "maximum"; + } + if (message.minimum != null && message.hasOwnProperty("minimum")) { + object.minimum = $root.google.firestore.v1beta1.Value.toObject(message.minimum, options); + if (options.oneofs) + object.transformType = "minimum"; + } + if (message.appendMissingElements != null && message.hasOwnProperty("appendMissingElements")) { + object.appendMissingElements = $root.google.firestore.v1beta1.ArrayValue.toObject(message.appendMissingElements, options); + if (options.oneofs) + object.transformType = "appendMissingElements"; + } + if (message.removeAllFromArray != null && message.hasOwnProperty("removeAllFromArray")) { + object.removeAllFromArray = $root.google.firestore.v1beta1.ArrayValue.toObject(message.removeAllFromArray, options); + if (options.oneofs) + object.transformType = "removeAllFromArray"; + } + return object; + }; + + /** + * Converts this FieldTransform to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform + * @instance + * @returns {Object.} JSON object + */ + FieldTransform.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldTransform + * @function getTypeUrl + * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldTransform.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.DocumentTransform.FieldTransform"; + }; + + /** + * ServerValue enum. + * @name google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue + * @enum {string} + * @property {string} SERVER_VALUE_UNSPECIFIED=SERVER_VALUE_UNSPECIFIED SERVER_VALUE_UNSPECIFIED value + * @property {string} REQUEST_TIME=REQUEST_TIME REQUEST_TIME value + */ + FieldTransform.ServerValue = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "SERVER_VALUE_UNSPECIFIED"] = "SERVER_VALUE_UNSPECIFIED"; + values[valuesById[1] = "REQUEST_TIME"] = "REQUEST_TIME"; + return values; + })(); + + return FieldTransform; + })(); + + return DocumentTransform; + })(); + + v1beta1.WriteResult = (function() { + + /** + * Properties of a WriteResult. + * @memberof google.firestore.v1beta1 + * @interface IWriteResult + * @property {google.protobuf.ITimestamp|null} [updateTime] WriteResult updateTime + * @property {Array.|null} [transformResults] WriteResult transformResults + */ + + /** + * Constructs a new WriteResult. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a WriteResult. + * @implements IWriteResult + * @constructor + * @param {google.firestore.v1beta1.IWriteResult=} [properties] Properties to set + */ + function WriteResult(properties) { + this.transformResults = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * WriteResult updateTime. + * @member {google.protobuf.ITimestamp|null|undefined} updateTime + * @memberof google.firestore.v1beta1.WriteResult + * @instance + */ + WriteResult.prototype.updateTime = null; + + /** + * WriteResult transformResults. + * @member {Array.} transformResults + * @memberof google.firestore.v1beta1.WriteResult + * @instance + */ + WriteResult.prototype.transformResults = $util.emptyArray; + + /** + * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.WriteResult + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.WriteResult} WriteResult + */ + WriteResult.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.WriteResult) + return object; + var message = new $root.google.firestore.v1beta1.WriteResult(); + if (object.updateTime != null) { + if (typeof object.updateTime !== "object") + throw TypeError(".google.firestore.v1beta1.WriteResult.updateTime: object expected"); + message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + } + if (object.transformResults) { + if (!Array.isArray(object.transformResults)) + throw TypeError(".google.firestore.v1beta1.WriteResult.transformResults: array expected"); + message.transformResults = []; + for (var i = 0; i < object.transformResults.length; ++i) { + if (typeof object.transformResults[i] !== "object") + throw TypeError(".google.firestore.v1beta1.WriteResult.transformResults: object expected"); + message.transformResults[i] = $root.google.firestore.v1beta1.Value.fromObject(object.transformResults[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a WriteResult message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.WriteResult + * @static + * @param {google.firestore.v1beta1.WriteResult} message WriteResult + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WriteResult.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.transformResults = []; + if (options.defaults) + object.updateTime = null; + if (message.updateTime != null && message.hasOwnProperty("updateTime")) + object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + if (message.transformResults && message.transformResults.length) { + object.transformResults = []; + for (var j = 0; j < message.transformResults.length; ++j) + object.transformResults[j] = $root.google.firestore.v1beta1.Value.toObject(message.transformResults[j], options); + } + return object; + }; + + /** + * Converts this WriteResult to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.WriteResult + * @instance + * @returns {Object.} JSON object + */ + WriteResult.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for WriteResult + * @function getTypeUrl + * @memberof google.firestore.v1beta1.WriteResult + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WriteResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.WriteResult"; + }; + + return WriteResult; + })(); + + v1beta1.DocumentChange = (function() { + + /** + * Properties of a DocumentChange. + * @memberof google.firestore.v1beta1 + * @interface IDocumentChange + * @property {google.firestore.v1beta1.IDocument|null} [document] DocumentChange document + * @property {Array.|null} [targetIds] DocumentChange targetIds + * @property {Array.|null} [removedTargetIds] DocumentChange removedTargetIds + */ + + /** + * Constructs a new DocumentChange. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a DocumentChange. + * @implements IDocumentChange + * @constructor + * @param {google.firestore.v1beta1.IDocumentChange=} [properties] Properties to set + */ + function DocumentChange(properties) { + this.targetIds = []; + this.removedTargetIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DocumentChange document. + * @member {google.firestore.v1beta1.IDocument|null|undefined} document + * @memberof google.firestore.v1beta1.DocumentChange + * @instance + */ + DocumentChange.prototype.document = null; + + /** + * DocumentChange targetIds. + * @member {Array.} targetIds + * @memberof google.firestore.v1beta1.DocumentChange + * @instance + */ + DocumentChange.prototype.targetIds = $util.emptyArray; + + /** + * DocumentChange removedTargetIds. + * @member {Array.} removedTargetIds + * @memberof google.firestore.v1beta1.DocumentChange + * @instance + */ + DocumentChange.prototype.removedTargetIds = $util.emptyArray; + + /** + * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.DocumentChange + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.DocumentChange} DocumentChange + */ + DocumentChange.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.DocumentChange) + return object; + var message = new $root.google.firestore.v1beta1.DocumentChange(); + if (object.document != null) { + if (typeof object.document !== "object") + throw TypeError(".google.firestore.v1beta1.DocumentChange.document: object expected"); + message.document = $root.google.firestore.v1beta1.Document.fromObject(object.document); + } + if (object.targetIds) { + if (!Array.isArray(object.targetIds)) + throw TypeError(".google.firestore.v1beta1.DocumentChange.targetIds: array expected"); + message.targetIds = []; + for (var i = 0; i < object.targetIds.length; ++i) + message.targetIds[i] = object.targetIds[i] | 0; + } + if (object.removedTargetIds) { + if (!Array.isArray(object.removedTargetIds)) + throw TypeError(".google.firestore.v1beta1.DocumentChange.removedTargetIds: array expected"); + message.removedTargetIds = []; + for (var i = 0; i < object.removedTargetIds.length; ++i) + message.removedTargetIds[i] = object.removedTargetIds[i] | 0; + } + return message; + }; + + /** + * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.DocumentChange + * @static + * @param {google.firestore.v1beta1.DocumentChange} message DocumentChange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DocumentChange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.targetIds = []; + object.removedTargetIds = []; + } + if (options.defaults) + object.document = null; + if (message.document != null && message.hasOwnProperty("document")) + object.document = $root.google.firestore.v1beta1.Document.toObject(message.document, options); + if (message.targetIds && message.targetIds.length) { + object.targetIds = []; + for (var j = 0; j < message.targetIds.length; ++j) + object.targetIds[j] = message.targetIds[j]; + } + if (message.removedTargetIds && message.removedTargetIds.length) { + object.removedTargetIds = []; + for (var j = 0; j < message.removedTargetIds.length; ++j) + object.removedTargetIds[j] = message.removedTargetIds[j]; + } + return object; + }; + + /** + * Converts this DocumentChange to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.DocumentChange + * @instance + * @returns {Object.} JSON object + */ + DocumentChange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DocumentChange + * @function getTypeUrl + * @memberof google.firestore.v1beta1.DocumentChange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DocumentChange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.DocumentChange"; + }; + + return DocumentChange; + })(); + + v1beta1.DocumentDelete = (function() { + + /** + * Properties of a DocumentDelete. + * @memberof google.firestore.v1beta1 + * @interface IDocumentDelete + * @property {string|null} [document] DocumentDelete document + * @property {Array.|null} [removedTargetIds] DocumentDelete removedTargetIds + * @property {google.protobuf.ITimestamp|null} [readTime] DocumentDelete readTime + */ + + /** + * Constructs a new DocumentDelete. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a DocumentDelete. + * @implements IDocumentDelete + * @constructor + * @param {google.firestore.v1beta1.IDocumentDelete=} [properties] Properties to set + */ + function DocumentDelete(properties) { + this.removedTargetIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DocumentDelete document. + * @member {string} document + * @memberof google.firestore.v1beta1.DocumentDelete + * @instance + */ + DocumentDelete.prototype.document = ""; + + /** + * DocumentDelete removedTargetIds. + * @member {Array.} removedTargetIds + * @memberof google.firestore.v1beta1.DocumentDelete + * @instance + */ + DocumentDelete.prototype.removedTargetIds = $util.emptyArray; + + /** + * DocumentDelete readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1beta1.DocumentDelete + * @instance + */ + DocumentDelete.prototype.readTime = null; + + /** + * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.DocumentDelete + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.DocumentDelete} DocumentDelete + */ + DocumentDelete.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.DocumentDelete) + return object; + var message = new $root.google.firestore.v1beta1.DocumentDelete(); + if (object.document != null) + message.document = String(object.document); + if (object.removedTargetIds) { + if (!Array.isArray(object.removedTargetIds)) + throw TypeError(".google.firestore.v1beta1.DocumentDelete.removedTargetIds: array expected"); + message.removedTargetIds = []; + for (var i = 0; i < object.removedTargetIds.length; ++i) + message.removedTargetIds[i] = object.removedTargetIds[i] | 0; + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1beta1.DocumentDelete.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.DocumentDelete + * @static + * @param {google.firestore.v1beta1.DocumentDelete} message DocumentDelete + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DocumentDelete.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.removedTargetIds = []; + if (options.defaults) { + object.document = ""; + object.readTime = null; + } + if (message.document != null && message.hasOwnProperty("document")) + object.document = message.document; + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (message.removedTargetIds && message.removedTargetIds.length) { + object.removedTargetIds = []; + for (var j = 0; j < message.removedTargetIds.length; ++j) + object.removedTargetIds[j] = message.removedTargetIds[j]; + } + return object; + }; + + /** + * Converts this DocumentDelete to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.DocumentDelete + * @instance + * @returns {Object.} JSON object + */ + DocumentDelete.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DocumentDelete + * @function getTypeUrl + * @memberof google.firestore.v1beta1.DocumentDelete + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DocumentDelete.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.DocumentDelete"; + }; + + return DocumentDelete; + })(); + + v1beta1.DocumentRemove = (function() { + + /** + * Properties of a DocumentRemove. + * @memberof google.firestore.v1beta1 + * @interface IDocumentRemove + * @property {string|null} [document] DocumentRemove document + * @property {Array.|null} [removedTargetIds] DocumentRemove removedTargetIds + * @property {google.protobuf.ITimestamp|null} [readTime] DocumentRemove readTime + */ + + /** + * Constructs a new DocumentRemove. + * @memberof google.firestore.v1beta1 + * @classdesc Represents a DocumentRemove. + * @implements IDocumentRemove + * @constructor + * @param {google.firestore.v1beta1.IDocumentRemove=} [properties] Properties to set + */ + function DocumentRemove(properties) { + this.removedTargetIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DocumentRemove document. + * @member {string} document + * @memberof google.firestore.v1beta1.DocumentRemove + * @instance + */ + DocumentRemove.prototype.document = ""; + + /** + * DocumentRemove removedTargetIds. + * @member {Array.} removedTargetIds + * @memberof google.firestore.v1beta1.DocumentRemove + * @instance + */ + DocumentRemove.prototype.removedTargetIds = $util.emptyArray; + + /** + * DocumentRemove readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1beta1.DocumentRemove + * @instance + */ + DocumentRemove.prototype.readTime = null; + + /** + * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.DocumentRemove + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.DocumentRemove} DocumentRemove + */ + DocumentRemove.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.DocumentRemove) + return object; + var message = new $root.google.firestore.v1beta1.DocumentRemove(); + if (object.document != null) + message.document = String(object.document); + if (object.removedTargetIds) { + if (!Array.isArray(object.removedTargetIds)) + throw TypeError(".google.firestore.v1beta1.DocumentRemove.removedTargetIds: array expected"); + message.removedTargetIds = []; + for (var i = 0; i < object.removedTargetIds.length; ++i) + message.removedTargetIds[i] = object.removedTargetIds[i] | 0; + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1beta1.DocumentRemove.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.DocumentRemove + * @static + * @param {google.firestore.v1beta1.DocumentRemove} message DocumentRemove + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DocumentRemove.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.removedTargetIds = []; + if (options.defaults) { + object.document = ""; + object.readTime = null; + } + if (message.document != null && message.hasOwnProperty("document")) + object.document = message.document; + if (message.removedTargetIds && message.removedTargetIds.length) { + object.removedTargetIds = []; + for (var j = 0; j < message.removedTargetIds.length; ++j) + object.removedTargetIds[j] = message.removedTargetIds[j]; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + return object; + }; + + /** + * Converts this DocumentRemove to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.DocumentRemove + * @instance + * @returns {Object.} JSON object + */ + DocumentRemove.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DocumentRemove + * @function getTypeUrl + * @memberof google.firestore.v1beta1.DocumentRemove + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DocumentRemove.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.DocumentRemove"; + }; + + return DocumentRemove; + })(); + + v1beta1.ExistenceFilter = (function() { + + /** + * Properties of an ExistenceFilter. + * @memberof google.firestore.v1beta1 + * @interface IExistenceFilter + * @property {number|null} [targetId] ExistenceFilter targetId + * @property {number|null} [count] ExistenceFilter count + */ + + /** + * Constructs a new ExistenceFilter. + * @memberof google.firestore.v1beta1 + * @classdesc Represents an ExistenceFilter. + * @implements IExistenceFilter + * @constructor + * @param {google.firestore.v1beta1.IExistenceFilter=} [properties] Properties to set + */ + function ExistenceFilter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExistenceFilter targetId. + * @member {number} targetId + * @memberof google.firestore.v1beta1.ExistenceFilter + * @instance + */ + ExistenceFilter.prototype.targetId = 0; + + /** + * ExistenceFilter count. + * @member {number} count + * @memberof google.firestore.v1beta1.ExistenceFilter + * @instance + */ + ExistenceFilter.prototype.count = 0; + + /** + * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.ExistenceFilter + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.ExistenceFilter} ExistenceFilter + */ + ExistenceFilter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.ExistenceFilter) + return object; + var message = new $root.google.firestore.v1beta1.ExistenceFilter(); + if (object.targetId != null) + message.targetId = object.targetId | 0; + if (object.count != null) + message.count = object.count | 0; + return message; + }; + + /** + * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.ExistenceFilter + * @static + * @param {google.firestore.v1beta1.ExistenceFilter} message ExistenceFilter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExistenceFilter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.targetId = 0; + object.count = 0; + } + if (message.targetId != null && message.hasOwnProperty("targetId")) + object.targetId = message.targetId; + if (message.count != null && message.hasOwnProperty("count")) + object.count = message.count; + return object; + }; + + /** + * Converts this ExistenceFilter to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.ExistenceFilter + * @instance + * @returns {Object.} JSON object + */ + ExistenceFilter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExistenceFilter + * @function getTypeUrl + * @memberof google.firestore.v1beta1.ExistenceFilter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExistenceFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.ExistenceFilter"; + }; + + return ExistenceFilter; + })(); + + v1beta1.UndeliverableFirstGenEvent = (function() { + + /** + * Properties of an UndeliverableFirstGenEvent. + * @memberof google.firestore.v1beta1 + * @interface IUndeliverableFirstGenEvent + * @property {string|null} [message] UndeliverableFirstGenEvent message + * @property {google.firestore.v1beta1.UndeliverableFirstGenEvent.Reason|null} [reason] UndeliverableFirstGenEvent reason + * @property {string|null} [documentName] UndeliverableFirstGenEvent documentName + * @property {google.firestore.v1beta1.UndeliverableFirstGenEvent.DocumentChangeType|null} [documentChangeType] UndeliverableFirstGenEvent documentChangeType + * @property {Array.|null} [functionName] UndeliverableFirstGenEvent functionName + * @property {google.protobuf.ITimestamp|null} [triggeredTime] UndeliverableFirstGenEvent triggeredTime + */ + + /** + * Constructs a new UndeliverableFirstGenEvent. + * @memberof google.firestore.v1beta1 + * @classdesc Represents an UndeliverableFirstGenEvent. + * @implements IUndeliverableFirstGenEvent + * @constructor + * @param {google.firestore.v1beta1.IUndeliverableFirstGenEvent=} [properties] Properties to set + */ + function UndeliverableFirstGenEvent(properties) { + this.functionName = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UndeliverableFirstGenEvent message. + * @member {string} message + * @memberof google.firestore.v1beta1.UndeliverableFirstGenEvent + * @instance + */ + UndeliverableFirstGenEvent.prototype.message = ""; + + /** + * UndeliverableFirstGenEvent reason. + * @member {google.firestore.v1beta1.UndeliverableFirstGenEvent.Reason} reason + * @memberof google.firestore.v1beta1.UndeliverableFirstGenEvent + * @instance + */ + UndeliverableFirstGenEvent.prototype.reason = 0; + + /** + * UndeliverableFirstGenEvent documentName. + * @member {string} documentName + * @memberof google.firestore.v1beta1.UndeliverableFirstGenEvent + * @instance + */ + UndeliverableFirstGenEvent.prototype.documentName = ""; + + /** + * UndeliverableFirstGenEvent documentChangeType. + * @member {google.firestore.v1beta1.UndeliverableFirstGenEvent.DocumentChangeType} documentChangeType + * @memberof google.firestore.v1beta1.UndeliverableFirstGenEvent + * @instance + */ + UndeliverableFirstGenEvent.prototype.documentChangeType = 0; + + /** + * UndeliverableFirstGenEvent functionName. + * @member {Array.} functionName + * @memberof google.firestore.v1beta1.UndeliverableFirstGenEvent + * @instance + */ + UndeliverableFirstGenEvent.prototype.functionName = $util.emptyArray; + + /** + * UndeliverableFirstGenEvent triggeredTime. + * @member {google.protobuf.ITimestamp|null|undefined} triggeredTime + * @memberof google.firestore.v1beta1.UndeliverableFirstGenEvent + * @instance + */ + UndeliverableFirstGenEvent.prototype.triggeredTime = null; + + /** + * Creates an UndeliverableFirstGenEvent message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1beta1.UndeliverableFirstGenEvent + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1beta1.UndeliverableFirstGenEvent} UndeliverableFirstGenEvent + */ + UndeliverableFirstGenEvent.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1beta1.UndeliverableFirstGenEvent) + return object; + var message = new $root.google.firestore.v1beta1.UndeliverableFirstGenEvent(); + if (object.message != null) + message.message = String(object.message); + switch (object.reason) { + default: + if (typeof object.reason === "number") { + message.reason = object.reason; + break; + } + break; + case "REASON_UNSPECIFIED": + case 0: + message.reason = 0; + break; + case "EXCEEDING_SIZE_LIMIT": + case 1: + message.reason = 1; + break; + } + if (object.documentName != null) + message.documentName = String(object.documentName); + switch (object.documentChangeType) { + default: + if (typeof object.documentChangeType === "number") { + message.documentChangeType = object.documentChangeType; + break; + } + break; + case "DOCUMENT_CHANGE_TYPE_UNSPECIFIED": + case 0: + message.documentChangeType = 0; + break; + case "CREATE": + case 1: + message.documentChangeType = 1; + break; + case "DELETE": + case 2: + message.documentChangeType = 2; + break; + case "UPDATE": + case 3: + message.documentChangeType = 3; + break; + } + if (object.functionName) { + if (!Array.isArray(object.functionName)) + throw TypeError(".google.firestore.v1beta1.UndeliverableFirstGenEvent.functionName: array expected"); + message.functionName = []; + for (var i = 0; i < object.functionName.length; ++i) + message.functionName[i] = String(object.functionName[i]); + } + if (object.triggeredTime != null) { + if (typeof object.triggeredTime !== "object") + throw TypeError(".google.firestore.v1beta1.UndeliverableFirstGenEvent.triggeredTime: object expected"); + message.triggeredTime = $root.google.protobuf.Timestamp.fromObject(object.triggeredTime); + } + return message; + }; + + /** + * Creates a plain object from an UndeliverableFirstGenEvent message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1beta1.UndeliverableFirstGenEvent + * @static + * @param {google.firestore.v1beta1.UndeliverableFirstGenEvent} message UndeliverableFirstGenEvent + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UndeliverableFirstGenEvent.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.functionName = []; + if (options.defaults) { + object.message = ""; + object.reason = options.enums === String ? "REASON_UNSPECIFIED" : 0; + object.documentName = ""; + object.documentChangeType = options.enums === String ? "DOCUMENT_CHANGE_TYPE_UNSPECIFIED" : 0; + object.triggeredTime = null; + } + if (message.message != null && message.hasOwnProperty("message")) + object.message = message.message; + if (message.reason != null && message.hasOwnProperty("reason")) + object.reason = options.enums === String ? $root.google.firestore.v1beta1.UndeliverableFirstGenEvent.Reason[message.reason] === undefined ? message.reason : $root.google.firestore.v1beta1.UndeliverableFirstGenEvent.Reason[message.reason] : message.reason; + if (message.documentName != null && message.hasOwnProperty("documentName")) + object.documentName = message.documentName; + if (message.documentChangeType != null && message.hasOwnProperty("documentChangeType")) + object.documentChangeType = options.enums === String ? $root.google.firestore.v1beta1.UndeliverableFirstGenEvent.DocumentChangeType[message.documentChangeType] === undefined ? message.documentChangeType : $root.google.firestore.v1beta1.UndeliverableFirstGenEvent.DocumentChangeType[message.documentChangeType] : message.documentChangeType; + if (message.functionName && message.functionName.length) { + object.functionName = []; + for (var j = 0; j < message.functionName.length; ++j) + object.functionName[j] = message.functionName[j]; + } + if (message.triggeredTime != null && message.hasOwnProperty("triggeredTime")) + object.triggeredTime = $root.google.protobuf.Timestamp.toObject(message.triggeredTime, options); + return object; + }; + + /** + * Converts this UndeliverableFirstGenEvent to JSON. + * @function toJSON + * @memberof google.firestore.v1beta1.UndeliverableFirstGenEvent + * @instance + * @returns {Object.} JSON object + */ + UndeliverableFirstGenEvent.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UndeliverableFirstGenEvent + * @function getTypeUrl + * @memberof google.firestore.v1beta1.UndeliverableFirstGenEvent + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UndeliverableFirstGenEvent.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1beta1.UndeliverableFirstGenEvent"; + }; + + /** + * Reason enum. + * @name google.firestore.v1beta1.UndeliverableFirstGenEvent.Reason + * @enum {string} + * @property {string} REASON_UNSPECIFIED=REASON_UNSPECIFIED REASON_UNSPECIFIED value + * @property {string} EXCEEDING_SIZE_LIMIT=EXCEEDING_SIZE_LIMIT EXCEEDING_SIZE_LIMIT value + */ + UndeliverableFirstGenEvent.Reason = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "REASON_UNSPECIFIED"] = "REASON_UNSPECIFIED"; + values[valuesById[1] = "EXCEEDING_SIZE_LIMIT"] = "EXCEEDING_SIZE_LIMIT"; + return values; + })(); + + /** + * DocumentChangeType enum. + * @name google.firestore.v1beta1.UndeliverableFirstGenEvent.DocumentChangeType + * @enum {string} + * @property {string} DOCUMENT_CHANGE_TYPE_UNSPECIFIED=DOCUMENT_CHANGE_TYPE_UNSPECIFIED DOCUMENT_CHANGE_TYPE_UNSPECIFIED value + * @property {string} CREATE=CREATE CREATE value + * @property {string} DELETE=DELETE DELETE value + * @property {string} UPDATE=UPDATE UPDATE value + */ + UndeliverableFirstGenEvent.DocumentChangeType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DOCUMENT_CHANGE_TYPE_UNSPECIFIED"] = "DOCUMENT_CHANGE_TYPE_UNSPECIFIED"; + values[valuesById[1] = "CREATE"] = "CREATE"; + values[valuesById[2] = "DELETE"] = "DELETE"; + values[valuesById[3] = "UPDATE"] = "UPDATE"; + return values; + })(); + + return UndeliverableFirstGenEvent; + })(); + + return v1beta1; + })(); + + return firestore; + })(); + + google.type = (function() { + + /** + * Namespace type. + * @memberof google + * @namespace + */ + var type = {}; + + type.LatLng = (function() { + + /** + * Properties of a LatLng. + * @memberof google.type + * @interface ILatLng + * @property {number|null} [latitude] LatLng latitude + * @property {number|null} [longitude] LatLng longitude + */ + + /** + * Constructs a new LatLng. + * @memberof google.type + * @classdesc Represents a LatLng. + * @implements ILatLng + * @constructor + * @param {google.type.ILatLng=} [properties] Properties to set + */ + function LatLng(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * LatLng latitude. + * @member {number} latitude + * @memberof google.type.LatLng + * @instance + */ + LatLng.prototype.latitude = 0; + + /** + * LatLng longitude. + * @member {number} longitude + * @memberof google.type.LatLng + * @instance + */ + LatLng.prototype.longitude = 0; + + /** + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.type.LatLng + * @static + * @param {Object.} object Plain object + * @returns {google.type.LatLng} LatLng + */ + LatLng.fromObject = function fromObject(object) { + if (object instanceof $root.google.type.LatLng) + return object; + var message = new $root.google.type.LatLng(); + if (object.latitude != null) + message.latitude = Number(object.latitude); + if (object.longitude != null) + message.longitude = Number(object.longitude); + return message; + }; + + /** + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @function toObject + * @memberof google.type.LatLng + * @static + * @param {google.type.LatLng} message LatLng + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + LatLng.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.latitude = 0; + object.longitude = 0; + } + if (message.latitude != null && message.hasOwnProperty("latitude")) + object.latitude = options.json && !isFinite(message.latitude) ? String(message.latitude) : message.latitude; + if (message.longitude != null && message.hasOwnProperty("longitude")) + object.longitude = options.json && !isFinite(message.longitude) ? String(message.longitude) : message.longitude; + return object; + }; + + /** + * Converts this LatLng to JSON. + * @function toJSON + * @memberof google.type.LatLng + * @instance + * @returns {Object.} JSON object + */ + LatLng.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for LatLng + * @function getTypeUrl + * @memberof google.type.LatLng + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + LatLng.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.type.LatLng"; + }; + + return LatLng; + })(); + + /** + * DayOfWeek enum. + * @name google.type.DayOfWeek + * @enum {string} + * @property {string} DAY_OF_WEEK_UNSPECIFIED=DAY_OF_WEEK_UNSPECIFIED DAY_OF_WEEK_UNSPECIFIED value + * @property {string} MONDAY=MONDAY MONDAY value + * @property {string} TUESDAY=TUESDAY TUESDAY value + * @property {string} WEDNESDAY=WEDNESDAY WEDNESDAY value + * @property {string} THURSDAY=THURSDAY THURSDAY value + * @property {string} FRIDAY=FRIDAY FRIDAY value + * @property {string} SATURDAY=SATURDAY SATURDAY value + * @property {string} SUNDAY=SUNDAY SUNDAY value + */ + type.DayOfWeek = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DAY_OF_WEEK_UNSPECIFIED"] = "DAY_OF_WEEK_UNSPECIFIED"; + values[valuesById[1] = "MONDAY"] = "MONDAY"; + values[valuesById[2] = "TUESDAY"] = "TUESDAY"; + values[valuesById[3] = "WEDNESDAY"] = "WEDNESDAY"; + values[valuesById[4] = "THURSDAY"] = "THURSDAY"; + values[valuesById[5] = "FRIDAY"] = "FRIDAY"; + values[valuesById[6] = "SATURDAY"] = "SATURDAY"; + values[valuesById[7] = "SUNDAY"] = "SUNDAY"; + return values; + })(); + + return type; + })(); + + google.api = (function() { + + /** + * Namespace api. + * @memberof google + * @namespace + */ + var api = {}; + + api.Http = (function() { + + /** + * Properties of a Http. + * @memberof google.api + * @interface IHttp + * @property {Array.|null} [rules] Http rules + * @property {boolean|null} [fullyDecodeReservedExpansion] Http fullyDecodeReservedExpansion + */ + + /** + * Constructs a new Http. + * @memberof google.api + * @classdesc Represents a Http. + * @implements IHttp + * @constructor + * @param {google.api.IHttp=} [properties] Properties to set + */ + function Http(properties) { + this.rules = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Http rules. + * @member {Array.} rules + * @memberof google.api.Http + * @instance + */ + Http.prototype.rules = $util.emptyArray; + + /** + * Http fullyDecodeReservedExpansion. + * @member {boolean} fullyDecodeReservedExpansion + * @memberof google.api.Http + * @instance + */ + Http.prototype.fullyDecodeReservedExpansion = false; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.Http + * @static + * @param {Object.} object Plain object + * @returns {google.api.Http} Http + */ + Http.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.Http) + return object; + var message = new $root.google.api.Http(); + if (object.rules) { + if (!Array.isArray(object.rules)) + throw TypeError(".google.api.Http.rules: array expected"); + message.rules = []; + for (var i = 0; i < object.rules.length; ++i) { + if (typeof object.rules[i] !== "object") + throw TypeError(".google.api.Http.rules: object expected"); + message.rules[i] = $root.google.api.HttpRule.fromObject(object.rules[i]); + } + } + if (object.fullyDecodeReservedExpansion != null) + message.fullyDecodeReservedExpansion = Boolean(object.fullyDecodeReservedExpansion); + return message; + }; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.Http + * @static + * @param {google.api.Http} message Http + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Http.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.rules = []; + if (options.defaults) + object.fullyDecodeReservedExpansion = false; + if (message.rules && message.rules.length) { + object.rules = []; + for (var j = 0; j < message.rules.length; ++j) + object.rules[j] = $root.google.api.HttpRule.toObject(message.rules[j], options); + } + if (message.fullyDecodeReservedExpansion != null && message.hasOwnProperty("fullyDecodeReservedExpansion")) + object.fullyDecodeReservedExpansion = message.fullyDecodeReservedExpansion; + return object; + }; + + /** + * Converts this Http to JSON. + * @function toJSON + * @memberof google.api.Http + * @instance + * @returns {Object.} JSON object + */ + Http.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Http + * @function getTypeUrl + * @memberof google.api.Http + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Http.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.Http"; + }; + + return Http; + })(); + + api.HttpRule = (function() { + + /** + * Properties of a HttpRule. + * @memberof google.api + * @interface IHttpRule + * @property {string|null} [selector] HttpRule selector + * @property {string|null} [get] HttpRule get + * @property {string|null} [put] HttpRule put + * @property {string|null} [post] HttpRule post + * @property {string|null} ["delete"] HttpRule delete + * @property {string|null} [patch] HttpRule patch + * @property {google.api.ICustomHttpPattern|null} [custom] HttpRule custom + * @property {string|null} [body] HttpRule body + * @property {string|null} [responseBody] HttpRule responseBody + * @property {Array.|null} [additionalBindings] HttpRule additionalBindings + */ + + /** + * Constructs a new HttpRule. + * @memberof google.api + * @classdesc Represents a HttpRule. + * @implements IHttpRule + * @constructor + * @param {google.api.IHttpRule=} [properties] Properties to set + */ + function HttpRule(properties) { + this.additionalBindings = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * HttpRule selector. + * @member {string} selector + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.selector = ""; + + /** + * HttpRule get. + * @member {string|null|undefined} get + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.get = null; + + /** + * HttpRule put. + * @member {string|null|undefined} put + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.put = null; + + /** + * HttpRule post. + * @member {string|null|undefined} post + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.post = null; + + /** + * HttpRule delete. + * @member {string|null|undefined} delete + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype["delete"] = null; + + /** + * HttpRule patch. + * @member {string|null|undefined} patch + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.patch = null; + + /** + * HttpRule custom. + * @member {google.api.ICustomHttpPattern|null|undefined} custom + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.custom = null; + + /** + * HttpRule body. + * @member {string} body + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.body = ""; + + /** + * HttpRule responseBody. + * @member {string} responseBody + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.responseBody = ""; + + /** + * HttpRule additionalBindings. + * @member {Array.} additionalBindings + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.additionalBindings = $util.emptyArray; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * HttpRule pattern. + * @member {"get"|"put"|"post"|"delete"|"patch"|"custom"|undefined} pattern + * @memberof google.api.HttpRule + * @instance + */ + Object.defineProperty(HttpRule.prototype, "pattern", { + get: $util.oneOfGetter($oneOfFields = ["get", "put", "post", "delete", "patch", "custom"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.HttpRule + * @static + * @param {Object.} object Plain object + * @returns {google.api.HttpRule} HttpRule + */ + HttpRule.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.HttpRule) + return object; + var message = new $root.google.api.HttpRule(); + if (object.selector != null) + message.selector = String(object.selector); + if (object.get != null) + message.get = String(object.get); + if (object.put != null) + message.put = String(object.put); + if (object.post != null) + message.post = String(object.post); + if (object["delete"] != null) + message["delete"] = String(object["delete"]); + if (object.patch != null) + message.patch = String(object.patch); + if (object.custom != null) { + if (typeof object.custom !== "object") + throw TypeError(".google.api.HttpRule.custom: object expected"); + message.custom = $root.google.api.CustomHttpPattern.fromObject(object.custom); + } + if (object.body != null) + message.body = String(object.body); + if (object.responseBody != null) + message.responseBody = String(object.responseBody); + if (object.additionalBindings) { + if (!Array.isArray(object.additionalBindings)) + throw TypeError(".google.api.HttpRule.additionalBindings: array expected"); + message.additionalBindings = []; + for (var i = 0; i < object.additionalBindings.length; ++i) { + if (typeof object.additionalBindings[i] !== "object") + throw TypeError(".google.api.HttpRule.additionalBindings: object expected"); + message.additionalBindings[i] = $root.google.api.HttpRule.fromObject(object.additionalBindings[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.HttpRule + * @static + * @param {google.api.HttpRule} message HttpRule + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + HttpRule.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.additionalBindings = []; + if (options.defaults) { + object.selector = ""; + object.body = ""; + object.responseBody = ""; + } + if (message.selector != null && message.hasOwnProperty("selector")) + object.selector = message.selector; + if (message.get != null && message.hasOwnProperty("get")) { + object.get = message.get; + if (options.oneofs) + object.pattern = "get"; + } + if (message.put != null && message.hasOwnProperty("put")) { + object.put = message.put; + if (options.oneofs) + object.pattern = "put"; + } + if (message.post != null && message.hasOwnProperty("post")) { + object.post = message.post; + if (options.oneofs) + object.pattern = "post"; + } + if (message["delete"] != null && message.hasOwnProperty("delete")) { + object["delete"] = message["delete"]; + if (options.oneofs) + object.pattern = "delete"; + } + if (message.patch != null && message.hasOwnProperty("patch")) { + object.patch = message.patch; + if (options.oneofs) + object.pattern = "patch"; + } + if (message.body != null && message.hasOwnProperty("body")) + object.body = message.body; + if (message.custom != null && message.hasOwnProperty("custom")) { + object.custom = $root.google.api.CustomHttpPattern.toObject(message.custom, options); + if (options.oneofs) + object.pattern = "custom"; + } + if (message.additionalBindings && message.additionalBindings.length) { + object.additionalBindings = []; + for (var j = 0; j < message.additionalBindings.length; ++j) + object.additionalBindings[j] = $root.google.api.HttpRule.toObject(message.additionalBindings[j], options); + } + if (message.responseBody != null && message.hasOwnProperty("responseBody")) + object.responseBody = message.responseBody; + return object; + }; + + /** + * Converts this HttpRule to JSON. + * @function toJSON + * @memberof google.api.HttpRule + * @instance + * @returns {Object.} JSON object + */ + HttpRule.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for HttpRule + * @function getTypeUrl + * @memberof google.api.HttpRule + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + HttpRule.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.HttpRule"; + }; + + return HttpRule; + })(); + + api.CustomHttpPattern = (function() { + + /** + * Properties of a CustomHttpPattern. + * @memberof google.api + * @interface ICustomHttpPattern + * @property {string|null} [kind] CustomHttpPattern kind + * @property {string|null} [path] CustomHttpPattern path + */ + + /** + * Constructs a new CustomHttpPattern. + * @memberof google.api + * @classdesc Represents a CustomHttpPattern. + * @implements ICustomHttpPattern + * @constructor + * @param {google.api.ICustomHttpPattern=} [properties] Properties to set + */ + function CustomHttpPattern(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CustomHttpPattern kind. + * @member {string} kind + * @memberof google.api.CustomHttpPattern + * @instance + */ + CustomHttpPattern.prototype.kind = ""; + + /** + * CustomHttpPattern path. + * @member {string} path + * @memberof google.api.CustomHttpPattern + * @instance + */ + CustomHttpPattern.prototype.path = ""; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.CustomHttpPattern + * @static + * @param {Object.} object Plain object + * @returns {google.api.CustomHttpPattern} CustomHttpPattern + */ + CustomHttpPattern.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.CustomHttpPattern) + return object; + var message = new $root.google.api.CustomHttpPattern(); + if (object.kind != null) + message.kind = String(object.kind); + if (object.path != null) + message.path = String(object.path); + return message; + }; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.CustomHttpPattern + * @static + * @param {google.api.CustomHttpPattern} message CustomHttpPattern + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CustomHttpPattern.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.kind = ""; + object.path = ""; + } + if (message.kind != null && message.hasOwnProperty("kind")) + object.kind = message.kind; + if (message.path != null && message.hasOwnProperty("path")) + object.path = message.path; + return object; + }; + + /** + * Converts this CustomHttpPattern to JSON. + * @function toJSON + * @memberof google.api.CustomHttpPattern + * @instance + * @returns {Object.} JSON object + */ + CustomHttpPattern.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CustomHttpPattern + * @function getTypeUrl + * @memberof google.api.CustomHttpPattern + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CustomHttpPattern.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.CustomHttpPattern"; + }; + + return CustomHttpPattern; + })(); + + api.CommonLanguageSettings = (function() { + + /** + * Properties of a CommonLanguageSettings. + * @memberof google.api + * @interface ICommonLanguageSettings + * @property {string|null} [referenceDocsUri] CommonLanguageSettings referenceDocsUri + * @property {Array.|null} [destinations] CommonLanguageSettings destinations + * @property {google.api.ISelectiveGapicGeneration|null} [selectiveGapicGeneration] CommonLanguageSettings selectiveGapicGeneration + */ + + /** + * Constructs a new CommonLanguageSettings. + * @memberof google.api + * @classdesc Represents a CommonLanguageSettings. + * @implements ICommonLanguageSettings + * @constructor + * @param {google.api.ICommonLanguageSettings=} [properties] Properties to set + */ + function CommonLanguageSettings(properties) { + this.destinations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CommonLanguageSettings referenceDocsUri. + * @member {string} referenceDocsUri + * @memberof google.api.CommonLanguageSettings + * @instance + */ + CommonLanguageSettings.prototype.referenceDocsUri = ""; + + /** + * CommonLanguageSettings destinations. + * @member {Array.} destinations + * @memberof google.api.CommonLanguageSettings + * @instance + */ + CommonLanguageSettings.prototype.destinations = $util.emptyArray; + + /** + * CommonLanguageSettings selectiveGapicGeneration. + * @member {google.api.ISelectiveGapicGeneration|null|undefined} selectiveGapicGeneration + * @memberof google.api.CommonLanguageSettings + * @instance + */ + CommonLanguageSettings.prototype.selectiveGapicGeneration = null; + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.CommonLanguageSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.CommonLanguageSettings} CommonLanguageSettings + */ + CommonLanguageSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.CommonLanguageSettings) + return object; + var message = new $root.google.api.CommonLanguageSettings(); + if (object.referenceDocsUri != null) + message.referenceDocsUri = String(object.referenceDocsUri); + if (object.destinations) { + if (!Array.isArray(object.destinations)) + throw TypeError(".google.api.CommonLanguageSettings.destinations: array expected"); + message.destinations = []; + for (var i = 0; i < object.destinations.length; ++i) + switch (object.destinations[i]) { + default: + if (typeof object.destinations[i] === "number") { + message.destinations[i] = object.destinations[i]; + break; + } + case "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED": + case 0: + message.destinations[i] = 0; + break; + case "GITHUB": + case 10: + message.destinations[i] = 10; + break; + case "PACKAGE_MANAGER": + case 20: + message.destinations[i] = 20; + break; + } + } + if (object.selectiveGapicGeneration != null) { + if (typeof object.selectiveGapicGeneration !== "object") + throw TypeError(".google.api.CommonLanguageSettings.selectiveGapicGeneration: object expected"); + message.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.fromObject(object.selectiveGapicGeneration); + } + return message; + }; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.CommonLanguageSettings + * @static + * @param {google.api.CommonLanguageSettings} message CommonLanguageSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CommonLanguageSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.destinations = []; + if (options.defaults) { + object.referenceDocsUri = ""; + object.selectiveGapicGeneration = null; + } + if (message.referenceDocsUri != null && message.hasOwnProperty("referenceDocsUri")) + object.referenceDocsUri = message.referenceDocsUri; + if (message.destinations && message.destinations.length) { + object.destinations = []; + for (var j = 0; j < message.destinations.length; ++j) + object.destinations[j] = options.enums === String ? $root.google.api.ClientLibraryDestination[message.destinations[j]] === undefined ? message.destinations[j] : $root.google.api.ClientLibraryDestination[message.destinations[j]] : message.destinations[j]; + } + if (message.selectiveGapicGeneration != null && message.hasOwnProperty("selectiveGapicGeneration")) + object.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.toObject(message.selectiveGapicGeneration, options); + return object; + }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @function toJSON + * @memberof google.api.CommonLanguageSettings + * @instance + * @returns {Object.} JSON object + */ + CommonLanguageSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CommonLanguageSettings + * @function getTypeUrl + * @memberof google.api.CommonLanguageSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CommonLanguageSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.CommonLanguageSettings"; + }; + + return CommonLanguageSettings; + })(); + + api.ClientLibrarySettings = (function() { + + /** + * Properties of a ClientLibrarySettings. + * @memberof google.api + * @interface IClientLibrarySettings + * @property {string|null} [version] ClientLibrarySettings version + * @property {google.api.LaunchStage|null} [launchStage] ClientLibrarySettings launchStage + * @property {boolean|null} [restNumericEnums] ClientLibrarySettings restNumericEnums + * @property {google.api.IJavaSettings|null} [javaSettings] ClientLibrarySettings javaSettings + * @property {google.api.ICppSettings|null} [cppSettings] ClientLibrarySettings cppSettings + * @property {google.api.IPhpSettings|null} [phpSettings] ClientLibrarySettings phpSettings + * @property {google.api.IPythonSettings|null} [pythonSettings] ClientLibrarySettings pythonSettings + * @property {google.api.INodeSettings|null} [nodeSettings] ClientLibrarySettings nodeSettings + * @property {google.api.IDotnetSettings|null} [dotnetSettings] ClientLibrarySettings dotnetSettings + * @property {google.api.IRubySettings|null} [rubySettings] ClientLibrarySettings rubySettings + * @property {google.api.IGoSettings|null} [goSettings] ClientLibrarySettings goSettings + */ + + /** + * Constructs a new ClientLibrarySettings. + * @memberof google.api + * @classdesc Represents a ClientLibrarySettings. + * @implements IClientLibrarySettings + * @constructor + * @param {google.api.IClientLibrarySettings=} [properties] Properties to set + */ + function ClientLibrarySettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ClientLibrarySettings version. + * @member {string} version + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.version = ""; + + /** + * ClientLibrarySettings launchStage. + * @member {google.api.LaunchStage} launchStage + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.launchStage = 0; + + /** + * ClientLibrarySettings restNumericEnums. + * @member {boolean} restNumericEnums + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.restNumericEnums = false; + + /** + * ClientLibrarySettings javaSettings. + * @member {google.api.IJavaSettings|null|undefined} javaSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.javaSettings = null; + + /** + * ClientLibrarySettings cppSettings. + * @member {google.api.ICppSettings|null|undefined} cppSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.cppSettings = null; + + /** + * ClientLibrarySettings phpSettings. + * @member {google.api.IPhpSettings|null|undefined} phpSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.phpSettings = null; + + /** + * ClientLibrarySettings pythonSettings. + * @member {google.api.IPythonSettings|null|undefined} pythonSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.pythonSettings = null; + + /** + * ClientLibrarySettings nodeSettings. + * @member {google.api.INodeSettings|null|undefined} nodeSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.nodeSettings = null; + + /** + * ClientLibrarySettings dotnetSettings. + * @member {google.api.IDotnetSettings|null|undefined} dotnetSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.dotnetSettings = null; + + /** + * ClientLibrarySettings rubySettings. + * @member {google.api.IRubySettings|null|undefined} rubySettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.rubySettings = null; + + /** + * ClientLibrarySettings goSettings. + * @member {google.api.IGoSettings|null|undefined} goSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.goSettings = null; + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ClientLibrarySettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.ClientLibrarySettings} ClientLibrarySettings + */ + ClientLibrarySettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ClientLibrarySettings) + return object; + var message = new $root.google.api.ClientLibrarySettings(); + if (object.version != null) + message.version = String(object.version); + switch (object.launchStage) { + default: + if (typeof object.launchStage === "number") { + message.launchStage = object.launchStage; + break; + } + break; + case "LAUNCH_STAGE_UNSPECIFIED": + case 0: + message.launchStage = 0; + break; + case "UNIMPLEMENTED": + case 6: + message.launchStage = 6; + break; + case "PRELAUNCH": + case 7: + message.launchStage = 7; + break; + case "EARLY_ACCESS": + case 1: + message.launchStage = 1; + break; + case "ALPHA": + case 2: + message.launchStage = 2; + break; + case "BETA": + case 3: + message.launchStage = 3; + break; + case "GA": + case 4: + message.launchStage = 4; + break; + case "DEPRECATED": + case 5: + message.launchStage = 5; + break; + } + if (object.restNumericEnums != null) + message.restNumericEnums = Boolean(object.restNumericEnums); + if (object.javaSettings != null) { + if (typeof object.javaSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.javaSettings: object expected"); + message.javaSettings = $root.google.api.JavaSettings.fromObject(object.javaSettings); + } + if (object.cppSettings != null) { + if (typeof object.cppSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.cppSettings: object expected"); + message.cppSettings = $root.google.api.CppSettings.fromObject(object.cppSettings); + } + if (object.phpSettings != null) { + if (typeof object.phpSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.phpSettings: object expected"); + message.phpSettings = $root.google.api.PhpSettings.fromObject(object.phpSettings); + } + if (object.pythonSettings != null) { + if (typeof object.pythonSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.pythonSettings: object expected"); + message.pythonSettings = $root.google.api.PythonSettings.fromObject(object.pythonSettings); + } + if (object.nodeSettings != null) { + if (typeof object.nodeSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.nodeSettings: object expected"); + message.nodeSettings = $root.google.api.NodeSettings.fromObject(object.nodeSettings); + } + if (object.dotnetSettings != null) { + if (typeof object.dotnetSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.dotnetSettings: object expected"); + message.dotnetSettings = $root.google.api.DotnetSettings.fromObject(object.dotnetSettings); + } + if (object.rubySettings != null) { + if (typeof object.rubySettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.rubySettings: object expected"); + message.rubySettings = $root.google.api.RubySettings.fromObject(object.rubySettings); + } + if (object.goSettings != null) { + if (typeof object.goSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.goSettings: object expected"); + message.goSettings = $root.google.api.GoSettings.fromObject(object.goSettings); + } + return message; + }; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ClientLibrarySettings + * @static + * @param {google.api.ClientLibrarySettings} message ClientLibrarySettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ClientLibrarySettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.version = ""; + object.launchStage = options.enums === String ? "LAUNCH_STAGE_UNSPECIFIED" : 0; + object.restNumericEnums = false; + object.javaSettings = null; + object.cppSettings = null; + object.phpSettings = null; + object.pythonSettings = null; + object.nodeSettings = null; + object.dotnetSettings = null; + object.rubySettings = null; + object.goSettings = null; + } + if (message.version != null && message.hasOwnProperty("version")) + object.version = message.version; + if (message.launchStage != null && message.hasOwnProperty("launchStage")) + object.launchStage = options.enums === String ? $root.google.api.LaunchStage[message.launchStage] === undefined ? message.launchStage : $root.google.api.LaunchStage[message.launchStage] : message.launchStage; + if (message.restNumericEnums != null && message.hasOwnProperty("restNumericEnums")) + object.restNumericEnums = message.restNumericEnums; + if (message.javaSettings != null && message.hasOwnProperty("javaSettings")) + object.javaSettings = $root.google.api.JavaSettings.toObject(message.javaSettings, options); + if (message.cppSettings != null && message.hasOwnProperty("cppSettings")) + object.cppSettings = $root.google.api.CppSettings.toObject(message.cppSettings, options); + if (message.phpSettings != null && message.hasOwnProperty("phpSettings")) + object.phpSettings = $root.google.api.PhpSettings.toObject(message.phpSettings, options); + if (message.pythonSettings != null && message.hasOwnProperty("pythonSettings")) + object.pythonSettings = $root.google.api.PythonSettings.toObject(message.pythonSettings, options); + if (message.nodeSettings != null && message.hasOwnProperty("nodeSettings")) + object.nodeSettings = $root.google.api.NodeSettings.toObject(message.nodeSettings, options); + if (message.dotnetSettings != null && message.hasOwnProperty("dotnetSettings")) + object.dotnetSettings = $root.google.api.DotnetSettings.toObject(message.dotnetSettings, options); + if (message.rubySettings != null && message.hasOwnProperty("rubySettings")) + object.rubySettings = $root.google.api.RubySettings.toObject(message.rubySettings, options); + if (message.goSettings != null && message.hasOwnProperty("goSettings")) + object.goSettings = $root.google.api.GoSettings.toObject(message.goSettings, options); + return object; + }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @function toJSON + * @memberof google.api.ClientLibrarySettings + * @instance + * @returns {Object.} JSON object + */ + ClientLibrarySettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ClientLibrarySettings + * @function getTypeUrl + * @memberof google.api.ClientLibrarySettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ClientLibrarySettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ClientLibrarySettings"; + }; + + return ClientLibrarySettings; + })(); + + api.Publishing = (function() { + + /** + * Properties of a Publishing. + * @memberof google.api + * @interface IPublishing + * @property {Array.|null} [methodSettings] Publishing methodSettings + * @property {string|null} [newIssueUri] Publishing newIssueUri + * @property {string|null} [documentationUri] Publishing documentationUri + * @property {string|null} [apiShortName] Publishing apiShortName + * @property {string|null} [githubLabel] Publishing githubLabel + * @property {Array.|null} [codeownerGithubTeams] Publishing codeownerGithubTeams + * @property {string|null} [docTagPrefix] Publishing docTagPrefix + * @property {google.api.ClientLibraryOrganization|null} [organization] Publishing organization + * @property {Array.|null} [librarySettings] Publishing librarySettings + * @property {string|null} [protoReferenceDocumentationUri] Publishing protoReferenceDocumentationUri + * @property {string|null} [restReferenceDocumentationUri] Publishing restReferenceDocumentationUri + */ + + /** + * Constructs a new Publishing. + * @memberof google.api + * @classdesc Represents a Publishing. + * @implements IPublishing + * @constructor + * @param {google.api.IPublishing=} [properties] Properties to set + */ + function Publishing(properties) { + this.methodSettings = []; + this.codeownerGithubTeams = []; + this.librarySettings = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Publishing methodSettings. + * @member {Array.} methodSettings + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.methodSettings = $util.emptyArray; + + /** + * Publishing newIssueUri. + * @member {string} newIssueUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.newIssueUri = ""; + + /** + * Publishing documentationUri. + * @member {string} documentationUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.documentationUri = ""; + + /** + * Publishing apiShortName. + * @member {string} apiShortName + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.apiShortName = ""; + + /** + * Publishing githubLabel. + * @member {string} githubLabel + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.githubLabel = ""; + + /** + * Publishing codeownerGithubTeams. + * @member {Array.} codeownerGithubTeams + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.codeownerGithubTeams = $util.emptyArray; + + /** + * Publishing docTagPrefix. + * @member {string} docTagPrefix + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.docTagPrefix = ""; + + /** + * Publishing organization. + * @member {google.api.ClientLibraryOrganization} organization + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.organization = 0; + + /** + * Publishing librarySettings. + * @member {Array.} librarySettings + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.librarySettings = $util.emptyArray; + + /** + * Publishing protoReferenceDocumentationUri. + * @member {string} protoReferenceDocumentationUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.protoReferenceDocumentationUri = ""; + + /** + * Publishing restReferenceDocumentationUri. + * @member {string} restReferenceDocumentationUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.restReferenceDocumentationUri = ""; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.Publishing + * @static + * @param {Object.} object Plain object + * @returns {google.api.Publishing} Publishing + */ + Publishing.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.Publishing) + return object; + var message = new $root.google.api.Publishing(); + if (object.methodSettings) { + if (!Array.isArray(object.methodSettings)) + throw TypeError(".google.api.Publishing.methodSettings: array expected"); + message.methodSettings = []; + for (var i = 0; i < object.methodSettings.length; ++i) { + if (typeof object.methodSettings[i] !== "object") + throw TypeError(".google.api.Publishing.methodSettings: object expected"); + message.methodSettings[i] = $root.google.api.MethodSettings.fromObject(object.methodSettings[i]); + } + } + if (object.newIssueUri != null) + message.newIssueUri = String(object.newIssueUri); + if (object.documentationUri != null) + message.documentationUri = String(object.documentationUri); + if (object.apiShortName != null) + message.apiShortName = String(object.apiShortName); + if (object.githubLabel != null) + message.githubLabel = String(object.githubLabel); + if (object.codeownerGithubTeams) { + if (!Array.isArray(object.codeownerGithubTeams)) + throw TypeError(".google.api.Publishing.codeownerGithubTeams: array expected"); + message.codeownerGithubTeams = []; + for (var i = 0; i < object.codeownerGithubTeams.length; ++i) + message.codeownerGithubTeams[i] = String(object.codeownerGithubTeams[i]); + } + if (object.docTagPrefix != null) + message.docTagPrefix = String(object.docTagPrefix); + switch (object.organization) { + default: + if (typeof object.organization === "number") { + message.organization = object.organization; + break; + } + break; + case "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED": + case 0: + message.organization = 0; + break; + case "CLOUD": + case 1: + message.organization = 1; + break; + case "ADS": + case 2: + message.organization = 2; + break; + case "PHOTOS": + case 3: + message.organization = 3; + break; + case "STREET_VIEW": + case 4: + message.organization = 4; + break; + case "SHOPPING": + case 5: + message.organization = 5; + break; + case "GEO": + case 6: + message.organization = 6; + break; + case "GENERATIVE_AI": + case 7: + message.organization = 7; + break; + } + if (object.librarySettings) { + if (!Array.isArray(object.librarySettings)) + throw TypeError(".google.api.Publishing.librarySettings: array expected"); + message.librarySettings = []; + for (var i = 0; i < object.librarySettings.length; ++i) { + if (typeof object.librarySettings[i] !== "object") + throw TypeError(".google.api.Publishing.librarySettings: object expected"); + message.librarySettings[i] = $root.google.api.ClientLibrarySettings.fromObject(object.librarySettings[i]); + } + } + if (object.protoReferenceDocumentationUri != null) + message.protoReferenceDocumentationUri = String(object.protoReferenceDocumentationUri); + if (object.restReferenceDocumentationUri != null) + message.restReferenceDocumentationUri = String(object.restReferenceDocumentationUri); + return message; + }; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.Publishing + * @static + * @param {google.api.Publishing} message Publishing + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Publishing.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.methodSettings = []; + object.codeownerGithubTeams = []; + object.librarySettings = []; + } + if (options.defaults) { + object.newIssueUri = ""; + object.documentationUri = ""; + object.apiShortName = ""; + object.githubLabel = ""; + object.docTagPrefix = ""; + object.organization = options.enums === String ? "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED" : 0; + object.protoReferenceDocumentationUri = ""; + object.restReferenceDocumentationUri = ""; + } + if (message.methodSettings && message.methodSettings.length) { + object.methodSettings = []; + for (var j = 0; j < message.methodSettings.length; ++j) + object.methodSettings[j] = $root.google.api.MethodSettings.toObject(message.methodSettings[j], options); + } + if (message.newIssueUri != null && message.hasOwnProperty("newIssueUri")) + object.newIssueUri = message.newIssueUri; + if (message.documentationUri != null && message.hasOwnProperty("documentationUri")) + object.documentationUri = message.documentationUri; + if (message.apiShortName != null && message.hasOwnProperty("apiShortName")) + object.apiShortName = message.apiShortName; + if (message.githubLabel != null && message.hasOwnProperty("githubLabel")) + object.githubLabel = message.githubLabel; + if (message.codeownerGithubTeams && message.codeownerGithubTeams.length) { + object.codeownerGithubTeams = []; + for (var j = 0; j < message.codeownerGithubTeams.length; ++j) + object.codeownerGithubTeams[j] = message.codeownerGithubTeams[j]; + } + if (message.docTagPrefix != null && message.hasOwnProperty("docTagPrefix")) + object.docTagPrefix = message.docTagPrefix; + if (message.organization != null && message.hasOwnProperty("organization")) + object.organization = options.enums === String ? $root.google.api.ClientLibraryOrganization[message.organization] === undefined ? message.organization : $root.google.api.ClientLibraryOrganization[message.organization] : message.organization; + if (message.librarySettings && message.librarySettings.length) { + object.librarySettings = []; + for (var j = 0; j < message.librarySettings.length; ++j) + object.librarySettings[j] = $root.google.api.ClientLibrarySettings.toObject(message.librarySettings[j], options); + } + if (message.protoReferenceDocumentationUri != null && message.hasOwnProperty("protoReferenceDocumentationUri")) + object.protoReferenceDocumentationUri = message.protoReferenceDocumentationUri; + if (message.restReferenceDocumentationUri != null && message.hasOwnProperty("restReferenceDocumentationUri")) + object.restReferenceDocumentationUri = message.restReferenceDocumentationUri; + return object; + }; + + /** + * Converts this Publishing to JSON. + * @function toJSON + * @memberof google.api.Publishing + * @instance + * @returns {Object.} JSON object + */ + Publishing.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Publishing + * @function getTypeUrl + * @memberof google.api.Publishing + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Publishing.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.Publishing"; + }; + + return Publishing; + })(); + + api.JavaSettings = (function() { + + /** + * Properties of a JavaSettings. + * @memberof google.api + * @interface IJavaSettings + * @property {string|null} [libraryPackage] JavaSettings libraryPackage + * @property {Object.|null} [serviceClassNames] JavaSettings serviceClassNames + * @property {google.api.ICommonLanguageSettings|null} [common] JavaSettings common + */ + + /** + * Constructs a new JavaSettings. + * @memberof google.api + * @classdesc Represents a JavaSettings. + * @implements IJavaSettings + * @constructor + * @param {google.api.IJavaSettings=} [properties] Properties to set + */ + function JavaSettings(properties) { + this.serviceClassNames = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * JavaSettings libraryPackage. + * @member {string} libraryPackage + * @memberof google.api.JavaSettings + * @instance + */ + JavaSettings.prototype.libraryPackage = ""; + + /** + * JavaSettings serviceClassNames. + * @member {Object.} serviceClassNames + * @memberof google.api.JavaSettings + * @instance + */ + JavaSettings.prototype.serviceClassNames = $util.emptyObject; + + /** + * JavaSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.JavaSettings + * @instance + */ + JavaSettings.prototype.common = null; + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.JavaSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.JavaSettings} JavaSettings + */ + JavaSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.JavaSettings) + return object; + var message = new $root.google.api.JavaSettings(); + if (object.libraryPackage != null) + message.libraryPackage = String(object.libraryPackage); + if (object.serviceClassNames) { + if (typeof object.serviceClassNames !== "object") + throw TypeError(".google.api.JavaSettings.serviceClassNames: object expected"); + message.serviceClassNames = {}; + for (var keys = Object.keys(object.serviceClassNames), i = 0; i < keys.length; ++i) + message.serviceClassNames[keys[i]] = String(object.serviceClassNames[keys[i]]); + } + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.JavaSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.JavaSettings + * @static + * @param {google.api.JavaSettings} message JavaSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + JavaSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.serviceClassNames = {}; + if (options.defaults) { + object.libraryPackage = ""; + object.common = null; + } + if (message.libraryPackage != null && message.hasOwnProperty("libraryPackage")) + object.libraryPackage = message.libraryPackage; + var keys2; + if (message.serviceClassNames && (keys2 = Object.keys(message.serviceClassNames)).length) { + object.serviceClassNames = {}; + for (var j = 0; j < keys2.length; ++j) + object.serviceClassNames[keys2[j]] = message.serviceClassNames[keys2[j]]; + } + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this JavaSettings to JSON. + * @function toJSON + * @memberof google.api.JavaSettings + * @instance + * @returns {Object.} JSON object + */ + JavaSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for JavaSettings + * @function getTypeUrl + * @memberof google.api.JavaSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + JavaSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.JavaSettings"; + }; + + return JavaSettings; + })(); + + api.CppSettings = (function() { + + /** + * Properties of a CppSettings. + * @memberof google.api + * @interface ICppSettings + * @property {google.api.ICommonLanguageSettings|null} [common] CppSettings common + */ + + /** + * Constructs a new CppSettings. + * @memberof google.api + * @classdesc Represents a CppSettings. + * @implements ICppSettings + * @constructor + * @param {google.api.ICppSettings=} [properties] Properties to set + */ + function CppSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CppSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.CppSettings + * @instance + */ + CppSettings.prototype.common = null; + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.CppSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.CppSettings} CppSettings + */ + CppSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.CppSettings) + return object; + var message = new $root.google.api.CppSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.CppSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.CppSettings + * @static + * @param {google.api.CppSettings} message CppSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CppSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this CppSettings to JSON. + * @function toJSON + * @memberof google.api.CppSettings + * @instance + * @returns {Object.} JSON object + */ + CppSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CppSettings + * @function getTypeUrl + * @memberof google.api.CppSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CppSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.CppSettings"; + }; + + return CppSettings; + })(); + + api.PhpSettings = (function() { + + /** + * Properties of a PhpSettings. + * @memberof google.api + * @interface IPhpSettings + * @property {google.api.ICommonLanguageSettings|null} [common] PhpSettings common + */ + + /** + * Constructs a new PhpSettings. + * @memberof google.api + * @classdesc Represents a PhpSettings. + * @implements IPhpSettings + * @constructor + * @param {google.api.IPhpSettings=} [properties] Properties to set + */ + function PhpSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PhpSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.PhpSettings + * @instance + */ + PhpSettings.prototype.common = null; + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.PhpSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.PhpSettings} PhpSettings + */ + PhpSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.PhpSettings) + return object; + var message = new $root.google.api.PhpSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.PhpSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.PhpSettings + * @static + * @param {google.api.PhpSettings} message PhpSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PhpSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this PhpSettings to JSON. + * @function toJSON + * @memberof google.api.PhpSettings + * @instance + * @returns {Object.} JSON object + */ + PhpSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PhpSettings + * @function getTypeUrl + * @memberof google.api.PhpSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PhpSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.PhpSettings"; + }; + + return PhpSettings; + })(); + + api.PythonSettings = (function() { + + /** + * Properties of a PythonSettings. + * @memberof google.api + * @interface IPythonSettings + * @property {google.api.ICommonLanguageSettings|null} [common] PythonSettings common + * @property {google.api.PythonSettings.IExperimentalFeatures|null} [experimentalFeatures] PythonSettings experimentalFeatures + */ + + /** + * Constructs a new PythonSettings. + * @memberof google.api + * @classdesc Represents a PythonSettings. + * @implements IPythonSettings + * @constructor + * @param {google.api.IPythonSettings=} [properties] Properties to set + */ + function PythonSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PythonSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.PythonSettings + * @instance + */ + PythonSettings.prototype.common = null; + + /** + * PythonSettings experimentalFeatures. + * @member {google.api.PythonSettings.IExperimentalFeatures|null|undefined} experimentalFeatures + * @memberof google.api.PythonSettings + * @instance + */ + PythonSettings.prototype.experimentalFeatures = null; + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.PythonSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.PythonSettings} PythonSettings + */ + PythonSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.PythonSettings) + return object; + var message = new $root.google.api.PythonSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.PythonSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + if (object.experimentalFeatures != null) { + if (typeof object.experimentalFeatures !== "object") + throw TypeError(".google.api.PythonSettings.experimentalFeatures: object expected"); + message.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.fromObject(object.experimentalFeatures); + } + return message; + }; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.PythonSettings + * @static + * @param {google.api.PythonSettings} message PythonSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PythonSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.common = null; + object.experimentalFeatures = null; + } + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + if (message.experimentalFeatures != null && message.hasOwnProperty("experimentalFeatures")) + object.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.toObject(message.experimentalFeatures, options); + return object; + }; + + /** + * Converts this PythonSettings to JSON. + * @function toJSON + * @memberof google.api.PythonSettings + * @instance + * @returns {Object.} JSON object + */ + PythonSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PythonSettings + * @function getTypeUrl + * @memberof google.api.PythonSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PythonSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.PythonSettings"; + }; + + PythonSettings.ExperimentalFeatures = (function() { + + /** + * Properties of an ExperimentalFeatures. + * @memberof google.api.PythonSettings + * @interface IExperimentalFeatures + * @property {boolean|null} [restAsyncIoEnabled] ExperimentalFeatures restAsyncIoEnabled + * @property {boolean|null} [protobufPythonicTypesEnabled] ExperimentalFeatures protobufPythonicTypesEnabled + * @property {boolean|null} [unversionedPackageDisabled] ExperimentalFeatures unversionedPackageDisabled + */ + + /** + * Constructs a new ExperimentalFeatures. + * @memberof google.api.PythonSettings + * @classdesc Represents an ExperimentalFeatures. + * @implements IExperimentalFeatures + * @constructor + * @param {google.api.PythonSettings.IExperimentalFeatures=} [properties] Properties to set + */ + function ExperimentalFeatures(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExperimentalFeatures restAsyncIoEnabled. + * @member {boolean} restAsyncIoEnabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.restAsyncIoEnabled = false; + + /** + * ExperimentalFeatures protobufPythonicTypesEnabled. + * @member {boolean} protobufPythonicTypesEnabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.protobufPythonicTypesEnabled = false; + + /** + * ExperimentalFeatures unversionedPackageDisabled. + * @member {boolean} unversionedPackageDisabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.unversionedPackageDisabled = false; + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {Object.} object Plain object + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + */ + ExperimentalFeatures.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.PythonSettings.ExperimentalFeatures) + return object; + var message = new $root.google.api.PythonSettings.ExperimentalFeatures(); + if (object.restAsyncIoEnabled != null) + message.restAsyncIoEnabled = Boolean(object.restAsyncIoEnabled); + if (object.protobufPythonicTypesEnabled != null) + message.protobufPythonicTypesEnabled = Boolean(object.protobufPythonicTypesEnabled); + if (object.unversionedPackageDisabled != null) + message.unversionedPackageDisabled = Boolean(object.unversionedPackageDisabled); + return message; + }; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.ExperimentalFeatures} message ExperimentalFeatures + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExperimentalFeatures.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.restAsyncIoEnabled = false; + object.protobufPythonicTypesEnabled = false; + object.unversionedPackageDisabled = false; + } + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + object.restAsyncIoEnabled = message.restAsyncIoEnabled; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + object.protobufPythonicTypesEnabled = message.protobufPythonicTypesEnabled; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + object.unversionedPackageDisabled = message.unversionedPackageDisabled; + return object; + }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @function toJSON + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + * @returns {Object.} JSON object + */ + ExperimentalFeatures.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExperimentalFeatures + * @function getTypeUrl + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExperimentalFeatures.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.PythonSettings.ExperimentalFeatures"; + }; + + return ExperimentalFeatures; + })(); + + return PythonSettings; + })(); + + api.NodeSettings = (function() { + + /** + * Properties of a NodeSettings. + * @memberof google.api + * @interface INodeSettings + * @property {google.api.ICommonLanguageSettings|null} [common] NodeSettings common + */ + + /** + * Constructs a new NodeSettings. + * @memberof google.api + * @classdesc Represents a NodeSettings. + * @implements INodeSettings + * @constructor + * @param {google.api.INodeSettings=} [properties] Properties to set + */ + function NodeSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * NodeSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.NodeSettings + * @instance + */ + NodeSettings.prototype.common = null; + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.NodeSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.NodeSettings} NodeSettings + */ + NodeSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.NodeSettings) + return object; + var message = new $root.google.api.NodeSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.NodeSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.NodeSettings + * @static + * @param {google.api.NodeSettings} message NodeSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + NodeSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this NodeSettings to JSON. + * @function toJSON + * @memberof google.api.NodeSettings + * @instance + * @returns {Object.} JSON object + */ + NodeSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for NodeSettings + * @function getTypeUrl + * @memberof google.api.NodeSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + NodeSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.NodeSettings"; + }; + + return NodeSettings; + })(); + + api.DotnetSettings = (function() { + + /** + * Properties of a DotnetSettings. + * @memberof google.api + * @interface IDotnetSettings + * @property {google.api.ICommonLanguageSettings|null} [common] DotnetSettings common + * @property {Object.|null} [renamedServices] DotnetSettings renamedServices + * @property {Object.|null} [renamedResources] DotnetSettings renamedResources + * @property {Array.|null} [ignoredResources] DotnetSettings ignoredResources + * @property {Array.|null} [forcedNamespaceAliases] DotnetSettings forcedNamespaceAliases + * @property {Array.|null} [handwrittenSignatures] DotnetSettings handwrittenSignatures + */ + + /** + * Constructs a new DotnetSettings. + * @memberof google.api + * @classdesc Represents a DotnetSettings. + * @implements IDotnetSettings + * @constructor + * @param {google.api.IDotnetSettings=} [properties] Properties to set + */ + function DotnetSettings(properties) { + this.renamedServices = {}; + this.renamedResources = {}; + this.ignoredResources = []; + this.forcedNamespaceAliases = []; + this.handwrittenSignatures = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DotnetSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.common = null; + + /** + * DotnetSettings renamedServices. + * @member {Object.} renamedServices + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.renamedServices = $util.emptyObject; + + /** + * DotnetSettings renamedResources. + * @member {Object.} renamedResources + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.renamedResources = $util.emptyObject; + + /** + * DotnetSettings ignoredResources. + * @member {Array.} ignoredResources + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.ignoredResources = $util.emptyArray; + + /** + * DotnetSettings forcedNamespaceAliases. + * @member {Array.} forcedNamespaceAliases + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.forcedNamespaceAliases = $util.emptyArray; + + /** + * DotnetSettings handwrittenSignatures. + * @member {Array.} handwrittenSignatures + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.handwrittenSignatures = $util.emptyArray; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.DotnetSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.DotnetSettings} DotnetSettings + */ + DotnetSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.DotnetSettings) + return object; + var message = new $root.google.api.DotnetSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.DotnetSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + if (object.renamedServices) { + if (typeof object.renamedServices !== "object") + throw TypeError(".google.api.DotnetSettings.renamedServices: object expected"); + message.renamedServices = {}; + for (var keys = Object.keys(object.renamedServices), i = 0; i < keys.length; ++i) + message.renamedServices[keys[i]] = String(object.renamedServices[keys[i]]); + } + if (object.renamedResources) { + if (typeof object.renamedResources !== "object") + throw TypeError(".google.api.DotnetSettings.renamedResources: object expected"); + message.renamedResources = {}; + for (var keys = Object.keys(object.renamedResources), i = 0; i < keys.length; ++i) + message.renamedResources[keys[i]] = String(object.renamedResources[keys[i]]); + } + if (object.ignoredResources) { + if (!Array.isArray(object.ignoredResources)) + throw TypeError(".google.api.DotnetSettings.ignoredResources: array expected"); + message.ignoredResources = []; + for (var i = 0; i < object.ignoredResources.length; ++i) + message.ignoredResources[i] = String(object.ignoredResources[i]); + } + if (object.forcedNamespaceAliases) { + if (!Array.isArray(object.forcedNamespaceAliases)) + throw TypeError(".google.api.DotnetSettings.forcedNamespaceAliases: array expected"); + message.forcedNamespaceAliases = []; + for (var i = 0; i < object.forcedNamespaceAliases.length; ++i) + message.forcedNamespaceAliases[i] = String(object.forcedNamespaceAliases[i]); + } + if (object.handwrittenSignatures) { + if (!Array.isArray(object.handwrittenSignatures)) + throw TypeError(".google.api.DotnetSettings.handwrittenSignatures: array expected"); + message.handwrittenSignatures = []; + for (var i = 0; i < object.handwrittenSignatures.length; ++i) + message.handwrittenSignatures[i] = String(object.handwrittenSignatures[i]); + } + return message; + }; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.DotnetSettings + * @static + * @param {google.api.DotnetSettings} message DotnetSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DotnetSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.ignoredResources = []; + object.forcedNamespaceAliases = []; + object.handwrittenSignatures = []; + } + if (options.objects || options.defaults) { + object.renamedServices = {}; + object.renamedResources = {}; + } + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + var keys2; + if (message.renamedServices && (keys2 = Object.keys(message.renamedServices)).length) { + object.renamedServices = {}; + for (var j = 0; j < keys2.length; ++j) + object.renamedServices[keys2[j]] = message.renamedServices[keys2[j]]; + } + if (message.renamedResources && (keys2 = Object.keys(message.renamedResources)).length) { + object.renamedResources = {}; + for (var j = 0; j < keys2.length; ++j) + object.renamedResources[keys2[j]] = message.renamedResources[keys2[j]]; + } + if (message.ignoredResources && message.ignoredResources.length) { + object.ignoredResources = []; + for (var j = 0; j < message.ignoredResources.length; ++j) + object.ignoredResources[j] = message.ignoredResources[j]; + } + if (message.forcedNamespaceAliases && message.forcedNamespaceAliases.length) { + object.forcedNamespaceAliases = []; + for (var j = 0; j < message.forcedNamespaceAliases.length; ++j) + object.forcedNamespaceAliases[j] = message.forcedNamespaceAliases[j]; + } + if (message.handwrittenSignatures && message.handwrittenSignatures.length) { + object.handwrittenSignatures = []; + for (var j = 0; j < message.handwrittenSignatures.length; ++j) + object.handwrittenSignatures[j] = message.handwrittenSignatures[j]; + } + return object; + }; + + /** + * Converts this DotnetSettings to JSON. + * @function toJSON + * @memberof google.api.DotnetSettings + * @instance + * @returns {Object.} JSON object + */ + DotnetSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DotnetSettings + * @function getTypeUrl + * @memberof google.api.DotnetSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DotnetSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.DotnetSettings"; + }; + + return DotnetSettings; + })(); + + api.RubySettings = (function() { + + /** + * Properties of a RubySettings. + * @memberof google.api + * @interface IRubySettings + * @property {google.api.ICommonLanguageSettings|null} [common] RubySettings common + */ + + /** + * Constructs a new RubySettings. + * @memberof google.api + * @classdesc Represents a RubySettings. + * @implements IRubySettings + * @constructor + * @param {google.api.IRubySettings=} [properties] Properties to set + */ + function RubySettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RubySettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.RubySettings + * @instance + */ + RubySettings.prototype.common = null; + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.RubySettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.RubySettings} RubySettings + */ + RubySettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RubySettings) + return object; + var message = new $root.google.api.RubySettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.RubySettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.RubySettings + * @static + * @param {google.api.RubySettings} message RubySettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RubySettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this RubySettings to JSON. + * @function toJSON + * @memberof google.api.RubySettings + * @instance + * @returns {Object.} JSON object + */ + RubySettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RubySettings + * @function getTypeUrl + * @memberof google.api.RubySettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RubySettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.RubySettings"; + }; + + return RubySettings; + })(); + + api.GoSettings = (function() { + + /** + * Properties of a GoSettings. + * @memberof google.api + * @interface IGoSettings + * @property {google.api.ICommonLanguageSettings|null} [common] GoSettings common + * @property {Object.|null} [renamedServices] GoSettings renamedServices + */ + + /** + * Constructs a new GoSettings. + * @memberof google.api + * @classdesc Represents a GoSettings. + * @implements IGoSettings + * @constructor + * @param {google.api.IGoSettings=} [properties] Properties to set + */ + function GoSettings(properties) { + this.renamedServices = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GoSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.GoSettings + * @instance + */ + GoSettings.prototype.common = null; + + /** + * GoSettings renamedServices. + * @member {Object.} renamedServices + * @memberof google.api.GoSettings + * @instance + */ + GoSettings.prototype.renamedServices = $util.emptyObject; + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.GoSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.GoSettings} GoSettings + */ + GoSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.GoSettings) + return object; + var message = new $root.google.api.GoSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.GoSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + if (object.renamedServices) { + if (typeof object.renamedServices !== "object") + throw TypeError(".google.api.GoSettings.renamedServices: object expected"); + message.renamedServices = {}; + for (var keys = Object.keys(object.renamedServices), i = 0; i < keys.length; ++i) + message.renamedServices[keys[i]] = String(object.renamedServices[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.GoSettings + * @static + * @param {google.api.GoSettings} message GoSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GoSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.renamedServices = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + var keys2; + if (message.renamedServices && (keys2 = Object.keys(message.renamedServices)).length) { + object.renamedServices = {}; + for (var j = 0; j < keys2.length; ++j) + object.renamedServices[keys2[j]] = message.renamedServices[keys2[j]]; + } + return object; + }; + + /** + * Converts this GoSettings to JSON. + * @function toJSON + * @memberof google.api.GoSettings + * @instance + * @returns {Object.} JSON object + */ + GoSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GoSettings + * @function getTypeUrl + * @memberof google.api.GoSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GoSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.GoSettings"; + }; + + return GoSettings; + })(); + + api.MethodSettings = (function() { + + /** + * Properties of a MethodSettings. + * @memberof google.api + * @interface IMethodSettings + * @property {string|null} [selector] MethodSettings selector + * @property {google.api.MethodSettings.ILongRunning|null} [longRunning] MethodSettings longRunning + * @property {Array.|null} [autoPopulatedFields] MethodSettings autoPopulatedFields + */ + + /** + * Constructs a new MethodSettings. + * @memberof google.api + * @classdesc Represents a MethodSettings. + * @implements IMethodSettings + * @constructor + * @param {google.api.IMethodSettings=} [properties] Properties to set + */ + function MethodSettings(properties) { + this.autoPopulatedFields = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MethodSettings selector. + * @member {string} selector + * @memberof google.api.MethodSettings + * @instance + */ + MethodSettings.prototype.selector = ""; + + /** + * MethodSettings longRunning. + * @member {google.api.MethodSettings.ILongRunning|null|undefined} longRunning + * @memberof google.api.MethodSettings + * @instance + */ + MethodSettings.prototype.longRunning = null; + + /** + * MethodSettings autoPopulatedFields. + * @member {Array.} autoPopulatedFields + * @memberof google.api.MethodSettings + * @instance + */ + MethodSettings.prototype.autoPopulatedFields = $util.emptyArray; + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.MethodSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.MethodSettings} MethodSettings + */ + MethodSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.MethodSettings) + return object; + var message = new $root.google.api.MethodSettings(); + if (object.selector != null) + message.selector = String(object.selector); + if (object.longRunning != null) { + if (typeof object.longRunning !== "object") + throw TypeError(".google.api.MethodSettings.longRunning: object expected"); + message.longRunning = $root.google.api.MethodSettings.LongRunning.fromObject(object.longRunning); + } + if (object.autoPopulatedFields) { + if (!Array.isArray(object.autoPopulatedFields)) + throw TypeError(".google.api.MethodSettings.autoPopulatedFields: array expected"); + message.autoPopulatedFields = []; + for (var i = 0; i < object.autoPopulatedFields.length; ++i) + message.autoPopulatedFields[i] = String(object.autoPopulatedFields[i]); + } + return message; + }; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.MethodSettings + * @static + * @param {google.api.MethodSettings} message MethodSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MethodSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.autoPopulatedFields = []; + if (options.defaults) { + object.selector = ""; + object.longRunning = null; + } + if (message.selector != null && message.hasOwnProperty("selector")) + object.selector = message.selector; + if (message.longRunning != null && message.hasOwnProperty("longRunning")) + object.longRunning = $root.google.api.MethodSettings.LongRunning.toObject(message.longRunning, options); + if (message.autoPopulatedFields && message.autoPopulatedFields.length) { + object.autoPopulatedFields = []; + for (var j = 0; j < message.autoPopulatedFields.length; ++j) + object.autoPopulatedFields[j] = message.autoPopulatedFields[j]; + } + return object; + }; + + /** + * Converts this MethodSettings to JSON. + * @function toJSON + * @memberof google.api.MethodSettings + * @instance + * @returns {Object.} JSON object + */ + MethodSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MethodSettings + * @function getTypeUrl + * @memberof google.api.MethodSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MethodSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.MethodSettings"; + }; + + MethodSettings.LongRunning = (function() { + + /** + * Properties of a LongRunning. + * @memberof google.api.MethodSettings + * @interface ILongRunning + * @property {google.protobuf.IDuration|null} [initialPollDelay] LongRunning initialPollDelay + * @property {number|null} [pollDelayMultiplier] LongRunning pollDelayMultiplier + * @property {google.protobuf.IDuration|null} [maxPollDelay] LongRunning maxPollDelay + * @property {google.protobuf.IDuration|null} [totalPollTimeout] LongRunning totalPollTimeout + */ + + /** + * Constructs a new LongRunning. + * @memberof google.api.MethodSettings + * @classdesc Represents a LongRunning. + * @implements ILongRunning + * @constructor + * @param {google.api.MethodSettings.ILongRunning=} [properties] Properties to set + */ + function LongRunning(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * LongRunning initialPollDelay. + * @member {google.protobuf.IDuration|null|undefined} initialPollDelay + * @memberof google.api.MethodSettings.LongRunning + * @instance + */ + LongRunning.prototype.initialPollDelay = null; + + /** + * LongRunning pollDelayMultiplier. + * @member {number} pollDelayMultiplier + * @memberof google.api.MethodSettings.LongRunning + * @instance + */ + LongRunning.prototype.pollDelayMultiplier = 0; + + /** + * LongRunning maxPollDelay. + * @member {google.protobuf.IDuration|null|undefined} maxPollDelay + * @memberof google.api.MethodSettings.LongRunning + * @instance + */ + LongRunning.prototype.maxPollDelay = null; + + /** + * LongRunning totalPollTimeout. + * @member {google.protobuf.IDuration|null|undefined} totalPollTimeout + * @memberof google.api.MethodSettings.LongRunning + * @instance + */ + LongRunning.prototype.totalPollTimeout = null; + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {Object.} object Plain object + * @returns {google.api.MethodSettings.LongRunning} LongRunning + */ + LongRunning.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.MethodSettings.LongRunning) + return object; + var message = new $root.google.api.MethodSettings.LongRunning(); + if (object.initialPollDelay != null) { + if (typeof object.initialPollDelay !== "object") + throw TypeError(".google.api.MethodSettings.LongRunning.initialPollDelay: object expected"); + message.initialPollDelay = $root.google.protobuf.Duration.fromObject(object.initialPollDelay); + } + if (object.pollDelayMultiplier != null) + message.pollDelayMultiplier = Number(object.pollDelayMultiplier); + if (object.maxPollDelay != null) { + if (typeof object.maxPollDelay !== "object") + throw TypeError(".google.api.MethodSettings.LongRunning.maxPollDelay: object expected"); + message.maxPollDelay = $root.google.protobuf.Duration.fromObject(object.maxPollDelay); + } + if (object.totalPollTimeout != null) { + if (typeof object.totalPollTimeout !== "object") + throw TypeError(".google.api.MethodSettings.LongRunning.totalPollTimeout: object expected"); + message.totalPollTimeout = $root.google.protobuf.Duration.fromObject(object.totalPollTimeout); + } + return message; + }; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {google.api.MethodSettings.LongRunning} message LongRunning + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + LongRunning.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.initialPollDelay = null; + object.pollDelayMultiplier = 0; + object.maxPollDelay = null; + object.totalPollTimeout = null; + } + if (message.initialPollDelay != null && message.hasOwnProperty("initialPollDelay")) + object.initialPollDelay = $root.google.protobuf.Duration.toObject(message.initialPollDelay, options); + if (message.pollDelayMultiplier != null && message.hasOwnProperty("pollDelayMultiplier")) + object.pollDelayMultiplier = options.json && !isFinite(message.pollDelayMultiplier) ? String(message.pollDelayMultiplier) : message.pollDelayMultiplier; + if (message.maxPollDelay != null && message.hasOwnProperty("maxPollDelay")) + object.maxPollDelay = $root.google.protobuf.Duration.toObject(message.maxPollDelay, options); + if (message.totalPollTimeout != null && message.hasOwnProperty("totalPollTimeout")) + object.totalPollTimeout = $root.google.protobuf.Duration.toObject(message.totalPollTimeout, options); + return object; + }; + + /** + * Converts this LongRunning to JSON. + * @function toJSON + * @memberof google.api.MethodSettings.LongRunning + * @instance + * @returns {Object.} JSON object + */ + LongRunning.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for LongRunning + * @function getTypeUrl + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + LongRunning.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.MethodSettings.LongRunning"; + }; + + return LongRunning; + })(); + + return MethodSettings; + })(); + + /** + * ClientLibraryOrganization enum. + * @name google.api.ClientLibraryOrganization + * @enum {string} + * @property {string} CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED=CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED value + * @property {string} CLOUD=CLOUD CLOUD value + * @property {string} ADS=ADS ADS value + * @property {string} PHOTOS=PHOTOS PHOTOS value + * @property {string} STREET_VIEW=STREET_VIEW STREET_VIEW value + * @property {string} SHOPPING=SHOPPING SHOPPING value + * @property {string} GEO=GEO GEO value + * @property {string} GENERATIVE_AI=GENERATIVE_AI GENERATIVE_AI value + */ + api.ClientLibraryOrganization = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"] = "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"; + values[valuesById[1] = "CLOUD"] = "CLOUD"; + values[valuesById[2] = "ADS"] = "ADS"; + values[valuesById[3] = "PHOTOS"] = "PHOTOS"; + values[valuesById[4] = "STREET_VIEW"] = "STREET_VIEW"; + values[valuesById[5] = "SHOPPING"] = "SHOPPING"; + values[valuesById[6] = "GEO"] = "GEO"; + values[valuesById[7] = "GENERATIVE_AI"] = "GENERATIVE_AI"; + return values; + })(); + + /** + * ClientLibraryDestination enum. + * @name google.api.ClientLibraryDestination + * @enum {string} + * @property {string} CLIENT_LIBRARY_DESTINATION_UNSPECIFIED=CLIENT_LIBRARY_DESTINATION_UNSPECIFIED CLIENT_LIBRARY_DESTINATION_UNSPECIFIED value + * @property {string} GITHUB=GITHUB GITHUB value + * @property {string} PACKAGE_MANAGER=PACKAGE_MANAGER PACKAGE_MANAGER value + */ + api.ClientLibraryDestination = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"] = "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"; + values[valuesById[10] = "GITHUB"] = "GITHUB"; + values[valuesById[20] = "PACKAGE_MANAGER"] = "PACKAGE_MANAGER"; + return values; + })(); + + api.SelectiveGapicGeneration = (function() { + + /** + * Properties of a SelectiveGapicGeneration. + * @memberof google.api + * @interface ISelectiveGapicGeneration + * @property {Array.|null} [methods] SelectiveGapicGeneration methods + * @property {boolean|null} [generateOmittedAsInternal] SelectiveGapicGeneration generateOmittedAsInternal + */ + + /** + * Constructs a new SelectiveGapicGeneration. + * @memberof google.api + * @classdesc Represents a SelectiveGapicGeneration. + * @implements ISelectiveGapicGeneration + * @constructor + * @param {google.api.ISelectiveGapicGeneration=} [properties] Properties to set + */ + function SelectiveGapicGeneration(properties) { + this.methods = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SelectiveGapicGeneration methods. + * @member {Array.} methods + * @memberof google.api.SelectiveGapicGeneration + * @instance + */ + SelectiveGapicGeneration.prototype.methods = $util.emptyArray; + + /** + * SelectiveGapicGeneration generateOmittedAsInternal. + * @member {boolean} generateOmittedAsInternal + * @memberof google.api.SelectiveGapicGeneration + * @instance + */ + SelectiveGapicGeneration.prototype.generateOmittedAsInternal = false; + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {Object.} object Plain object + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + */ + SelectiveGapicGeneration.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.SelectiveGapicGeneration) + return object; + var message = new $root.google.api.SelectiveGapicGeneration(); + if (object.methods) { + if (!Array.isArray(object.methods)) + throw TypeError(".google.api.SelectiveGapicGeneration.methods: array expected"); + message.methods = []; + for (var i = 0; i < object.methods.length; ++i) + message.methods[i] = String(object.methods[i]); + } + if (object.generateOmittedAsInternal != null) + message.generateOmittedAsInternal = Boolean(object.generateOmittedAsInternal); + return message; + }; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.SelectiveGapicGeneration} message SelectiveGapicGeneration + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SelectiveGapicGeneration.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.methods = []; + if (options.defaults) + object.generateOmittedAsInternal = false; + if (message.methods && message.methods.length) { + object.methods = []; + for (var j = 0; j < message.methods.length; ++j) + object.methods[j] = message.methods[j]; + } + if (message.generateOmittedAsInternal != null && message.hasOwnProperty("generateOmittedAsInternal")) + object.generateOmittedAsInternal = message.generateOmittedAsInternal; + return object; + }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @function toJSON + * @memberof google.api.SelectiveGapicGeneration + * @instance + * @returns {Object.} JSON object + */ + SelectiveGapicGeneration.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @function getTypeUrl + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SelectiveGapicGeneration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.SelectiveGapicGeneration"; + }; + + return SelectiveGapicGeneration; + })(); + + /** + * LaunchStage enum. + * @name google.api.LaunchStage + * @enum {string} + * @property {string} LAUNCH_STAGE_UNSPECIFIED=LAUNCH_STAGE_UNSPECIFIED LAUNCH_STAGE_UNSPECIFIED value + * @property {string} UNIMPLEMENTED=UNIMPLEMENTED UNIMPLEMENTED value + * @property {string} PRELAUNCH=PRELAUNCH PRELAUNCH value + * @property {string} EARLY_ACCESS=EARLY_ACCESS EARLY_ACCESS value + * @property {string} ALPHA=ALPHA ALPHA value + * @property {string} BETA=BETA BETA value + * @property {string} GA=GA GA value + * @property {string} DEPRECATED=DEPRECATED DEPRECATED value + */ + api.LaunchStage = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = "LAUNCH_STAGE_UNSPECIFIED"; + values[valuesById[6] = "UNIMPLEMENTED"] = "UNIMPLEMENTED"; + values[valuesById[7] = "PRELAUNCH"] = "PRELAUNCH"; + values[valuesById[1] = "EARLY_ACCESS"] = "EARLY_ACCESS"; + values[valuesById[2] = "ALPHA"] = "ALPHA"; + values[valuesById[3] = "BETA"] = "BETA"; + values[valuesById[4] = "GA"] = "GA"; + values[valuesById[5] = "DEPRECATED"] = "DEPRECATED"; + return values; + })(); + + /** + * FieldBehavior enum. + * @name google.api.FieldBehavior + * @enum {string} + * @property {string} FIELD_BEHAVIOR_UNSPECIFIED=FIELD_BEHAVIOR_UNSPECIFIED FIELD_BEHAVIOR_UNSPECIFIED value + * @property {string} OPTIONAL=OPTIONAL OPTIONAL value + * @property {string} REQUIRED=REQUIRED REQUIRED value + * @property {string} OUTPUT_ONLY=OUTPUT_ONLY OUTPUT_ONLY value + * @property {string} INPUT_ONLY=INPUT_ONLY INPUT_ONLY value + * @property {string} IMMUTABLE=IMMUTABLE IMMUTABLE value + * @property {string} UNORDERED_LIST=UNORDERED_LIST UNORDERED_LIST value + * @property {string} NON_EMPTY_DEFAULT=NON_EMPTY_DEFAULT NON_EMPTY_DEFAULT value + * @property {string} IDENTIFIER=IDENTIFIER IDENTIFIER value + */ + api.FieldBehavior = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "FIELD_BEHAVIOR_UNSPECIFIED"] = "FIELD_BEHAVIOR_UNSPECIFIED"; + values[valuesById[1] = "OPTIONAL"] = "OPTIONAL"; + values[valuesById[2] = "REQUIRED"] = "REQUIRED"; + values[valuesById[3] = "OUTPUT_ONLY"] = "OUTPUT_ONLY"; + values[valuesById[4] = "INPUT_ONLY"] = "INPUT_ONLY"; + values[valuesById[5] = "IMMUTABLE"] = "IMMUTABLE"; + values[valuesById[6] = "UNORDERED_LIST"] = "UNORDERED_LIST"; + values[valuesById[7] = "NON_EMPTY_DEFAULT"] = "NON_EMPTY_DEFAULT"; + values[valuesById[8] = "IDENTIFIER"] = "IDENTIFIER"; + return values; + })(); + + api.ResourceDescriptor = (function() { + + /** + * Properties of a ResourceDescriptor. + * @memberof google.api + * @interface IResourceDescriptor + * @property {string|null} [type] ResourceDescriptor type + * @property {Array.|null} [pattern] ResourceDescriptor pattern + * @property {string|null} [nameField] ResourceDescriptor nameField + * @property {google.api.ResourceDescriptor.History|null} [history] ResourceDescriptor history + * @property {string|null} [plural] ResourceDescriptor plural + * @property {string|null} [singular] ResourceDescriptor singular + * @property {Array.|null} [style] ResourceDescriptor style + */ + + /** + * Constructs a new ResourceDescriptor. + * @memberof google.api + * @classdesc Represents a ResourceDescriptor. + * @implements IResourceDescriptor + * @constructor + * @param {google.api.IResourceDescriptor=} [properties] Properties to set + */ + function ResourceDescriptor(properties) { + this.pattern = []; + this.style = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResourceDescriptor type. + * @member {string} type + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.type = ""; + + /** + * ResourceDescriptor pattern. + * @member {Array.} pattern + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.pattern = $util.emptyArray; + + /** + * ResourceDescriptor nameField. + * @member {string} nameField + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.nameField = ""; + + /** + * ResourceDescriptor history. + * @member {google.api.ResourceDescriptor.History} history + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.history = 0; + + /** + * ResourceDescriptor plural. + * @member {string} plural + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.plural = ""; + + /** + * ResourceDescriptor singular. + * @member {string} singular + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.singular = ""; + + /** + * ResourceDescriptor style. + * @member {Array.} style + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.style = $util.emptyArray; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ResourceDescriptor + * @static + * @param {Object.} object Plain object + * @returns {google.api.ResourceDescriptor} ResourceDescriptor + */ + ResourceDescriptor.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ResourceDescriptor) + return object; + var message = new $root.google.api.ResourceDescriptor(); + if (object.type != null) + message.type = String(object.type); + if (object.pattern) { + if (!Array.isArray(object.pattern)) + throw TypeError(".google.api.ResourceDescriptor.pattern: array expected"); + message.pattern = []; + for (var i = 0; i < object.pattern.length; ++i) + message.pattern[i] = String(object.pattern[i]); + } + if (object.nameField != null) + message.nameField = String(object.nameField); + switch (object.history) { + default: + if (typeof object.history === "number") { + message.history = object.history; + break; + } + break; + case "HISTORY_UNSPECIFIED": + case 0: + message.history = 0; + break; + case "ORIGINALLY_SINGLE_PATTERN": + case 1: + message.history = 1; + break; + case "FUTURE_MULTI_PATTERN": + case 2: + message.history = 2; + break; + } + if (object.plural != null) + message.plural = String(object.plural); + if (object.singular != null) + message.singular = String(object.singular); + if (object.style) { + if (!Array.isArray(object.style)) + throw TypeError(".google.api.ResourceDescriptor.style: array expected"); + message.style = []; + for (var i = 0; i < object.style.length; ++i) + switch (object.style[i]) { + default: + if (typeof object.style[i] === "number") { + message.style[i] = object.style[i]; + break; + } + case "STYLE_UNSPECIFIED": + case 0: + message.style[i] = 0; + break; + case "DECLARATIVE_FRIENDLY": + case 1: + message.style[i] = 1; + break; + } + } + return message; + }; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ResourceDescriptor + * @static + * @param {google.api.ResourceDescriptor} message ResourceDescriptor + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceDescriptor.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.pattern = []; + object.style = []; + } + if (options.defaults) { + object.type = ""; + object.nameField = ""; + object.history = options.enums === String ? "HISTORY_UNSPECIFIED" : 0; + object.plural = ""; + object.singular = ""; + } + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.pattern && message.pattern.length) { + object.pattern = []; + for (var j = 0; j < message.pattern.length; ++j) + object.pattern[j] = message.pattern[j]; + } + if (message.nameField != null && message.hasOwnProperty("nameField")) + object.nameField = message.nameField; + if (message.history != null && message.hasOwnProperty("history")) + object.history = options.enums === String ? $root.google.api.ResourceDescriptor.History[message.history] === undefined ? message.history : $root.google.api.ResourceDescriptor.History[message.history] : message.history; + if (message.plural != null && message.hasOwnProperty("plural")) + object.plural = message.plural; + if (message.singular != null && message.hasOwnProperty("singular")) + object.singular = message.singular; + if (message.style && message.style.length) { + object.style = []; + for (var j = 0; j < message.style.length; ++j) + object.style[j] = options.enums === String ? $root.google.api.ResourceDescriptor.Style[message.style[j]] === undefined ? message.style[j] : $root.google.api.ResourceDescriptor.Style[message.style[j]] : message.style[j]; + } + return object; + }; + + /** + * Converts this ResourceDescriptor to JSON. + * @function toJSON + * @memberof google.api.ResourceDescriptor + * @instance + * @returns {Object.} JSON object + */ + ResourceDescriptor.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResourceDescriptor + * @function getTypeUrl + * @memberof google.api.ResourceDescriptor + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceDescriptor.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ResourceDescriptor"; + }; + + /** + * History enum. + * @name google.api.ResourceDescriptor.History + * @enum {string} + * @property {string} HISTORY_UNSPECIFIED=HISTORY_UNSPECIFIED HISTORY_UNSPECIFIED value + * @property {string} ORIGINALLY_SINGLE_PATTERN=ORIGINALLY_SINGLE_PATTERN ORIGINALLY_SINGLE_PATTERN value + * @property {string} FUTURE_MULTI_PATTERN=FUTURE_MULTI_PATTERN FUTURE_MULTI_PATTERN value + */ + ResourceDescriptor.History = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "HISTORY_UNSPECIFIED"] = "HISTORY_UNSPECIFIED"; + values[valuesById[1] = "ORIGINALLY_SINGLE_PATTERN"] = "ORIGINALLY_SINGLE_PATTERN"; + values[valuesById[2] = "FUTURE_MULTI_PATTERN"] = "FUTURE_MULTI_PATTERN"; + return values; + })(); + + /** + * Style enum. + * @name google.api.ResourceDescriptor.Style + * @enum {string} + * @property {string} STYLE_UNSPECIFIED=STYLE_UNSPECIFIED STYLE_UNSPECIFIED value + * @property {string} DECLARATIVE_FRIENDLY=DECLARATIVE_FRIENDLY DECLARATIVE_FRIENDLY value + */ + ResourceDescriptor.Style = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STYLE_UNSPECIFIED"] = "STYLE_UNSPECIFIED"; + values[valuesById[1] = "DECLARATIVE_FRIENDLY"] = "DECLARATIVE_FRIENDLY"; + return values; + })(); + + return ResourceDescriptor; + })(); + + api.ResourceReference = (function() { + + /** + * Properties of a ResourceReference. + * @memberof google.api + * @interface IResourceReference + * @property {string|null} [type] ResourceReference type + * @property {string|null} [childType] ResourceReference childType + */ + + /** + * Constructs a new ResourceReference. + * @memberof google.api + * @classdesc Represents a ResourceReference. + * @implements IResourceReference + * @constructor + * @param {google.api.IResourceReference=} [properties] Properties to set + */ + function ResourceReference(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResourceReference type. + * @member {string} type + * @memberof google.api.ResourceReference + * @instance + */ + ResourceReference.prototype.type = ""; + + /** + * ResourceReference childType. + * @member {string} childType + * @memberof google.api.ResourceReference + * @instance + */ + ResourceReference.prototype.childType = ""; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ResourceReference + * @static + * @param {Object.} object Plain object + * @returns {google.api.ResourceReference} ResourceReference + */ + ResourceReference.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ResourceReference) + return object; + var message = new $root.google.api.ResourceReference(); + if (object.type != null) + message.type = String(object.type); + if (object.childType != null) + message.childType = String(object.childType); + return message; + }; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ResourceReference + * @static + * @param {google.api.ResourceReference} message ResourceReference + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceReference.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.type = ""; + object.childType = ""; + } + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.childType != null && message.hasOwnProperty("childType")) + object.childType = message.childType; + return object; + }; + + /** + * Converts this ResourceReference to JSON. + * @function toJSON + * @memberof google.api.ResourceReference + * @instance + * @returns {Object.} JSON object + */ + ResourceReference.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResourceReference + * @function getTypeUrl + * @memberof google.api.ResourceReference + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceReference.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ResourceReference"; + }; + + return ResourceReference; + })(); + + api.RoutingRule = (function() { + + /** + * Properties of a RoutingRule. + * @memberof google.api + * @interface IRoutingRule + * @property {Array.|null} [routingParameters] RoutingRule routingParameters + */ + + /** + * Constructs a new RoutingRule. + * @memberof google.api + * @classdesc Represents a RoutingRule. + * @implements IRoutingRule + * @constructor + * @param {google.api.IRoutingRule=} [properties] Properties to set + */ + function RoutingRule(properties) { + this.routingParameters = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RoutingRule routingParameters. + * @member {Array.} routingParameters + * @memberof google.api.RoutingRule + * @instance + */ + RoutingRule.prototype.routingParameters = $util.emptyArray; + + /** + * Creates a RoutingRule message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.RoutingRule + * @static + * @param {Object.} object Plain object + * @returns {google.api.RoutingRule} RoutingRule + */ + RoutingRule.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RoutingRule) + return object; + var message = new $root.google.api.RoutingRule(); + if (object.routingParameters) { + if (!Array.isArray(object.routingParameters)) + throw TypeError(".google.api.RoutingRule.routingParameters: array expected"); + message.routingParameters = []; + for (var i = 0; i < object.routingParameters.length; ++i) { + if (typeof object.routingParameters[i] !== "object") + throw TypeError(".google.api.RoutingRule.routingParameters: object expected"); + message.routingParameters[i] = $root.google.api.RoutingParameter.fromObject(object.routingParameters[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a RoutingRule message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.RoutingRule + * @static + * @param {google.api.RoutingRule} message RoutingRule + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RoutingRule.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.routingParameters = []; + if (message.routingParameters && message.routingParameters.length) { + object.routingParameters = []; + for (var j = 0; j < message.routingParameters.length; ++j) + object.routingParameters[j] = $root.google.api.RoutingParameter.toObject(message.routingParameters[j], options); + } + return object; + }; + + /** + * Converts this RoutingRule to JSON. + * @function toJSON + * @memberof google.api.RoutingRule + * @instance + * @returns {Object.} JSON object + */ + RoutingRule.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RoutingRule + * @function getTypeUrl + * @memberof google.api.RoutingRule + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RoutingRule.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.RoutingRule"; + }; + + return RoutingRule; + })(); + + api.RoutingParameter = (function() { + + /** + * Properties of a RoutingParameter. + * @memberof google.api + * @interface IRoutingParameter + * @property {string|null} [field] RoutingParameter field + * @property {string|null} [pathTemplate] RoutingParameter pathTemplate + */ + + /** + * Constructs a new RoutingParameter. + * @memberof google.api + * @classdesc Represents a RoutingParameter. + * @implements IRoutingParameter + * @constructor + * @param {google.api.IRoutingParameter=} [properties] Properties to set + */ + function RoutingParameter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RoutingParameter field. + * @member {string} field + * @memberof google.api.RoutingParameter + * @instance + */ + RoutingParameter.prototype.field = ""; + + /** + * RoutingParameter pathTemplate. + * @member {string} pathTemplate + * @memberof google.api.RoutingParameter + * @instance + */ + RoutingParameter.prototype.pathTemplate = ""; + + /** + * Creates a RoutingParameter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.RoutingParameter + * @static + * @param {Object.} object Plain object + * @returns {google.api.RoutingParameter} RoutingParameter + */ + RoutingParameter.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RoutingParameter) + return object; + var message = new $root.google.api.RoutingParameter(); + if (object.field != null) + message.field = String(object.field); + if (object.pathTemplate != null) + message.pathTemplate = String(object.pathTemplate); + return message; + }; + + /** + * Creates a plain object from a RoutingParameter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.RoutingParameter + * @static + * @param {google.api.RoutingParameter} message RoutingParameter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RoutingParameter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.field = ""; + object.pathTemplate = ""; + } + if (message.field != null && message.hasOwnProperty("field")) + object.field = message.field; + if (message.pathTemplate != null && message.hasOwnProperty("pathTemplate")) + object.pathTemplate = message.pathTemplate; + return object; + }; + + /** + * Converts this RoutingParameter to JSON. + * @function toJSON + * @memberof google.api.RoutingParameter + * @instance + * @returns {Object.} JSON object + */ + RoutingParameter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RoutingParameter + * @function getTypeUrl + * @memberof google.api.RoutingParameter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RoutingParameter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.RoutingParameter"; + }; + + return RoutingParameter; + })(); + + return api; + })(); + + google.rpc = (function() { + + /** + * Namespace rpc. + * @memberof google + * @namespace + */ + var rpc = {}; + + rpc.Status = (function() { + + /** + * Properties of a Status. + * @memberof google.rpc + * @interface IStatus + * @property {number|null} [code] Status code + * @property {string|null} [message] Status message + * @property {Array.|null} [details] Status details + */ + + /** + * Constructs a new Status. + * @memberof google.rpc + * @classdesc Represents a Status. + * @implements IStatus + * @constructor + * @param {google.rpc.IStatus=} [properties] Properties to set + */ + function Status(properties) { + this.details = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Status code. + * @member {number} code + * @memberof google.rpc.Status + * @instance + */ + Status.prototype.code = 0; + + /** + * Status message. + * @member {string} message + * @memberof google.rpc.Status + * @instance + */ + Status.prototype.message = ""; + + /** + * Status details. + * @member {Array.} details + * @memberof google.rpc.Status + * @instance + */ + Status.prototype.details = $util.emptyArray; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.Status + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.Status} Status + */ + Status.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.Status) + return object; + var message = new $root.google.rpc.Status(); + if (object.code != null) + message.code = object.code | 0; + if (object.message != null) + message.message = String(object.message); + if (object.details) { + if (!Array.isArray(object.details)) + throw TypeError(".google.rpc.Status.details: array expected"); + message.details = []; + for (var i = 0; i < object.details.length; ++i) { + if (typeof object.details[i] !== "object") + throw TypeError(".google.rpc.Status.details: object expected"); + message.details[i] = $root.google.protobuf.Any.fromObject(object.details[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.Status + * @static + * @param {google.rpc.Status} message Status + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Status.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.details = []; + if (options.defaults) { + object.code = 0; + object.message = ""; + } + if (message.code != null && message.hasOwnProperty("code")) + object.code = message.code; + if (message.message != null && message.hasOwnProperty("message")) + object.message = message.message; + if (message.details && message.details.length) { + object.details = []; + for (var j = 0; j < message.details.length; ++j) + object.details[j] = $root.google.protobuf.Any.toObject(message.details[j], options); + } + return object; + }; + + /** + * Converts this Status to JSON. + * @function toJSON + * @memberof google.rpc.Status + * @instance + * @returns {Object.} JSON object + */ + Status.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Status + * @function getTypeUrl + * @memberof google.rpc.Status + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Status.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.Status"; + }; + + return Status; + })(); + + return rpc; + })(); + + google.longrunning = (function() { + + /** + * Namespace longrunning. + * @memberof google + * @namespace + */ + var longrunning = {}; + + longrunning.Operations = (function() { + + /** + * Constructs a new Operations service. + * @memberof google.longrunning + * @classdesc Represents an Operations + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function Operations(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (Operations.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = Operations; + + /** + * Callback as used by {@link google.longrunning.Operations#listOperations}. + * @memberof google.longrunning.Operations + * @typedef ListOperationsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.ListOperationsResponse} [response] ListOperationsResponse + */ + + /** + * Calls ListOperations. + * @function listOperations + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IListOperationsRequest} request ListOperationsRequest message or plain object + * @param {google.longrunning.Operations.ListOperationsCallback} callback Node-style callback called with the error, if any, and ListOperationsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.listOperations = function listOperations(request, callback) { + return this.rpcCall(listOperations, $root.google.longrunning.ListOperationsRequest, $root.google.longrunning.ListOperationsResponse, request, callback); + }, "name", { value: "ListOperations" }); + + /** + * Calls ListOperations. + * @function listOperations + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IListOperationsRequest} request ListOperationsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.longrunning.Operations#getOperation}. + * @memberof google.longrunning.Operations + * @typedef GetOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls GetOperation. + * @function getOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IGetOperationRequest} request GetOperationRequest message or plain object + * @param {google.longrunning.Operations.GetOperationCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.getOperation = function getOperation(request, callback) { + return this.rpcCall(getOperation, $root.google.longrunning.GetOperationRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "GetOperation" }); + + /** + * Calls GetOperation. + * @function getOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IGetOperationRequest} request GetOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.longrunning.Operations#deleteOperation}. + * @memberof google.longrunning.Operations + * @typedef DeleteOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteOperation. + * @function deleteOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IDeleteOperationRequest} request DeleteOperationRequest message or plain object + * @param {google.longrunning.Operations.DeleteOperationCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.deleteOperation = function deleteOperation(request, callback) { + return this.rpcCall(deleteOperation, $root.google.longrunning.DeleteOperationRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteOperation" }); + + /** + * Calls DeleteOperation. + * @function deleteOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IDeleteOperationRequest} request DeleteOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.longrunning.Operations#cancelOperation}. + * @memberof google.longrunning.Operations + * @typedef CancelOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls CancelOperation. + * @function cancelOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.ICancelOperationRequest} request CancelOperationRequest message or plain object + * @param {google.longrunning.Operations.CancelOperationCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.cancelOperation = function cancelOperation(request, callback) { + return this.rpcCall(cancelOperation, $root.google.longrunning.CancelOperationRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "CancelOperation" }); + + /** + * Calls CancelOperation. + * @function cancelOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.ICancelOperationRequest} request CancelOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.longrunning.Operations#waitOperation}. + * @memberof google.longrunning.Operations + * @typedef WaitOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls WaitOperation. + * @function waitOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IWaitOperationRequest} request WaitOperationRequest message or plain object + * @param {google.longrunning.Operations.WaitOperationCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.waitOperation = function waitOperation(request, callback) { + return this.rpcCall(waitOperation, $root.google.longrunning.WaitOperationRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "WaitOperation" }); + + /** + * Calls WaitOperation. + * @function waitOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IWaitOperationRequest} request WaitOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return Operations; + })(); + + longrunning.Operation = (function() { + + /** + * Properties of an Operation. + * @memberof google.longrunning + * @interface IOperation + * @property {string|null} [name] Operation name + * @property {google.protobuf.IAny|null} [metadata] Operation metadata + * @property {boolean|null} [done] Operation done + * @property {google.rpc.IStatus|null} [error] Operation error + * @property {google.protobuf.IAny|null} [response] Operation response + */ + + /** + * Constructs a new Operation. + * @memberof google.longrunning + * @classdesc Represents an Operation. + * @implements IOperation + * @constructor + * @param {google.longrunning.IOperation=} [properties] Properties to set + */ + function Operation(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Operation name. + * @member {string} name + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.name = ""; + + /** + * Operation metadata. + * @member {google.protobuf.IAny|null|undefined} metadata + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.metadata = null; + + /** + * Operation done. + * @member {boolean} done + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.done = false; + + /** + * Operation error. + * @member {google.rpc.IStatus|null|undefined} error + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.error = null; + + /** + * Operation response. + * @member {google.protobuf.IAny|null|undefined} response + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.response = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Operation result. + * @member {"error"|"response"|undefined} result + * @memberof google.longrunning.Operation + * @instance + */ + Object.defineProperty(Operation.prototype, "result", { + get: $util.oneOfGetter($oneOfFields = ["error", "response"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.Operation + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.Operation} Operation + */ + Operation.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.Operation) + return object; + var message = new $root.google.longrunning.Operation(); + if (object.name != null) + message.name = String(object.name); + if (object.metadata != null) { + if (typeof object.metadata !== "object") + throw TypeError(".google.longrunning.Operation.metadata: object expected"); + message.metadata = $root.google.protobuf.Any.fromObject(object.metadata); + } + if (object.done != null) + message.done = Boolean(object.done); + if (object.error != null) { + if (typeof object.error !== "object") + throw TypeError(".google.longrunning.Operation.error: object expected"); + message.error = $root.google.rpc.Status.fromObject(object.error); + } + if (object.response != null) { + if (typeof object.response !== "object") + throw TypeError(".google.longrunning.Operation.response: object expected"); + message.response = $root.google.protobuf.Any.fromObject(object.response); + } + return message; + }; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.Operation + * @static + * @param {google.longrunning.Operation} message Operation + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Operation.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.metadata = null; + object.done = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.metadata != null && message.hasOwnProperty("metadata")) + object.metadata = $root.google.protobuf.Any.toObject(message.metadata, options); + if (message.done != null && message.hasOwnProperty("done")) + object.done = message.done; + if (message.error != null && message.hasOwnProperty("error")) { + object.error = $root.google.rpc.Status.toObject(message.error, options); + if (options.oneofs) + object.result = "error"; + } + if (message.response != null && message.hasOwnProperty("response")) { + object.response = $root.google.protobuf.Any.toObject(message.response, options); + if (options.oneofs) + object.result = "response"; + } + return object; + }; + + /** + * Converts this Operation to JSON. + * @function toJSON + * @memberof google.longrunning.Operation + * @instance + * @returns {Object.} JSON object + */ + Operation.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Operation + * @function getTypeUrl + * @memberof google.longrunning.Operation + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Operation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.Operation"; + }; + + return Operation; + })(); + + longrunning.GetOperationRequest = (function() { + + /** + * Properties of a GetOperationRequest. + * @memberof google.longrunning + * @interface IGetOperationRequest + * @property {string|null} [name] GetOperationRequest name + */ + + /** + * Constructs a new GetOperationRequest. + * @memberof google.longrunning + * @classdesc Represents a GetOperationRequest. + * @implements IGetOperationRequest + * @constructor + * @param {google.longrunning.IGetOperationRequest=} [properties] Properties to set + */ + function GetOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetOperationRequest name. + * @member {string} name + * @memberof google.longrunning.GetOperationRequest + * @instance + */ + GetOperationRequest.prototype.name = ""; + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.GetOperationRequest} GetOperationRequest + */ + GetOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.GetOperationRequest) + return object; + var message = new $root.google.longrunning.GetOperationRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {google.longrunning.GetOperationRequest} message GetOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetOperationRequest to JSON. + * @function toJSON + * @memberof google.longrunning.GetOperationRequest + * @instance + * @returns {Object.} JSON object + */ + GetOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetOperationRequest + * @function getTypeUrl + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.GetOperationRequest"; + }; + + return GetOperationRequest; + })(); + + longrunning.ListOperationsRequest = (function() { + + /** + * Properties of a ListOperationsRequest. + * @memberof google.longrunning + * @interface IListOperationsRequest + * @property {string|null} [name] ListOperationsRequest name + * @property {string|null} [filter] ListOperationsRequest filter + * @property {number|null} [pageSize] ListOperationsRequest pageSize + * @property {string|null} [pageToken] ListOperationsRequest pageToken + * @property {boolean|null} [returnPartialSuccess] ListOperationsRequest returnPartialSuccess + */ + + /** + * Constructs a new ListOperationsRequest. + * @memberof google.longrunning + * @classdesc Represents a ListOperationsRequest. + * @implements IListOperationsRequest + * @constructor + * @param {google.longrunning.IListOperationsRequest=} [properties] Properties to set + */ + function ListOperationsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListOperationsRequest name. + * @member {string} name + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.name = ""; + + /** + * ListOperationsRequest filter. + * @member {string} filter + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.filter = ""; + + /** + * ListOperationsRequest pageSize. + * @member {number} pageSize + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.pageSize = 0; + + /** + * ListOperationsRequest pageToken. + * @member {string} pageToken + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.pageToken = ""; + + /** + * ListOperationsRequest returnPartialSuccess. + * @member {boolean} returnPartialSuccess + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.returnPartialSuccess = false; + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.ListOperationsRequest} ListOperationsRequest + */ + ListOperationsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.ListOperationsRequest) + return object; + var message = new $root.google.longrunning.ListOperationsRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.returnPartialSuccess != null) + message.returnPartialSuccess = Boolean(object.returnPartialSuccess); + return message; + }; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {google.longrunning.ListOperationsRequest} message ListOperationsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListOperationsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + object.name = ""; + object.returnPartialSuccess = false; + } + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) + object.returnPartialSuccess = message.returnPartialSuccess; + return object; + }; + + /** + * Converts this ListOperationsRequest to JSON. + * @function toJSON + * @memberof google.longrunning.ListOperationsRequest + * @instance + * @returns {Object.} JSON object + */ + ListOperationsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListOperationsRequest + * @function getTypeUrl + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListOperationsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.ListOperationsRequest"; + }; + + return ListOperationsRequest; + })(); + + longrunning.ListOperationsResponse = (function() { + + /** + * Properties of a ListOperationsResponse. + * @memberof google.longrunning + * @interface IListOperationsResponse + * @property {Array.|null} [operations] ListOperationsResponse operations + * @property {string|null} [nextPageToken] ListOperationsResponse nextPageToken + * @property {Array.|null} [unreachable] ListOperationsResponse unreachable + */ + + /** + * Constructs a new ListOperationsResponse. + * @memberof google.longrunning + * @classdesc Represents a ListOperationsResponse. + * @implements IListOperationsResponse + * @constructor + * @param {google.longrunning.IListOperationsResponse=} [properties] Properties to set + */ + function ListOperationsResponse(properties) { + this.operations = []; + this.unreachable = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListOperationsResponse operations. + * @member {Array.} operations + * @memberof google.longrunning.ListOperationsResponse + * @instance + */ + ListOperationsResponse.prototype.operations = $util.emptyArray; + + /** + * ListOperationsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.longrunning.ListOperationsResponse + * @instance + */ + ListOperationsResponse.prototype.nextPageToken = ""; + + /** + * ListOperationsResponse unreachable. + * @member {Array.} unreachable + * @memberof google.longrunning.ListOperationsResponse + * @instance + */ + ListOperationsResponse.prototype.unreachable = $util.emptyArray; + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.ListOperationsResponse} ListOperationsResponse + */ + ListOperationsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.ListOperationsResponse) + return object; + var message = new $root.google.longrunning.ListOperationsResponse(); + if (object.operations) { + if (!Array.isArray(object.operations)) + throw TypeError(".google.longrunning.ListOperationsResponse.operations: array expected"); + message.operations = []; + for (var i = 0; i < object.operations.length; ++i) { + if (typeof object.operations[i] !== "object") + throw TypeError(".google.longrunning.ListOperationsResponse.operations: object expected"); + message.operations[i] = $root.google.longrunning.Operation.fromObject(object.operations[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + if (object.unreachable) { + if (!Array.isArray(object.unreachable)) + throw TypeError(".google.longrunning.ListOperationsResponse.unreachable: array expected"); + message.unreachable = []; + for (var i = 0; i < object.unreachable.length; ++i) + message.unreachable[i] = String(object.unreachable[i]); + } + return message; + }; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {google.longrunning.ListOperationsResponse} message ListOperationsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListOperationsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.operations = []; + object.unreachable = []; + } + if (options.defaults) + object.nextPageToken = ""; + if (message.operations && message.operations.length) { + object.operations = []; + for (var j = 0; j < message.operations.length; ++j) + object.operations[j] = $root.google.longrunning.Operation.toObject(message.operations[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + if (message.unreachable && message.unreachable.length) { + object.unreachable = []; + for (var j = 0; j < message.unreachable.length; ++j) + object.unreachable[j] = message.unreachable[j]; + } + return object; + }; + + /** + * Converts this ListOperationsResponse to JSON. + * @function toJSON + * @memberof google.longrunning.ListOperationsResponse + * @instance + * @returns {Object.} JSON object + */ + ListOperationsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListOperationsResponse + * @function getTypeUrl + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListOperationsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.ListOperationsResponse"; + }; + + return ListOperationsResponse; + })(); + + longrunning.CancelOperationRequest = (function() { + + /** + * Properties of a CancelOperationRequest. + * @memberof google.longrunning + * @interface ICancelOperationRequest + * @property {string|null} [name] CancelOperationRequest name + */ + + /** + * Constructs a new CancelOperationRequest. + * @memberof google.longrunning + * @classdesc Represents a CancelOperationRequest. + * @implements ICancelOperationRequest + * @constructor + * @param {google.longrunning.ICancelOperationRequest=} [properties] Properties to set + */ + function CancelOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CancelOperationRequest name. + * @member {string} name + * @memberof google.longrunning.CancelOperationRequest + * @instance + */ + CancelOperationRequest.prototype.name = ""; + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.CancelOperationRequest} CancelOperationRequest + */ + CancelOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.CancelOperationRequest) + return object; + var message = new $root.google.longrunning.CancelOperationRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {google.longrunning.CancelOperationRequest} message CancelOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CancelOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this CancelOperationRequest to JSON. + * @function toJSON + * @memberof google.longrunning.CancelOperationRequest + * @instance + * @returns {Object.} JSON object + */ + CancelOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CancelOperationRequest + * @function getTypeUrl + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CancelOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.CancelOperationRequest"; + }; + + return CancelOperationRequest; + })(); + + longrunning.DeleteOperationRequest = (function() { + + /** + * Properties of a DeleteOperationRequest. + * @memberof google.longrunning + * @interface IDeleteOperationRequest + * @property {string|null} [name] DeleteOperationRequest name + */ + + /** + * Constructs a new DeleteOperationRequest. + * @memberof google.longrunning + * @classdesc Represents a DeleteOperationRequest. + * @implements IDeleteOperationRequest + * @constructor + * @param {google.longrunning.IDeleteOperationRequest=} [properties] Properties to set + */ + function DeleteOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteOperationRequest name. + * @member {string} name + * @memberof google.longrunning.DeleteOperationRequest + * @instance + */ + DeleteOperationRequest.prototype.name = ""; + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.DeleteOperationRequest} DeleteOperationRequest + */ + DeleteOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.DeleteOperationRequest) + return object; + var message = new $root.google.longrunning.DeleteOperationRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {google.longrunning.DeleteOperationRequest} message DeleteOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @function toJSON + * @memberof google.longrunning.DeleteOperationRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteOperationRequest + * @function getTypeUrl + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.DeleteOperationRequest"; + }; + + return DeleteOperationRequest; + })(); + + longrunning.WaitOperationRequest = (function() { + + /** + * Properties of a WaitOperationRequest. + * @memberof google.longrunning + * @interface IWaitOperationRequest + * @property {string|null} [name] WaitOperationRequest name + * @property {google.protobuf.IDuration|null} [timeout] WaitOperationRequest timeout + */ + + /** + * Constructs a new WaitOperationRequest. + * @memberof google.longrunning + * @classdesc Represents a WaitOperationRequest. + * @implements IWaitOperationRequest + * @constructor + * @param {google.longrunning.IWaitOperationRequest=} [properties] Properties to set + */ + function WaitOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * WaitOperationRequest name. + * @member {string} name + * @memberof google.longrunning.WaitOperationRequest + * @instance + */ + WaitOperationRequest.prototype.name = ""; + + /** + * WaitOperationRequest timeout. + * @member {google.protobuf.IDuration|null|undefined} timeout + * @memberof google.longrunning.WaitOperationRequest + * @instance + */ + WaitOperationRequest.prototype.timeout = null; + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.WaitOperationRequest} WaitOperationRequest + */ + WaitOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.WaitOperationRequest) + return object; + var message = new $root.google.longrunning.WaitOperationRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.timeout != null) { + if (typeof object.timeout !== "object") + throw TypeError(".google.longrunning.WaitOperationRequest.timeout: object expected"); + message.timeout = $root.google.protobuf.Duration.fromObject(object.timeout); + } + return message; + }; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {google.longrunning.WaitOperationRequest} message WaitOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WaitOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.timeout = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.timeout != null && message.hasOwnProperty("timeout")) + object.timeout = $root.google.protobuf.Duration.toObject(message.timeout, options); + return object; + }; + + /** + * Converts this WaitOperationRequest to JSON. + * @function toJSON + * @memberof google.longrunning.WaitOperationRequest + * @instance + * @returns {Object.} JSON object + */ + WaitOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for WaitOperationRequest + * @function getTypeUrl + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WaitOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.WaitOperationRequest"; + }; + + return WaitOperationRequest; + })(); + + longrunning.OperationInfo = (function() { + + /** + * Properties of an OperationInfo. + * @memberof google.longrunning + * @interface IOperationInfo + * @property {string|null} [responseType] OperationInfo responseType + * @property {string|null} [metadataType] OperationInfo metadataType + */ + + /** + * Constructs a new OperationInfo. + * @memberof google.longrunning + * @classdesc Represents an OperationInfo. + * @implements IOperationInfo + * @constructor + * @param {google.longrunning.IOperationInfo=} [properties] Properties to set + */ + function OperationInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OperationInfo responseType. + * @member {string} responseType + * @memberof google.longrunning.OperationInfo + * @instance + */ + OperationInfo.prototype.responseType = ""; + + /** + * OperationInfo metadataType. + * @member {string} metadataType + * @memberof google.longrunning.OperationInfo + * @instance + */ + OperationInfo.prototype.metadataType = ""; + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.OperationInfo + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.OperationInfo} OperationInfo + */ + OperationInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.OperationInfo) + return object; + var message = new $root.google.longrunning.OperationInfo(); + if (object.responseType != null) + message.responseType = String(object.responseType); + if (object.metadataType != null) + message.metadataType = String(object.metadataType); + return message; + }; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.OperationInfo + * @static + * @param {google.longrunning.OperationInfo} message OperationInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OperationInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.responseType = ""; + object.metadataType = ""; + } + if (message.responseType != null && message.hasOwnProperty("responseType")) + object.responseType = message.responseType; + if (message.metadataType != null && message.hasOwnProperty("metadataType")) + object.metadataType = message.metadataType; + return object; + }; + + /** + * Converts this OperationInfo to JSON. + * @function toJSON + * @memberof google.longrunning.OperationInfo + * @instance + * @returns {Object.} JSON object + */ + OperationInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OperationInfo + * @function getTypeUrl + * @memberof google.longrunning.OperationInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OperationInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.OperationInfo"; + }; + + return OperationInfo; + })(); + + return longrunning; + })(); + + return google; + })(); + + return $root; +}); diff --git a/handwritten/firestore/dev/protos/google/api/annotations.proto b/handwritten/firestore/dev/protos/google/api/annotations.proto new file mode 100644 index 00000000000..417edd8fa19 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/api/annotations.proto @@ -0,0 +1,31 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/api/http.proto"; +import "google/protobuf/descriptor.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "AnnotationsProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.MethodOptions { + // See `HttpRule`. + HttpRule http = 72295728; +} diff --git a/handwritten/firestore/dev/protos/google/api/client.proto b/handwritten/firestore/dev/protos/google/api/client.proto new file mode 100644 index 00000000000..3d692560abb --- /dev/null +++ b/handwritten/firestore/dev/protos/google/api/client.proto @@ -0,0 +1,486 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/api/launch_stage.proto"; +import "google/protobuf/descriptor.proto"; +import "google/protobuf/duration.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "ClientProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.MethodOptions { + // A definition of a client library method signature. + // + // In client libraries, each proto RPC corresponds to one or more methods + // which the end user is able to call, and calls the underlying RPC. + // Normally, this method receives a single argument (a struct or instance + // corresponding to the RPC request object). Defining this field will + // add one or more overloads providing flattened or simpler method signatures + // in some languages. + // + // The fields on the method signature are provided as a comma-separated + // string. + // + // For example, the proto RPC and annotation: + // + // rpc CreateSubscription(CreateSubscriptionRequest) + // returns (Subscription) { + // option (google.api.method_signature) = "name,topic"; + // } + // + // Would add the following Java overload (in addition to the method accepting + // the request object): + // + // public final Subscription createSubscription(String name, String topic) + // + // The following backwards-compatibility guidelines apply: + // + // * Adding this annotation to an unannotated method is backwards + // compatible. + // * Adding this annotation to a method which already has existing + // method signature annotations is backwards compatible if and only if + // the new method signature annotation is last in the sequence. + // * Modifying or removing an existing method signature annotation is + // a breaking change. + // * Re-ordering existing method signature annotations is a breaking + // change. + repeated string method_signature = 1051; +} + +extend google.protobuf.ServiceOptions { + // The hostname for this service. + // This should be specified with no prefix or protocol. + // + // Example: + // + // service Foo { + // option (google.api.default_host) = "foo.googleapi.com"; + // ... + // } + string default_host = 1049; + + // OAuth scopes needed for the client. + // + // Example: + // + // service Foo { + // option (google.api.oauth_scopes) = \ + // "https://www.googleapis.com/auth/cloud-platform"; + // ... + // } + // + // If there is more than one scope, use a comma-separated string: + // + // Example: + // + // service Foo { + // option (google.api.oauth_scopes) = \ + // "https://www.googleapis.com/auth/cloud-platform," + // "https://www.googleapis.com/auth/monitoring"; + // ... + // } + string oauth_scopes = 1050; + + // The API version of this service, which should be sent by version-aware + // clients to the service. This allows services to abide by the schema and + // behavior of the service at the time this API version was deployed. + // The format of the API version must be treated as opaque by clients. + // Services may use a format with an apparent structure, but clients must + // not rely on this to determine components within an API version, or attempt + // to construct other valid API versions. Note that this is for upcoming + // functionality and may not be implemented for all services. + // + // Example: + // + // service Foo { + // option (google.api.api_version) = "v1_20230821_preview"; + // } + string api_version = 525000001; +} + +// Required information for every language. +message CommonLanguageSettings { + // Link to automatically generated reference documentation. Example: + // https://cloud.google.com/nodejs/docs/reference/asset/latest + string reference_docs_uri = 1 [deprecated = true]; + + // The destination where API teams want this client library to be published. + repeated ClientLibraryDestination destinations = 2; + + // Configuration for which RPCs should be generated in the GAPIC client. + SelectiveGapicGeneration selective_gapic_generation = 3; +} + +// Details about how and where to publish client libraries. +message ClientLibrarySettings { + // Version of the API to apply these settings to. This is the full protobuf + // package for the API, ending in the version element. + // Examples: "google.cloud.speech.v1" and "google.spanner.admin.database.v1". + string version = 1; + + // Launch stage of this version of the API. + LaunchStage launch_stage = 2; + + // When using transport=rest, the client request will encode enums as + // numbers rather than strings. + bool rest_numeric_enums = 3; + + // Settings for legacy Java features, supported in the Service YAML. + JavaSettings java_settings = 21; + + // Settings for C++ client libraries. + CppSettings cpp_settings = 22; + + // Settings for PHP client libraries. + PhpSettings php_settings = 23; + + // Settings for Python client libraries. + PythonSettings python_settings = 24; + + // Settings for Node client libraries. + NodeSettings node_settings = 25; + + // Settings for .NET client libraries. + DotnetSettings dotnet_settings = 26; + + // Settings for Ruby client libraries. + RubySettings ruby_settings = 27; + + // Settings for Go client libraries. + GoSettings go_settings = 28; +} + +// This message configures the settings for publishing [Google Cloud Client +// libraries](https://cloud.google.com/apis/docs/cloud-client-libraries) +// generated from the service config. +message Publishing { + // A list of API method settings, e.g. the behavior for methods that use the + // long-running operation pattern. + repeated MethodSettings method_settings = 2; + + // Link to a *public* URI where users can report issues. Example: + // https://issuetracker.google.com/issues/new?component=190865&template=1161103 + string new_issue_uri = 101; + + // Link to product home page. Example: + // https://cloud.google.com/asset-inventory/docs/overview + string documentation_uri = 102; + + // Used as a tracking tag when collecting data about the APIs developer + // relations artifacts like docs, packages delivered to package managers, + // etc. Example: "speech". + string api_short_name = 103; + + // GitHub label to apply to issues and pull requests opened for this API. + string github_label = 104; + + // GitHub teams to be added to CODEOWNERS in the directory in GitHub + // containing source code for the client libraries for this API. + repeated string codeowner_github_teams = 105; + + // A prefix used in sample code when demarking regions to be included in + // documentation. + string doc_tag_prefix = 106; + + // For whom the client library is being published. + ClientLibraryOrganization organization = 107; + + // Client library settings. If the same version string appears multiple + // times in this list, then the last one wins. Settings from earlier + // settings with the same version string are discarded. + repeated ClientLibrarySettings library_settings = 109; + + // Optional link to proto reference documentation. Example: + // https://cloud.google.com/pubsub/lite/docs/reference/rpc + string proto_reference_documentation_uri = 110; + + // Optional link to REST reference documentation. Example: + // https://cloud.google.com/pubsub/lite/docs/reference/rest + string rest_reference_documentation_uri = 111; +} + +// Settings for Java client libraries. +message JavaSettings { + // The package name to use in Java. Clobbers the java_package option + // set in the protobuf. This should be used **only** by APIs + // who have already set the language_settings.java.package_name" field + // in gapic.yaml. API teams should use the protobuf java_package option + // where possible. + // + // Example of a YAML configuration:: + // + // publishing: + // java_settings: + // library_package: com.google.cloud.pubsub.v1 + string library_package = 1; + + // Configure the Java class name to use instead of the service's for its + // corresponding generated GAPIC client. Keys are fully-qualified + // service names as they appear in the protobuf (including the full + // the language_settings.java.interface_names" field in gapic.yaml. API + // teams should otherwise use the service name as it appears in the + // protobuf. + // + // Example of a YAML configuration:: + // + // publishing: + // java_settings: + // service_class_names: + // - google.pubsub.v1.Publisher: TopicAdmin + // - google.pubsub.v1.Subscriber: SubscriptionAdmin + map service_class_names = 2; + + // Some settings. + CommonLanguageSettings common = 3; +} + +// Settings for C++ client libraries. +message CppSettings { + // Some settings. + CommonLanguageSettings common = 1; +} + +// Settings for Php client libraries. +message PhpSettings { + // Some settings. + CommonLanguageSettings common = 1; +} + +// Settings for Python client libraries. +message PythonSettings { + // Experimental features to be included during client library generation. + // These fields will be deprecated once the feature graduates and is enabled + // by default. + message ExperimentalFeatures { + // Enables generation of asynchronous REST clients if `rest` transport is + // enabled. By default, asynchronous REST clients will not be generated. + // This feature will be enabled by default 1 month after launching the + // feature in preview packages. + bool rest_async_io_enabled = 1; + + // Enables generation of protobuf code using new types that are more + // Pythonic which are included in `protobuf>=5.29.x`. This feature will be + // enabled by default 1 month after launching the feature in preview + // packages. + bool protobuf_pythonic_types_enabled = 2; + + // Disables generation of an unversioned Python package for this client + // library. This means that the module names will need to be versioned in + // import statements. For example `import google.cloud.library_v2` instead + // of `import google.cloud.library`. + bool unversioned_package_disabled = 3; + } + + // Some settings. + CommonLanguageSettings common = 1; + + // Experimental features to be included during client library generation. + ExperimentalFeatures experimental_features = 2; +} + +// Settings for Node client libraries. +message NodeSettings { + // Some settings. + CommonLanguageSettings common = 1; +} + +// Settings for Dotnet client libraries. +message DotnetSettings { + // Some settings. + CommonLanguageSettings common = 1; + + // Map from original service names to renamed versions. + // This is used when the default generated types + // would cause a naming conflict. (Neither name is + // fully-qualified.) + // Example: Subscriber to SubscriberServiceApi. + map renamed_services = 2; + + // Map from full resource types to the effective short name + // for the resource. This is used when otherwise resource + // named from different services would cause naming collisions. + // Example entry: + // "datalabeling.googleapis.com/Dataset": "DataLabelingDataset" + map renamed_resources = 3; + + // List of full resource types to ignore during generation. + // This is typically used for API-specific Location resources, + // which should be handled by the generator as if they were actually + // the common Location resources. + // Example entry: "documentai.googleapis.com/Location" + repeated string ignored_resources = 4; + + // Namespaces which must be aliased in snippets due to + // a known (but non-generator-predictable) naming collision + repeated string forced_namespace_aliases = 5; + + // Method signatures (in the form "service.method(signature)") + // which are provided separately, so shouldn't be generated. + // Snippets *calling* these methods are still generated, however. + repeated string handwritten_signatures = 6; +} + +// Settings for Ruby client libraries. +message RubySettings { + // Some settings. + CommonLanguageSettings common = 1; +} + +// Settings for Go client libraries. +message GoSettings { + // Some settings. + CommonLanguageSettings common = 1; + + // Map of service names to renamed services. Keys are the package relative + // service names and values are the name to be used for the service client + // and call options. + // + // publishing: + // go_settings: + // renamed_services: + // Publisher: TopicAdmin + map renamed_services = 2; +} + +// Describes the generator configuration for a method. +message MethodSettings { + // Describes settings to use when generating API methods that use the + // long-running operation pattern. + // All default values below are from those used in the client library + // generators (e.g. + // [Java](https://github.com/googleapis/gapic-generator-java/blob/04c2faa191a9b5a10b92392fe8482279c4404803/src/main/java/com/google/api/generator/gapic/composer/common/RetrySettingsComposer.java)). + message LongRunning { + // Initial delay after which the first poll request will be made. + // Default value: 5 seconds. + google.protobuf.Duration initial_poll_delay = 1; + + // Multiplier to gradually increase delay between subsequent polls until it + // reaches max_poll_delay. + // Default value: 1.5. + float poll_delay_multiplier = 2; + + // Maximum time between two subsequent poll requests. + // Default value: 45 seconds. + google.protobuf.Duration max_poll_delay = 3; + + // Total polling timeout. + // Default value: 5 minutes. + google.protobuf.Duration total_poll_timeout = 4; + } + + // The fully qualified name of the method, for which the options below apply. + // This is used to find the method to apply the options. + // + // Example: + // + // publishing: + // method_settings: + // - selector: google.storage.control.v2.StorageControl.CreateFolder + // # method settings for CreateFolder... + string selector = 1; + + // Describes settings to use for long-running operations when generating + // API methods for RPCs. Complements RPCs that use the annotations in + // google/longrunning/operations.proto. + // + // Example of a YAML configuration:: + // + // publishing: + // method_settings: + // - selector: google.cloud.speech.v2.Speech.BatchRecognize + // long_running: + // initial_poll_delay: 60s # 1 minute + // poll_delay_multiplier: 1.5 + // max_poll_delay: 360s # 6 minutes + // total_poll_timeout: 54000s # 90 minutes + LongRunning long_running = 2; + + // List of top-level fields of the request message, that should be + // automatically populated by the client libraries based on their + // (google.api.field_info).format. Currently supported format: UUID4. + // + // Example of a YAML configuration: + // + // publishing: + // method_settings: + // - selector: google.example.v1.ExampleService.CreateExample + // auto_populated_fields: + // - request_id + repeated string auto_populated_fields = 3; +} + +// The organization for which the client libraries are being published. +// Affects the url where generated docs are published, etc. +enum ClientLibraryOrganization { + // Not useful. + CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED = 0; + + // Google Cloud Platform Org. + CLOUD = 1; + + // Ads (Advertising) Org. + ADS = 2; + + // Photos Org. + PHOTOS = 3; + + // Street View Org. + STREET_VIEW = 4; + + // Shopping Org. + SHOPPING = 5; + + // Geo Org. + GEO = 6; + + // Generative AI - https://developers.generativeai.google + GENERATIVE_AI = 7; +} + +// To where should client libraries be published? +enum ClientLibraryDestination { + // Client libraries will neither be generated nor published to package + // managers. + CLIENT_LIBRARY_DESTINATION_UNSPECIFIED = 0; + + // Generate the client library in a repo under github.com/googleapis, + // but don't publish it to package managers. + GITHUB = 10; + + // Publish the library to package managers like nuget.org and npmjs.com. + PACKAGE_MANAGER = 20; +} + +// This message is used to configure the generation of a subset of the RPCs in +// a service for client libraries. +message SelectiveGapicGeneration { + // An allowlist of the fully qualified names of RPCs that should be included + // on public client surfaces. + repeated string methods = 1; + + // Setting this to true indicates to the client generators that methods + // that would be excluded from the generation should instead be generated + // in a way that indicates these methods should not be consumed by + // end users. How this is expressed is up to individual language + // implementations to decide. Some examples may be: added annotations, + // obfuscated identifiers, or other language idiomatic patterns. + bool generate_omitted_as_internal = 2; +} diff --git a/handwritten/firestore/dev/protos/google/api/field_behavior.proto b/handwritten/firestore/dev/protos/google/api/field_behavior.proto new file mode 100644 index 00000000000..1fdaaed11ac --- /dev/null +++ b/handwritten/firestore/dev/protos/google/api/field_behavior.proto @@ -0,0 +1,104 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/descriptor.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "FieldBehaviorProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.FieldOptions { + // A designation of a specific field behavior (required, output only, etc.) + // in protobuf messages. + // + // Examples: + // + // string name = 1 [(google.api.field_behavior) = REQUIRED]; + // State state = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + // google.protobuf.Duration ttl = 1 + // [(google.api.field_behavior) = INPUT_ONLY]; + // google.protobuf.Timestamp expire_time = 1 + // [(google.api.field_behavior) = OUTPUT_ONLY, + // (google.api.field_behavior) = IMMUTABLE]; + repeated google.api.FieldBehavior field_behavior = 1052 [packed = false]; +} + +// An indicator of the behavior of a given field (for example, that a field +// is required in requests, or given as output but ignored as input). +// This **does not** change the behavior in protocol buffers itself; it only +// denotes the behavior and may affect how API tooling handles the field. +// +// Note: This enum **may** receive new values in the future. +enum FieldBehavior { + // Conventional default for enums. Do not use this. + FIELD_BEHAVIOR_UNSPECIFIED = 0; + + // Specifically denotes a field as optional. + // While all fields in protocol buffers are optional, this may be specified + // for emphasis if appropriate. + OPTIONAL = 1; + + // Denotes a field as required. + // This indicates that the field **must** be provided as part of the request, + // and failure to do so will cause an error (usually `INVALID_ARGUMENT`). + REQUIRED = 2; + + // Denotes a field as output only. + // This indicates that the field is provided in responses, but including the + // field in a request does nothing (the server *must* ignore it and + // *must not* throw an error as a result of the field's presence). + OUTPUT_ONLY = 3; + + // Denotes a field as input only. + // This indicates that the field is provided in requests, and the + // corresponding field is not included in output. + INPUT_ONLY = 4; + + // Denotes a field as immutable. + // This indicates that the field may be set once in a request to create a + // resource, but may not be changed thereafter. + IMMUTABLE = 5; + + // Denotes that a (repeated) field is an unordered list. + // This indicates that the service may provide the elements of the list + // in any arbitrary order, rather than the order the user originally + // provided. Additionally, the list's order may or may not be stable. + UNORDERED_LIST = 6; + + // Denotes that this field returns a non-empty default value if not set. + // This indicates that if the user provides the empty value in a request, + // a non-empty value will be returned. The user will not be aware of what + // non-empty value to expect. + NON_EMPTY_DEFAULT = 7; + + // Denotes that the field in a resource (a message annotated with + // google.api.resource) is used in the resource name to uniquely identify the + // resource. For AIP-compliant APIs, this should only be applied to the + // `name` field on the resource. + // + // This behavior should not be applied to references to other resources within + // the message. + // + // The identifier field of resources often have different field behavior + // depending on the request it is embedded in (e.g. for Create methods name + // is optional and unused, while for Update methods it is required). Instead + // of method-specific annotations, only `IDENTIFIER` is required. + IDENTIFIER = 8; +} diff --git a/handwritten/firestore/dev/protos/google/api/http.proto b/handwritten/firestore/dev/protos/google/api/http.proto new file mode 100644 index 00000000000..57621b53743 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/api/http.proto @@ -0,0 +1,370 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "HttpProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Defines the HTTP configuration for an API service. It contains a list of +// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method +// to one or more HTTP REST API methods. +message Http { + // A list of HTTP configuration rules that apply to individual API methods. + // + // **NOTE:** All service configuration rules follow "last one wins" order. + repeated HttpRule rules = 1; + + // When set to true, URL path parameters will be fully URI-decoded except in + // cases of single segment matches in reserved expansion, where "%2F" will be + // left encoded. + // + // The default behavior is to not decode RFC 6570 reserved characters in multi + // segment matches. + bool fully_decode_reserved_expansion = 2; +} + +// gRPC Transcoding +// +// gRPC Transcoding is a feature for mapping between a gRPC method and one or +// more HTTP REST endpoints. It allows developers to build a single API service +// that supports both gRPC APIs and REST APIs. Many systems, including [Google +// APIs](https://github.com/googleapis/googleapis), +// [Cloud Endpoints](https://cloud.google.com/endpoints), [gRPC +// Gateway](https://github.com/grpc-ecosystem/grpc-gateway), +// and [Envoy](https://github.com/envoyproxy/envoy) proxy support this feature +// and use it for large scale production services. +// +// `HttpRule` defines the schema of the gRPC/REST mapping. The mapping specifies +// how different portions of the gRPC request message are mapped to the URL +// path, URL query parameters, and HTTP request body. It also controls how the +// gRPC response message is mapped to the HTTP response body. `HttpRule` is +// typically specified as an `google.api.http` annotation on the gRPC method. +// +// Each mapping specifies a URL path template and an HTTP method. The path +// template may refer to one or more fields in the gRPC request message, as long +// as each field is a non-repeated field with a primitive (non-message) type. +// The path template controls how fields of the request message are mapped to +// the URL path. +// +// Example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get: "/v1/{name=messages/*}" +// }; +// } +// } +// message GetMessageRequest { +// string name = 1; // Mapped to URL path. +// } +// message Message { +// string text = 1; // The resource content. +// } +// +// This enables an HTTP REST to gRPC mapping as below: +// +// - HTTP: `GET /v1/messages/123456` +// - gRPC: `GetMessage(name: "messages/123456")` +// +// Any fields in the request message which are not bound by the path template +// automatically become HTTP query parameters if there is no HTTP request body. +// For example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get:"/v1/messages/{message_id}" +// }; +// } +// } +// message GetMessageRequest { +// message SubMessage { +// string subfield = 1; +// } +// string message_id = 1; // Mapped to URL path. +// int64 revision = 2; // Mapped to URL query parameter `revision`. +// SubMessage sub = 3; // Mapped to URL query parameter `sub.subfield`. +// } +// +// This enables a HTTP JSON to RPC mapping as below: +// +// - HTTP: `GET /v1/messages/123456?revision=2&sub.subfield=foo` +// - gRPC: `GetMessage(message_id: "123456" revision: 2 sub: +// SubMessage(subfield: "foo"))` +// +// Note that fields which are mapped to URL query parameters must have a +// primitive type or a repeated primitive type or a non-repeated message type. +// In the case of a repeated type, the parameter can be repeated in the URL +// as `...?param=A¶m=B`. In the case of a message type, each field of the +// message is mapped to a separate parameter, such as +// `...?foo.a=A&foo.b=B&foo.c=C`. +// +// For HTTP methods that allow a request body, the `body` field +// specifies the mapping. Consider a REST update method on the +// message resource collection: +// +// service Messaging { +// rpc UpdateMessage(UpdateMessageRequest) returns (Message) { +// option (google.api.http) = { +// patch: "/v1/messages/{message_id}" +// body: "message" +// }; +// } +// } +// message UpdateMessageRequest { +// string message_id = 1; // mapped to the URL +// Message message = 2; // mapped to the body +// } +// +// The following HTTP JSON to RPC mapping is enabled, where the +// representation of the JSON in the request body is determined by +// protos JSON encoding: +// +// - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }` +// - gRPC: `UpdateMessage(message_id: "123456" message { text: "Hi!" })` +// +// The special name `*` can be used in the body mapping to define that +// every field not bound by the path template should be mapped to the +// request body. This enables the following alternative definition of +// the update method: +// +// service Messaging { +// rpc UpdateMessage(Message) returns (Message) { +// option (google.api.http) = { +// patch: "/v1/messages/{message_id}" +// body: "*" +// }; +// } +// } +// message Message { +// string message_id = 1; +// string text = 2; +// } +// +// +// The following HTTP JSON to RPC mapping is enabled: +// +// - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }` +// - gRPC: `UpdateMessage(message_id: "123456" text: "Hi!")` +// +// Note that when using `*` in the body mapping, it is not possible to +// have HTTP parameters, as all fields not bound by the path end in +// the body. This makes this option more rarely used in practice when +// defining REST APIs. The common usage of `*` is in custom methods +// which don't use the URL at all for transferring data. +// +// It is possible to define multiple HTTP methods for one RPC by using +// the `additional_bindings` option. Example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get: "/v1/messages/{message_id}" +// additional_bindings { +// get: "/v1/users/{user_id}/messages/{message_id}" +// } +// }; +// } +// } +// message GetMessageRequest { +// string message_id = 1; +// string user_id = 2; +// } +// +// This enables the following two alternative HTTP JSON to RPC mappings: +// +// - HTTP: `GET /v1/messages/123456` +// - gRPC: `GetMessage(message_id: "123456")` +// +// - HTTP: `GET /v1/users/me/messages/123456` +// - gRPC: `GetMessage(user_id: "me" message_id: "123456")` +// +// Rules for HTTP mapping +// +// 1. Leaf request fields (recursive expansion nested messages in the request +// message) are classified into three categories: +// - Fields referred by the path template. They are passed via the URL path. +// - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They +// are passed via the HTTP +// request body. +// - All other fields are passed via the URL query parameters, and the +// parameter name is the field path in the request message. A repeated +// field can be represented as multiple query parameters under the same +// name. +// 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL +// query parameter, all fields +// are passed via URL path and HTTP request body. +// 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP +// request body, all +// fields are passed via URL path and URL query parameters. +// +// Path template syntax +// +// Template = "/" Segments [ Verb ] ; +// Segments = Segment { "/" Segment } ; +// Segment = "*" | "**" | LITERAL | Variable ; +// Variable = "{" FieldPath [ "=" Segments ] "}" ; +// FieldPath = IDENT { "." IDENT } ; +// Verb = ":" LITERAL ; +// +// The syntax `*` matches a single URL path segment. The syntax `**` matches +// zero or more URL path segments, which must be the last part of the URL path +// except the `Verb`. +// +// The syntax `Variable` matches part of the URL path as specified by its +// template. A variable template must not contain other variables. If a variable +// matches a single path segment, its template may be omitted, e.g. `{var}` +// is equivalent to `{var=*}`. +// +// The syntax `LITERAL` matches literal text in the URL path. If the `LITERAL` +// contains any reserved character, such characters should be percent-encoded +// before the matching. +// +// If a variable contains exactly one path segment, such as `"{var}"` or +// `"{var=*}"`, when such a variable is expanded into a URL path on the client +// side, all characters except `[-_.~0-9a-zA-Z]` are percent-encoded. The +// server side does the reverse decoding. Such variables show up in the +// [Discovery +// Document](https://developers.google.com/discovery/v1/reference/apis) as +// `{var}`. +// +// If a variable contains multiple path segments, such as `"{var=foo/*}"` +// or `"{var=**}"`, when such a variable is expanded into a URL path on the +// client side, all characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. +// The server side does the reverse decoding, except "%2F" and "%2f" are left +// unchanged. Such variables show up in the +// [Discovery +// Document](https://developers.google.com/discovery/v1/reference/apis) as +// `{+var}`. +// +// Using gRPC API Service Configuration +// +// gRPC API Service Configuration (service config) is a configuration language +// for configuring a gRPC service to become a user-facing product. The +// service config is simply the YAML representation of the `google.api.Service` +// proto message. +// +// As an alternative to annotating your proto file, you can configure gRPC +// transcoding in your service config YAML files. You do this by specifying a +// `HttpRule` that maps the gRPC method to a REST endpoint, achieving the same +// effect as the proto annotation. This can be particularly useful if you +// have a proto that is reused in multiple services. Note that any transcoding +// specified in the service config will override any matching transcoding +// configuration in the proto. +// +// The following example selects a gRPC method and applies an `HttpRule` to it: +// +// http: +// rules: +// - selector: example.v1.Messaging.GetMessage +// get: /v1/messages/{message_id}/{sub.subfield} +// +// Special notes +// +// When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the +// proto to JSON conversion must follow the [proto3 +// specification](https://developers.google.com/protocol-buffers/docs/proto3#json). +// +// While the single segment variable follows the semantics of +// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String +// Expansion, the multi segment variable **does not** follow RFC 6570 Section +// 3.2.3 Reserved Expansion. The reason is that the Reserved Expansion +// does not expand special characters like `?` and `#`, which would lead +// to invalid URLs. As the result, gRPC Transcoding uses a custom encoding +// for multi segment variables. +// +// The path variables **must not** refer to any repeated or mapped field, +// because client libraries are not capable of handling such variable expansion. +// +// The path variables **must not** capture the leading "/" character. The reason +// is that the most common use case "{var}" does not capture the leading "/" +// character. For consistency, all path variables must share the same behavior. +// +// Repeated message fields must not be mapped to URL query parameters, because +// no client library can support such complicated mapping. +// +// If an API needs to use a JSON array for request or response body, it can map +// the request or response body to a repeated field. However, some gRPC +// Transcoding implementations may not support this feature. +message HttpRule { + // Selects a method to which this rule applies. + // + // Refer to [selector][google.api.DocumentationRule.selector] for syntax + // details. + string selector = 1; + + // Determines the URL pattern is matched by this rules. This pattern can be + // used with any of the {get|put|post|delete|patch} methods. A custom method + // can be defined using the 'custom' field. + oneof pattern { + // Maps to HTTP GET. Used for listing and getting information about + // resources. + string get = 2; + + // Maps to HTTP PUT. Used for replacing a resource. + string put = 3; + + // Maps to HTTP POST. Used for creating a resource or performing an action. + string post = 4; + + // Maps to HTTP DELETE. Used for deleting a resource. + string delete = 5; + + // Maps to HTTP PATCH. Used for updating a resource. + string patch = 6; + + // The custom pattern is used for specifying an HTTP method that is not + // included in the `pattern` field, such as HEAD, or "*" to leave the + // HTTP method unspecified for this rule. The wild-card rule is useful + // for services that provide content to Web (HTML) clients. + CustomHttpPattern custom = 8; + } + + // The name of the request field whose value is mapped to the HTTP request + // body, or `*` for mapping all request fields not captured by the path + // pattern to the HTTP body, or omitted for not having any HTTP request body. + // + // NOTE: the referred field must be present at the top-level of the request + // message type. + string body = 7; + + // Optional. The name of the response field whose value is mapped to the HTTP + // response body. When omitted, the entire response message will be used + // as the HTTP response body. + // + // NOTE: The referred field must be present at the top-level of the response + // message type. + string response_body = 12; + + // Additional HTTP bindings for the selector. Nested bindings must + // not contain an `additional_bindings` field themselves (that is, + // the nesting may only be one level deep). + repeated HttpRule additional_bindings = 11; +} + +// A custom pattern is used for defining custom HTTP verb. +message CustomHttpPattern { + // The name of this custom HTTP verb. + string kind = 1; + + // The path matched by this custom verb. + string path = 2; +} diff --git a/handwritten/firestore/dev/protos/google/api/launch_stage.proto b/handwritten/firestore/dev/protos/google/api/launch_stage.proto new file mode 100644 index 00000000000..1e86c1ad178 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/api/launch_stage.proto @@ -0,0 +1,72 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api;api"; +option java_multiple_files = true; +option java_outer_classname = "LaunchStageProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// The launch stage as defined by [Google Cloud Platform +// Launch Stages](https://cloud.google.com/terms/launch-stages). +enum LaunchStage { + // Do not use this default value. + LAUNCH_STAGE_UNSPECIFIED = 0; + + // The feature is not yet implemented. Users can not use it. + UNIMPLEMENTED = 6; + + // Prelaunch features are hidden from users and are only visible internally. + PRELAUNCH = 7; + + // Early Access features are limited to a closed group of testers. To use + // these features, you must sign up in advance and sign a Trusted Tester + // agreement (which includes confidentiality provisions). These features may + // be unstable, changed in backward-incompatible ways, and are not + // guaranteed to be released. + EARLY_ACCESS = 1; + + // Alpha is a limited availability test for releases before they are cleared + // for widespread use. By Alpha, all significant design issues are resolved + // and we are in the process of verifying functionality. Alpha customers + // need to apply for access, agree to applicable terms, and have their + // projects allowlisted. Alpha releases don't have to be feature complete, + // no SLAs are provided, and there are no technical support obligations, but + // they will be far enough along that customers can actually use them in + // test environments or for limited-use tests -- just like they would in + // normal production cases. + ALPHA = 2; + + // Beta is the point at which we are ready to open a release for any + // customer to use. There are no SLA or technical support obligations in a + // Beta release. Products will be complete from a feature perspective, but + // may have some open outstanding issues. Beta releases are suitable for + // limited production use cases. + BETA = 3; + + // GA features are open to all developers and are considered stable and + // fully qualified for production use. + GA = 4; + + // Deprecated features are scheduled to be shut down and removed. For more + // information, see the "Deprecation Policy" section of our [Terms of + // Service](https://cloud.google.com/terms/) + // and the [Google Cloud Platform Subject to the Deprecation + // Policy](https://cloud.google.com/terms/deprecation) documentation. + DEPRECATED = 5; +} diff --git a/handwritten/firestore/dev/protos/google/api/resource.proto b/handwritten/firestore/dev/protos/google/api/resource.proto new file mode 100644 index 00000000000..5669cbc985d --- /dev/null +++ b/handwritten/firestore/dev/protos/google/api/resource.proto @@ -0,0 +1,242 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/descriptor.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "ResourceProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.FieldOptions { + // An annotation that describes a resource reference, see + // [ResourceReference][]. + google.api.ResourceReference resource_reference = 1055; +} + +extend google.protobuf.FileOptions { + // An annotation that describes a resource definition without a corresponding + // message; see [ResourceDescriptor][]. + repeated google.api.ResourceDescriptor resource_definition = 1053; +} + +extend google.protobuf.MessageOptions { + // An annotation that describes a resource definition, see + // [ResourceDescriptor][]. + google.api.ResourceDescriptor resource = 1053; +} + +// A simple descriptor of a resource type. +// +// ResourceDescriptor annotates a resource message (either by means of a +// protobuf annotation or use in the service config), and associates the +// resource's schema, the resource type, and the pattern of the resource name. +// +// Example: +// +// message Topic { +// // Indicates this message defines a resource schema. +// // Declares the resource type in the format of {service}/{kind}. +// // For Kubernetes resources, the format is {api group}/{kind}. +// option (google.api.resource) = { +// type: "pubsub.googleapis.com/Topic" +// pattern: "projects/{project}/topics/{topic}" +// }; +// } +// +// The ResourceDescriptor Yaml config will look like: +// +// resources: +// - type: "pubsub.googleapis.com/Topic" +// pattern: "projects/{project}/topics/{topic}" +// +// Sometimes, resources have multiple patterns, typically because they can +// live under multiple parents. +// +// Example: +// +// message LogEntry { +// option (google.api.resource) = { +// type: "logging.googleapis.com/LogEntry" +// pattern: "projects/{project}/logs/{log}" +// pattern: "folders/{folder}/logs/{log}" +// pattern: "organizations/{organization}/logs/{log}" +// pattern: "billingAccounts/{billing_account}/logs/{log}" +// }; +// } +// +// The ResourceDescriptor Yaml config will look like: +// +// resources: +// - type: 'logging.googleapis.com/LogEntry' +// pattern: "projects/{project}/logs/{log}" +// pattern: "folders/{folder}/logs/{log}" +// pattern: "organizations/{organization}/logs/{log}" +// pattern: "billingAccounts/{billing_account}/logs/{log}" +message ResourceDescriptor { + // A description of the historical or future-looking state of the + // resource pattern. + enum History { + // The "unset" value. + HISTORY_UNSPECIFIED = 0; + + // The resource originally had one pattern and launched as such, and + // additional patterns were added later. + ORIGINALLY_SINGLE_PATTERN = 1; + + // The resource has one pattern, but the API owner expects to add more + // later. (This is the inverse of ORIGINALLY_SINGLE_PATTERN, and prevents + // that from being necessary once there are multiple patterns.) + FUTURE_MULTI_PATTERN = 2; + } + + // A flag representing a specific style that a resource claims to conform to. + enum Style { + // The unspecified value. Do not use. + STYLE_UNSPECIFIED = 0; + + // This resource is intended to be "declarative-friendly". + // + // Declarative-friendly resources must be more strictly consistent, and + // setting this to true communicates to tools that this resource should + // adhere to declarative-friendly expectations. + // + // Note: This is used by the API linter (linter.aip.dev) to enable + // additional checks. + DECLARATIVE_FRIENDLY = 1; + } + + // The resource type. It must be in the format of + // {service_name}/{resource_type_kind}. The `resource_type_kind` must be + // singular and must not include version numbers. + // + // Example: `storage.googleapis.com/Bucket` + // + // The value of the resource_type_kind must follow the regular expression + // /[A-Za-z][a-zA-Z0-9]+/. It should start with an upper case character and + // should use PascalCase (UpperCamelCase). The maximum number of + // characters allowed for the `resource_type_kind` is 100. + string type = 1; + + // Optional. The relative resource name pattern associated with this resource + // type. The DNS prefix of the full resource name shouldn't be specified here. + // + // The path pattern must follow the syntax, which aligns with HTTP binding + // syntax: + // + // Template = Segment { "/" Segment } ; + // Segment = LITERAL | Variable ; + // Variable = "{" LITERAL "}" ; + // + // Examples: + // + // - "projects/{project}/topics/{topic}" + // - "projects/{project}/knowledgeBases/{knowledge_base}" + // + // The components in braces correspond to the IDs for each resource in the + // hierarchy. It is expected that, if multiple patterns are provided, + // the same component name (e.g. "project") refers to IDs of the same + // type of resource. + repeated string pattern = 2; + + // Optional. The field on the resource that designates the resource name + // field. If omitted, this is assumed to be "name". + string name_field = 3; + + // Optional. The historical or future-looking state of the resource pattern. + // + // Example: + // + // // The InspectTemplate message originally only supported resource + // // names with organization, and project was added later. + // message InspectTemplate { + // option (google.api.resource) = { + // type: "dlp.googleapis.com/InspectTemplate" + // pattern: + // "organizations/{organization}/inspectTemplates/{inspect_template}" + // pattern: "projects/{project}/inspectTemplates/{inspect_template}" + // history: ORIGINALLY_SINGLE_PATTERN + // }; + // } + History history = 4; + + // The plural name used in the resource name and permission names, such as + // 'projects' for the resource name of 'projects/{project}' and the permission + // name of 'cloudresourcemanager.googleapis.com/projects.get'. One exception + // to this is for Nested Collections that have stuttering names, as defined + // in [AIP-122](https://google.aip.dev/122#nested-collections), where the + // collection ID in the resource name pattern does not necessarily directly + // match the `plural` value. + // + // It is the same concept of the `plural` field in k8s CRD spec + // https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/ + // + // Note: The plural form is required even for singleton resources. See + // https://aip.dev/156 + string plural = 5; + + // The same concept of the `singular` field in k8s CRD spec + // https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/ + // Such as "project" for the `resourcemanager.googleapis.com/Project` type. + string singular = 6; + + // Style flag(s) for this resource. + // These indicate that a resource is expected to conform to a given + // style. See the specific style flags for additional information. + repeated Style style = 10; +} + +// Defines a proto annotation that describes a string field that refers to +// an API resource. +message ResourceReference { + // The resource type that the annotated field references. + // + // Example: + // + // message Subscription { + // string topic = 2 [(google.api.resource_reference) = { + // type: "pubsub.googleapis.com/Topic" + // }]; + // } + // + // Occasionally, a field may reference an arbitrary resource. In this case, + // APIs use the special value * in their resource reference. + // + // Example: + // + // message GetIamPolicyRequest { + // string resource = 2 [(google.api.resource_reference) = { + // type: "*" + // }]; + // } + string type = 1; + + // The resource type of a child collection that the annotated field + // references. This is useful for annotating the `parent` field that + // doesn't have a fixed resource type. + // + // Example: + // + // message ListLogEntriesRequest { + // string parent = 1 [(google.api.resource_reference) = { + // child_type: "logging.googleapis.com/LogEntry" + // }; + // } + string child_type = 2; +} diff --git a/handwritten/firestore/dev/protos/google/api/routing.proto b/handwritten/firestore/dev/protos/google/api/routing.proto new file mode 100644 index 00000000000..4fcb2acb6cd --- /dev/null +++ b/handwritten/firestore/dev/protos/google/api/routing.proto @@ -0,0 +1,461 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/descriptor.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "RoutingProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.MethodOptions { + // See RoutingRule. + google.api.RoutingRule routing = 72295729; +} + +// Specifies the routing information that should be sent along with the request +// in the form of routing header. +// **NOTE:** All service configuration rules follow the "last one wins" order. +// +// The examples below will apply to an RPC which has the following request type: +// +// Message Definition: +// +// message Request { +// // The name of the Table +// // Values can be of the following formats: +// // - `projects//tables/` +// // - `projects//instances//tables/
` +// // - `region//zones//tables/
` +// string table_name = 1; +// +// // This value specifies routing for replication. +// // It can be in the following formats: +// // - `profiles/` +// // - a legacy `profile_id` that can be any string +// string app_profile_id = 2; +// } +// +// Example message: +// +// { +// table_name: projects/proj_foo/instances/instance_bar/table/table_baz, +// app_profile_id: profiles/prof_qux +// } +// +// The routing header consists of one or multiple key-value pairs. Every key +// and value must be percent-encoded, and joined together in the format of +// `key1=value1&key2=value2`. +// The examples below skip the percent-encoding for readability. +// +// Example 1 +// +// Extracting a field from the request to put into the routing header +// unchanged, with the key equal to the field name. +// +// annotation: +// +// option (google.api.routing) = { +// // Take the `app_profile_id`. +// routing_parameters { +// field: "app_profile_id" +// } +// }; +// +// result: +// +// x-goog-request-params: app_profile_id=profiles/prof_qux +// +// Example 2 +// +// Extracting a field from the request to put into the routing header +// unchanged, with the key different from the field name. +// +// annotation: +// +// option (google.api.routing) = { +// // Take the `app_profile_id`, but name it `routing_id` in the header. +// routing_parameters { +// field: "app_profile_id" +// path_template: "{routing_id=**}" +// } +// }; +// +// result: +// +// x-goog-request-params: routing_id=profiles/prof_qux +// +// Example 3 +// +// Extracting a field from the request to put into the routing +// header, while matching a path template syntax on the field's value. +// +// NB: it is more useful to send nothing than to send garbage for the purpose +// of dynamic routing, since garbage pollutes cache. Thus the matching. +// +// Sub-example 3a +// +// The field matches the template. +// +// annotation: +// +// option (google.api.routing) = { +// // Take the `table_name`, if it's well-formed (with project-based +// // syntax). +// routing_parameters { +// field: "table_name" +// path_template: "{table_name=projects/*/instances/*/**}" +// } +// }; +// +// result: +// +// x-goog-request-params: +// table_name=projects/proj_foo/instances/instance_bar/table/table_baz +// +// Sub-example 3b +// +// The field does not match the template. +// +// annotation: +// +// option (google.api.routing) = { +// // Take the `table_name`, if it's well-formed (with region-based +// // syntax). +// routing_parameters { +// field: "table_name" +// path_template: "{table_name=regions/*/zones/*/**}" +// } +// }; +// +// result: +// +// +// +// Sub-example 3c +// +// Multiple alternative conflictingly named path templates are +// specified. The one that matches is used to construct the header. +// +// annotation: +// +// option (google.api.routing) = { +// // Take the `table_name`, if it's well-formed, whether +// // using the region- or projects-based syntax. +// +// routing_parameters { +// field: "table_name" +// path_template: "{table_name=regions/*/zones/*/**}" +// } +// routing_parameters { +// field: "table_name" +// path_template: "{table_name=projects/*/instances/*/**}" +// } +// }; +// +// result: +// +// x-goog-request-params: +// table_name=projects/proj_foo/instances/instance_bar/table/table_baz +// +// Example 4 +// +// Extracting a single routing header key-value pair by matching a +// template syntax on (a part of) a single request field. +// +// annotation: +// +// option (google.api.routing) = { +// // Take just the project id from the `table_name` field. +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=projects/*}/**" +// } +// }; +// +// result: +// +// x-goog-request-params: routing_id=projects/proj_foo +// +// Example 5 +// +// Extracting a single routing header key-value pair by matching +// several conflictingly named path templates on (parts of) a single request +// field. The last template to match "wins" the conflict. +// +// annotation: +// +// option (google.api.routing) = { +// // If the `table_name` does not have instances information, +// // take just the project id for routing. +// // Otherwise take project + instance. +// +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=projects/*}/**" +// } +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=projects/*/instances/*}/**" +// } +// }; +// +// result: +// +// x-goog-request-params: +// routing_id=projects/proj_foo/instances/instance_bar +// +// Example 6 +// +// Extracting multiple routing header key-value pairs by matching +// several non-conflicting path templates on (parts of) a single request field. +// +// Sub-example 6a +// +// Make the templates strict, so that if the `table_name` does not +// have an instance information, nothing is sent. +// +// annotation: +// +// option (google.api.routing) = { +// // The routing code needs two keys instead of one composite +// // but works only for the tables with the "project-instance" name +// // syntax. +// +// routing_parameters { +// field: "table_name" +// path_template: "{project_id=projects/*}/instances/*/**" +// } +// routing_parameters { +// field: "table_name" +// path_template: "projects/*/{instance_id=instances/*}/**" +// } +// }; +// +// result: +// +// x-goog-request-params: +// project_id=projects/proj_foo&instance_id=instances/instance_bar +// +// Sub-example 6b +// +// Make the templates loose, so that if the `table_name` does not +// have an instance information, just the project id part is sent. +// +// annotation: +// +// option (google.api.routing) = { +// // The routing code wants two keys instead of one composite +// // but will work with just the `project_id` for tables without +// // an instance in the `table_name`. +// +// routing_parameters { +// field: "table_name" +// path_template: "{project_id=projects/*}/**" +// } +// routing_parameters { +// field: "table_name" +// path_template: "projects/*/{instance_id=instances/*}/**" +// } +// }; +// +// result (is the same as 6a for our example message because it has the instance +// information): +// +// x-goog-request-params: +// project_id=projects/proj_foo&instance_id=instances/instance_bar +// +// Example 7 +// +// Extracting multiple routing header key-value pairs by matching +// several path templates on multiple request fields. +// +// NB: note that here there is no way to specify sending nothing if one of the +// fields does not match its template. E.g. if the `table_name` is in the wrong +// format, the `project_id` will not be sent, but the `routing_id` will be. +// The backend routing code has to be aware of that and be prepared to not +// receive a full complement of keys if it expects multiple. +// +// annotation: +// +// option (google.api.routing) = { +// // The routing needs both `project_id` and `routing_id` +// // (from the `app_profile_id` field) for routing. +// +// routing_parameters { +// field: "table_name" +// path_template: "{project_id=projects/*}/**" +// } +// routing_parameters { +// field: "app_profile_id" +// path_template: "{routing_id=**}" +// } +// }; +// +// result: +// +// x-goog-request-params: +// project_id=projects/proj_foo&routing_id=profiles/prof_qux +// +// Example 8 +// +// Extracting a single routing header key-value pair by matching +// several conflictingly named path templates on several request fields. The +// last template to match "wins" the conflict. +// +// annotation: +// +// option (google.api.routing) = { +// // The `routing_id` can be a project id or a region id depending on +// // the table name format, but only if the `app_profile_id` is not set. +// // If `app_profile_id` is set it should be used instead. +// +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=projects/*}/**" +// } +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=regions/*}/**" +// } +// routing_parameters { +// field: "app_profile_id" +// path_template: "{routing_id=**}" +// } +// }; +// +// result: +// +// x-goog-request-params: routing_id=profiles/prof_qux +// +// Example 9 +// +// Bringing it all together. +// +// annotation: +// +// option (google.api.routing) = { +// // For routing both `table_location` and a `routing_id` are needed. +// // +// // table_location can be either an instance id or a region+zone id. +// // +// // For `routing_id`, take the value of `app_profile_id` +// // - If it's in the format `profiles/`, send +// // just the `` part. +// // - If it's any other literal, send it as is. +// // If the `app_profile_id` is empty, and the `table_name` starts with +// // the project_id, send that instead. +// +// routing_parameters { +// field: "table_name" +// path_template: "projects/*/{table_location=instances/*}/tables/*" +// } +// routing_parameters { +// field: "table_name" +// path_template: "{table_location=regions/*/zones/*}/tables/*" +// } +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=projects/*}/**" +// } +// routing_parameters { +// field: "app_profile_id" +// path_template: "{routing_id=**}" +// } +// routing_parameters { +// field: "app_profile_id" +// path_template: "profiles/{routing_id=*}" +// } +// }; +// +// result: +// +// x-goog-request-params: +// table_location=instances/instance_bar&routing_id=prof_qux +message RoutingRule { + // A collection of Routing Parameter specifications. + // **NOTE:** If multiple Routing Parameters describe the same key + // (via the `path_template` field or via the `field` field when + // `path_template` is not provided), "last one wins" rule + // determines which Parameter gets used. + // See the examples for more details. + repeated RoutingParameter routing_parameters = 2; +} + +// A projection from an input message to the GRPC or REST header. +message RoutingParameter { + // A request field to extract the header key-value pair from. + string field = 1; + + // A pattern matching the key-value field. Optional. + // If not specified, the whole field specified in the `field` field will be + // taken as value, and its name used as key. If specified, it MUST contain + // exactly one named segment (along with any number of unnamed segments) The + // pattern will be matched over the field specified in the `field` field, then + // if the match is successful: + // - the name of the single named segment will be used as a header name, + // - the match value of the segment will be used as a header value; + // if the match is NOT successful, nothing will be sent. + // + // Example: + // + // -- This is a field in the request message + // | that the header value will be extracted from. + // | + // | -- This is the key name in the + // | | routing header. + // V | + // field: "table_name" v + // path_template: "projects/*/{table_location=instances/*}/tables/*" + // ^ ^ + // | | + // In the {} brackets is the pattern that -- | + // specifies what to extract from the | + // field as a value to be sent. | + // | + // The string in the field must match the whole pattern -- + // before brackets, inside brackets, after brackets. + // + // When looking at this specific example, we can see that: + // - A key-value pair with the key `table_location` + // and the value matching `instances/*` should be added + // to the x-goog-request-params routing header. + // - The value is extracted from the request message's `table_name` field + // if it matches the full pattern specified: + // `projects/*/instances/*/tables/*`. + // + // **NB:** If the `path_template` field is not provided, the key name is + // equal to the field name, and the whole field should be sent as a value. + // This makes the pattern for the field and the value functionally equivalent + // to `**`, and the configuration + // + // { + // field: "table_name" + // } + // + // is a functionally equivalent shorthand to: + // + // { + // field: "table_name" + // path_template: "{table_name=**}" + // } + // + // See Example 1 for more details. + string path_template = 2; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/admin/v1/backup.proto b/handwritten/firestore/dev/protos/google/firestore/admin/v1/backup.proto new file mode 100644 index 00000000000..bed41ff6680 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/admin/v1/backup.proto @@ -0,0 +1,107 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "BackupProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; + +// A Backup of a Cloud Firestore Database. +// +// The backup contains all documents and index configurations for the given +// database at a specific point in time. +message Backup { + option (google.api.resource) = { + type: "firestore.googleapis.com/Backup" + pattern: "projects/{project}/locations/{location}/backups/{backup}" + }; + + // Backup specific statistics. + message Stats { + // Output only. Summation of the size of all documents and index entries in + // the backup, measured in bytes. + int64 size_bytes = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The total number of documents contained in the backup. + int64 document_count = 2 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The total number of index entries contained in the backup. + int64 index_count = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; + } + + // Indicate the current state of the backup. + enum State { + // The state is unspecified. + STATE_UNSPECIFIED = 0; + + // The pending backup is still being created. Operations on the + // backup will be rejected in this state. + CREATING = 1; + + // The backup is complete and ready to use. + READY = 2; + + // The backup is not available at this moment. + NOT_AVAILABLE = 3; + } + + // Output only. The unique resource name of the Backup. + // + // Format is `projects/{project}/locations/{location}/backups/{backup}`. + string name = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Name of the Firestore database that the backup is from. + // + // Format is `projects/{project}/databases/{database}`. + string database = 2 [ + (google.api.field_behavior) = OUTPUT_ONLY, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; + + // Output only. The system-generated UUID4 for the Firestore database that the + // backup is from. + string database_uid = 7 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The backup contains an externally consistent copy of the + // database at this time. + google.protobuf.Timestamp snapshot_time = 3 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The timestamp at which this backup expires. + google.protobuf.Timestamp expire_time = 4 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Statistics about the backup. + // + // This data only becomes available after the backup is fully materialized to + // secondary storage. This field will be empty till then. + Stats stats = 6 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The current state of the backup. + State state = 8 [(google.api.field_behavior) = OUTPUT_ONLY]; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/admin/v1/database.proto b/handwritten/firestore/dev/protos/google/firestore/admin/v1/database.proto new file mode 100644 index 00000000000..3537e4a3b64 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/admin/v1/database.proto @@ -0,0 +1,362 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "DatabaseProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; +option (google.api.resource_definition) = { + type: "firestore.googleapis.com/Operation" + pattern: "projects/{project}/databases/{database}/operations/{operation}" +}; + +// A Cloud Firestore Database. +message Database { + option (google.api.resource) = { + type: "firestore.googleapis.com/Database" + pattern: "projects/{project}/databases/{database}" + style: DECLARATIVE_FRIENDLY + }; + + // The type of the database. + // See https://cloud.google.com/datastore/docs/firestore-or-datastore for + // information about how to choose. + // + // Mode changes are only allowed if the database is empty. + enum DatabaseType { + // Not used. + DATABASE_TYPE_UNSPECIFIED = 0; + + // Firestore Native Mode + FIRESTORE_NATIVE = 1; + + // Firestore in Datastore Mode. + DATASTORE_MODE = 2; + } + + // The type of concurrency control mode for transactions. + enum ConcurrencyMode { + // Not used. + CONCURRENCY_MODE_UNSPECIFIED = 0; + + // Use optimistic concurrency control by default. This mode is available + // for Cloud Firestore databases. + OPTIMISTIC = 1; + + // Use pessimistic concurrency control by default. This mode is available + // for Cloud Firestore databases. + // + // This is the default setting for Cloud Firestore. + PESSIMISTIC = 2; + + // Use optimistic concurrency control with entity groups by default. + // + // This is the only available mode for Cloud Datastore. + // + // This mode is also available for Cloud Firestore with Datastore Mode but + // is not recommended. + OPTIMISTIC_WITH_ENTITY_GROUPS = 3; + } + + // Point In Time Recovery feature enablement. + enum PointInTimeRecoveryEnablement { + // Not used. + POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED = 0; + + // Reads are supported on selected versions of the data from within the past + // 7 days: + // + // * Reads against any timestamp within the past hour + // * Reads against 1-minute snapshots beyond 1 hour and within 7 days + // + // `version_retention_period` and `earliest_version_time` can be + // used to determine the supported versions. + POINT_IN_TIME_RECOVERY_ENABLED = 1; + + // Reads are supported on any version of the data from within the past 1 + // hour. + POINT_IN_TIME_RECOVERY_DISABLED = 2; + } + + // The type of App Engine integration mode. + enum AppEngineIntegrationMode { + // Not used. + APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED = 0; + + // If an App Engine application exists in the same region as this database, + // App Engine configuration will impact this database. This includes + // disabling of the application & database, as well as disabling writes to + // the database. + ENABLED = 1; + + // App Engine has no effect on the ability of this database to serve + // requests. + // + // This is the default setting for databases created with the Firestore API. + DISABLED = 2; + } + + // The delete protection state of the database. + enum DeleteProtectionState { + // The default value. Delete protection type is not specified + DELETE_PROTECTION_STATE_UNSPECIFIED = 0; + + // Delete protection is disabled + DELETE_PROTECTION_DISABLED = 1; + + // Delete protection is enabled + DELETE_PROTECTION_ENABLED = 2; + } + + // The CMEK (Customer Managed Encryption Key) configuration for a Firestore + // database. If not present, the database is secured by the default Google + // encryption key. + message CmekConfig { + // Required. Only keys in the same location as this database are allowed to + // be used for encryption. + // + // For Firestore's nam5 multi-region, this corresponds to Cloud KMS + // multi-region us. For Firestore's eur3 multi-region, this corresponds to + // Cloud KMS multi-region europe. See + // https://cloud.google.com/kms/docs/locations. + // + // The expected format is + // `projects/{project_id}/locations/{kms_location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}`. + string kms_key_name = 1 [(google.api.field_behavior) = REQUIRED]; + + // Output only. Currently in-use [KMS key + // versions](https://cloud.google.com/kms/docs/resource-hierarchy#key_versions). + // During [key rotation](https://cloud.google.com/kms/docs/key-rotation), + // there can be multiple in-use key versions. + // + // The expected format is + // `projects/{project_id}/locations/{kms_location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{key_version}`. + repeated string active_key_version = 2 + [(google.api.field_behavior) = OUTPUT_ONLY]; + } + + // Information about the provenance of this database. + message SourceInfo { + // Information about a backup that was used to restore a database. + message BackupSource { + // The resource name of the backup that was used to restore this + // database. Format: + // `projects/{project}/locations/{location}/backups/{backup}`. + string backup = 1 [(google.api.resource_reference) = { + type: "firestore.googleapis.com/Backup" + }]; + } + + // The source from which this database is derived. + oneof source { + // If set, this database was restored from the specified backup (or a + // snapshot thereof). + BackupSource backup = 1; + } + + // The associated long-running operation. This field may not be set after + // the operation has completed. Format: + // `projects/{project}/databases/{database}/operations/{operation}`. + string operation = 3 [(google.api.resource_reference) = { + type: "firestore.googleapis.com/Operation" + }]; + } + + // Encryption configuration for a new database being created from another + // source. + // + // The source could be a [Backup][google.firestore.admin.v1.Backup] . + message EncryptionConfig { + // The configuration options for using Google default encryption. + message GoogleDefaultEncryptionOptions {} + + // The configuration options for using the same encryption method as the + // source. + message SourceEncryptionOptions {} + + // The configuration options for using CMEK (Customer Managed Encryption + // Key) encryption. + message CustomerManagedEncryptionOptions { + // Required. Only keys in the same location as the database are allowed to + // be used for encryption. + // + // For Firestore's nam5 multi-region, this corresponds to Cloud KMS + // multi-region us. For Firestore's eur3 multi-region, this corresponds to + // Cloud KMS multi-region europe. See + // https://cloud.google.com/kms/docs/locations. + // + // The expected format is + // `projects/{project_id}/locations/{kms_location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}`. + string kms_key_name = 1 [(google.api.field_behavior) = REQUIRED]; + } + + // The method for encrypting the database. + oneof encryption_type { + // Use Google default encryption. + GoogleDefaultEncryptionOptions google_default_encryption = 1; + + // The database will use the same encryption configuration as the source. + SourceEncryptionOptions use_source_encryption = 2; + + // Use Customer Managed Encryption Keys (CMEK) for encryption. + CustomerManagedEncryptionOptions customer_managed_encryption = 3; + } + } + + // The edition of the database. + enum DatabaseEdition { + // Not used. + DATABASE_EDITION_UNSPECIFIED = 0; + + // Standard edition. + // + // This is the default setting if not specified. + STANDARD = 1; + + // Enterprise edition. + ENTERPRISE = 2; + } + + // The resource name of the Database. + // Format: `projects/{project}/databases/{database}` + string name = 1; + + // Output only. The system-generated UUID4 for this Database. + string uid = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The timestamp at which this database was created. Databases + // created before 2016 do not populate create_time. + google.protobuf.Timestamp create_time = 5 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The timestamp at which this database was most recently + // updated. Note this only includes updates to the database resource and not + // data contained by the database. + google.protobuf.Timestamp update_time = 6 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The timestamp at which this database was deleted. Only set if + // the database has been deleted. + google.protobuf.Timestamp delete_time = 7 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // The location of the database. Available locations are listed at + // https://cloud.google.com/firestore/docs/locations. + string location_id = 9; + + // The type of the database. + // See https://cloud.google.com/datastore/docs/firestore-or-datastore for + // information about how to choose. + DatabaseType type = 10; + + // The concurrency control mode to use for this database. + ConcurrencyMode concurrency_mode = 15; + + // Output only. The period during which past versions of data are retained in + // the database. + // + // Any [read][google.firestore.v1.GetDocumentRequest.read_time] + // or [query][google.firestore.v1.ListDocumentsRequest.read_time] can specify + // a `read_time` within this window, and will read the state of the database + // at that time. + // + // If the PITR feature is enabled, the retention period is 7 days. Otherwise, + // the retention period is 1 hour. + google.protobuf.Duration version_retention_period = 17 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The earliest timestamp at which older versions of the data can + // be read from the database. See [version_retention_period] above; this field + // is populated with `now - version_retention_period`. + // + // This value is continuously updated, and becomes stale the moment it is + // queried. If you are using this value to recover data, make sure to account + // for the time from the moment when the value is queried to the moment when + // you initiate the recovery. + google.protobuf.Timestamp earliest_version_time = 18 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Whether to enable the PITR feature on this database. + PointInTimeRecoveryEnablement point_in_time_recovery_enablement = 21; + + // The App Engine integration mode to use for this database. + AppEngineIntegrationMode app_engine_integration_mode = 19; + + // Output only. The key_prefix for this database. This key_prefix is used, in + // combination with the project ID ("~") to construct + // the application ID that is returned from the Cloud Datastore APIs in Google + // App Engine first generation runtimes. + // + // This value may be empty in which case the appid to use for URL-encoded keys + // is the project_id (eg: foo instead of v~foo). + string key_prefix = 20 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // State of delete protection for the database. + DeleteProtectionState delete_protection_state = 22; + + // Optional. Presence indicates CMEK is enabled for this database. + CmekConfig cmek_config = 23 [(google.api.field_behavior) = OPTIONAL]; + + // Output only. The database resource's prior database ID. This field is only + // populated for deleted databases. + string previous_id = 25 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Information about the provenance of this database. + SourceInfo source_info = 26 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Optional. Input only. Immutable. Tag keys/values directly bound to this + // resource. For example: + // "123/environment": "production", + // "123/costCenter": "marketing" + map tags = 29 [ + (google.api.field_behavior) = INPUT_ONLY, + (google.api.field_behavior) = IMMUTABLE, + (google.api.field_behavior) = OPTIONAL + ]; + + // Output only. Background: Free tier is the ability of a Firestore database + // to use a small amount of resources every day without being charged. Once + // usage exceeds the free tier limit further usage is charged. + // + // Whether this database can make use of the free tier. Only one database + // per project can be eligible for the free tier. + // + // The first (or next) database that is created in a project without a free + // tier database will be marked as eligible for the free tier. Databases that + // are created while there is a free tier database will not be eligible for + // the free tier. + optional bool free_tier = 30 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // This checksum is computed by the server based on the value of other + // fields, and may be sent on update and delete requests to ensure the + // client has an up-to-date value before proceeding. + string etag = 99; + + // Immutable. The edition of the database. + DatabaseEdition database_edition = 28 + [(google.api.field_behavior) = IMMUTABLE]; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/admin/v1/field.proto b/handwritten/firestore/dev/protos/google/firestore/admin/v1/field.proto new file mode 100644 index 00000000000..d899bdb5c03 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/admin/v1/field.proto @@ -0,0 +1,137 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/firestore/admin/v1/index.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "FieldProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; + +// Represents a single field in the database. +// +// Fields are grouped by their "Collection Group", which represent all +// collections in the database with the same ID. +message Field { + option (google.api.resource) = { + type: "firestore.googleapis.com/Field" + pattern: "projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}" + }; + + // The index configuration for this field. + message IndexConfig { + // The indexes supported for this field. + repeated Index indexes = 1; + + // Output only. When true, the `Field`'s index configuration is set from the + // configuration specified by the `ancestor_field`. + // When false, the `Field`'s index configuration is defined explicitly. + bool uses_ancestor_config = 2; + + // Output only. Specifies the resource name of the `Field` from which this + // field's index configuration is set (when `uses_ancestor_config` is true), + // or from which it *would* be set if this field had no index configuration + // (when `uses_ancestor_config` is false). + string ancestor_field = 3; + + // Output only + // When true, the `Field`'s index configuration is in the process of being + // reverted. Once complete, the index config will transition to the same + // state as the field specified by `ancestor_field`, at which point + // `uses_ancestor_config` will be `true` and `reverting` will be `false`. + bool reverting = 4; + } + + // The TTL (time-to-live) configuration for documents that have this `Field` + // set. + // + // Storing a timestamp value into a TTL-enabled field will be treated as + // the document's absolute expiration time. Timestamp values in the past + // indicate that the document is eligible for immediate expiration. Using any + // other data type or leaving the field absent will disable expiration for the + // individual document. + message TtlConfig { + // The state of applying the TTL configuration to all documents. + enum State { + // The state is unspecified or unknown. + STATE_UNSPECIFIED = 0; + + // The TTL is being applied. There is an active long-running operation to + // track the change. Newly written documents will have TTLs applied as + // requested. Requested TTLs on existing documents are still being + // processed. When TTLs on all existing documents have been processed, the + // state will move to 'ACTIVE'. + CREATING = 1; + + // The TTL is active for all documents. + ACTIVE = 2; + + // The TTL configuration could not be enabled for all existing documents. + // Newly written documents will continue to have their TTL applied. + // The LRO returned when last attempting to enable TTL for this `Field` + // has failed, and may have more details. + NEEDS_REPAIR = 3; + } + + // Output only. The state of the TTL configuration. + State state = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + } + + // Required. A field name of the form: + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_path}` + // + // A field path can be a simple field name, e.g. `address` or a path to fields + // within `map_value` , e.g. `address.city`, + // or a special field path. The only valid special field is `*`, which + // represents any field. + // + // Field paths can be quoted using `` ` `` (backtick). The only character that + // must be escaped within a quoted field path is the backtick character + // itself, escaped using a backslash. Special characters in field paths that + // must be quoted include: `*`, `.`, + // `` ` `` (backtick), `[`, `]`, as well as any ascii symbolic characters. + // + // Examples: + // `` `address.city` `` represents a field named `address.city`, not the map + // key `city` in the field `address`. `` `*` `` represents a field named `*`, + // not any field. + // + // A special `Field` contains the default indexing settings for all fields. + // This field's resource name is: + // `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*` + // Indexes defined on this `Field` will be applied to all fields which do not + // have their own `Field` index configuration. + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // The index configuration for this field. If unset, field indexing will + // revert to the configuration defined by the `ancestor_field`. To + // explicitly remove all indexes for this field, specify an index config + // with an empty list of indexes. + IndexConfig index_config = 2; + + // The TTL configuration for this `Field`. + // Setting or unsetting this will enable or disable the TTL for + // documents that have this `Field`. + TtlConfig ttl_config = 3; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/admin/v1/firestore_admin.proto b/handwritten/firestore/dev/protos/google/firestore/admin/v1/firestore_admin.proto new file mode 100644 index 00000000000..1d4efbdde1b --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/admin/v1/firestore_admin.proto @@ -0,0 +1,1228 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/api/routing.proto"; +import "google/firestore/admin/v1/backup.proto"; +import "google/firestore/admin/v1/database.proto"; +import "google/firestore/admin/v1/field.proto"; +import "google/firestore/admin/v1/index.proto"; +import "google/firestore/admin/v1/operation.proto"; +import "google/firestore/admin/v1/schedule.proto"; +import "google/firestore/admin/v1/snapshot.proto"; +import "google/firestore/admin/v1/user_creds.proto"; +import "google/longrunning/operations.proto"; +import "google/protobuf/empty.proto"; +import "google/protobuf/field_mask.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "FirestoreAdminProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; +option (google.api.resource_definition) = { + type: "firestore.googleapis.com/Location" + pattern: "projects/{project}/locations/{location}" +}; +option (google.api.resource_definition) = { + type: "firestore.googleapis.com/CollectionGroup" + pattern: "projects/{project}/databases/{database}/collectionGroups/{collection}" +}; + +// The Cloud Firestore Admin API. +// +// This API provides several administrative services for Cloud Firestore. +// +// Project, Database, Namespace, Collection, Collection Group, and Document are +// used as defined in the Google Cloud Firestore API. +// +// Operation: An Operation represents work being performed in the background. +// +// The index service manages Cloud Firestore indexes. +// +// Index creation is performed asynchronously. +// An Operation resource is created for each such asynchronous operation. +// The state of the operation (including any errors encountered) +// may be queried via the Operation resource. +// +// The Operations collection provides a record of actions performed for the +// specified Project (including any Operations in progress). Operations are not +// created directly but through calls on other collections or resources. +// +// An Operation that is done may be deleted so that it is no longer listed as +// part of the Operation collection. Operations are garbage collected after +// 30 days. By default, ListOperations will only return in progress and failed +// operations. To list completed operation, issue a ListOperations request with +// the filter `done: true`. +// +// Operations are created by service `FirestoreAdmin`, but are accessed via +// service `google.longrunning.Operations`. +service FirestoreAdmin { + option (google.api.default_host) = "firestore.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/datastore"; + + // Creates a composite index. This returns a + // [google.longrunning.Operation][google.longrunning.Operation] which may be + // used to track the status of the creation. The metadata for the operation + // will be the type + // [IndexOperationMetadata][google.firestore.admin.v1.IndexOperationMetadata]. + rpc CreateIndex(CreateIndexRequest) returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/databases/*/collectionGroups/*}/indexes" + body: "index" + }; + option (google.api.method_signature) = "parent,index"; + option (google.longrunning.operation_info) = { + response_type: "Index" + metadata_type: "IndexOperationMetadata" + }; + } + + // Lists composite indexes. + rpc ListIndexes(ListIndexesRequest) returns (ListIndexesResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/databases/*/collectionGroups/*}/indexes" + }; + option (google.api.method_signature) = "parent"; + } + + // Gets a composite index. + rpc GetIndex(GetIndexRequest) returns (Index) { + option (google.api.http) = { + get: "/v1/{name=projects/*/databases/*/collectionGroups/*/indexes/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Deletes a composite index. + rpc DeleteIndex(DeleteIndexRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/databases/*/collectionGroups/*/indexes/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Gets the metadata and configuration for a Field. + rpc GetField(GetFieldRequest) returns (Field) { + option (google.api.http) = { + get: "/v1/{name=projects/*/databases/*/collectionGroups/*/fields/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Updates a field configuration. Currently, field updates apply only to + // single field index configuration. However, calls to + // [FirestoreAdmin.UpdateField][google.firestore.admin.v1.FirestoreAdmin.UpdateField] + // should provide a field mask to avoid changing any configuration that the + // caller isn't aware of. The field mask should be specified as: `{ paths: + // "index_config" }`. + // + // This call returns a + // [google.longrunning.Operation][google.longrunning.Operation] which may be + // used to track the status of the field update. The metadata for the + // operation will be the type + // [FieldOperationMetadata][google.firestore.admin.v1.FieldOperationMetadata]. + // + // To configure the default field settings for the database, use + // the special `Field` with resource name: + // `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*`. + rpc UpdateField(UpdateFieldRequest) returns (google.longrunning.Operation) { + option (google.api.http) = { + patch: "/v1/{field.name=projects/*/databases/*/collectionGroups/*/fields/*}" + body: "field" + }; + option (google.api.method_signature) = "field"; + option (google.longrunning.operation_info) = { + response_type: "Field" + metadata_type: "FieldOperationMetadata" + }; + } + + // Lists the field configuration and metadata for this database. + // + // Currently, + // [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] + // only supports listing fields that have been explicitly overridden. To issue + // this query, call + // [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] + // with the filter set to `indexConfig.usesAncestorConfig:false` or + // `ttlConfig:*`. + rpc ListFields(ListFieldsRequest) returns (ListFieldsResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/databases/*/collectionGroups/*}/fields" + }; + option (google.api.method_signature) = "parent"; + } + + // Exports a copy of all or a subset of documents from Google Cloud Firestore + // to another storage system, such as Google Cloud Storage. Recent updates to + // documents may not be reflected in the export. The export occurs in the + // background and its progress can be monitored and managed via the + // Operation resource that is created. The output of an export may only be + // used once the associated operation is done. If an export operation is + // cancelled before completion it may leave partial data behind in Google + // Cloud Storage. + // + // For more details on export behavior and output format, refer to: + // https://cloud.google.com/firestore/docs/manage-data/export-import + rpc ExportDocuments(ExportDocumentsRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{name=projects/*/databases/*}:exportDocuments" + body: "*" + }; + option (google.api.method_signature) = "name"; + option (google.longrunning.operation_info) = { + response_type: "ExportDocumentsResponse" + metadata_type: "ExportDocumentsMetadata" + }; + } + + // Imports documents into Google Cloud Firestore. Existing documents with the + // same name are overwritten. The import occurs in the background and its + // progress can be monitored and managed via the Operation resource that is + // created. If an ImportDocuments operation is cancelled, it is possible + // that a subset of the data has already been imported to Cloud Firestore. + rpc ImportDocuments(ImportDocumentsRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{name=projects/*/databases/*}:importDocuments" + body: "*" + }; + option (google.api.method_signature) = "name"; + option (google.longrunning.operation_info) = { + response_type: "google.protobuf.Empty" + metadata_type: "ImportDocumentsMetadata" + }; + } + + // Bulk deletes a subset of documents from Google Cloud Firestore. + // Documents created or updated after the underlying system starts to process + // the request will not be deleted. The bulk delete occurs in the background + // and its progress can be monitored and managed via the Operation resource + // that is created. + // + // For more details on bulk delete behavior, refer to: + // https://cloud.google.com/firestore/docs/manage-data/bulk-delete + rpc BulkDeleteDocuments(BulkDeleteDocumentsRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{name=projects/*/databases/*}:bulkDeleteDocuments" + body: "*" + }; + option (google.api.method_signature) = "name"; + option (google.longrunning.operation_info) = { + response_type: "BulkDeleteDocumentsResponse" + metadata_type: "BulkDeleteDocumentsMetadata" + }; + } + + // Create a database. + rpc CreateDatabase(CreateDatabaseRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{parent=projects/*}/databases" + body: "database" + }; + option (google.api.method_signature) = "parent,database,database_id"; + option (google.longrunning.operation_info) = { + response_type: "Database" + metadata_type: "CreateDatabaseMetadata" + }; + } + + // Gets information about a database. + rpc GetDatabase(GetDatabaseRequest) returns (Database) { + option (google.api.http) = { + get: "/v1/{name=projects/*/databases/*}" + }; + option (google.api.method_signature) = "name"; + } + + // List all the databases in the project. + rpc ListDatabases(ListDatabasesRequest) returns (ListDatabasesResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*}/databases" + }; + option (google.api.method_signature) = "parent"; + } + + // Updates a database. + rpc UpdateDatabase(UpdateDatabaseRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + patch: "/v1/{database.name=projects/*/databases/*}" + body: "database" + }; + option (google.api.method_signature) = "database,update_mask"; + option (google.longrunning.operation_info) = { + response_type: "Database" + metadata_type: "UpdateDatabaseMetadata" + }; + } + + // Deletes a database. + rpc DeleteDatabase(DeleteDatabaseRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/databases/*}" + }; + option (google.api.method_signature) = "name"; + option (google.longrunning.operation_info) = { + response_type: "Database" + metadata_type: "DeleteDatabaseMetadata" + }; + } + + // Create a user creds. + rpc CreateUserCreds(CreateUserCredsRequest) returns (UserCreds) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/databases/*}/userCreds" + body: "user_creds" + }; + option (google.api.method_signature) = "parent,user_creds,user_creds_id"; + } + + // Gets a user creds resource. Note that the returned resource does not + // contain the secret value itself. + rpc GetUserCreds(GetUserCredsRequest) returns (UserCreds) { + option (google.api.http) = { + get: "/v1/{name=projects/*/databases/*/userCreds/*}" + }; + option (google.api.method_signature) = "name"; + } + + // List all user creds in the database. Note that the returned resource + // does not contain the secret value itself. + rpc ListUserCreds(ListUserCredsRequest) returns (ListUserCredsResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/databases/*}/userCreds" + }; + option (google.api.method_signature) = "parent"; + } + + // Enables a user creds. No-op if the user creds are already enabled. + rpc EnableUserCreds(EnableUserCredsRequest) returns (UserCreds) { + option (google.api.http) = { + post: "/v1/{name=projects/*/databases/*/userCreds/*}:enable" + body: "*" + }; + option (google.api.method_signature) = "name"; + } + + // Disables a user creds. No-op if the user creds are already disabled. + rpc DisableUserCreds(DisableUserCredsRequest) returns (UserCreds) { + option (google.api.http) = { + post: "/v1/{name=projects/*/databases/*/userCreds/*}:disable" + body: "*" + }; + option (google.api.method_signature) = "name"; + } + + // Resets the password of a user creds. + rpc ResetUserPassword(ResetUserPasswordRequest) returns (UserCreds) { + option (google.api.http) = { + post: "/v1/{name=projects/*/databases/*/userCreds/*}:resetPassword" + body: "*" + }; + option (google.api.method_signature) = "name"; + } + + // Deletes a user creds. + rpc DeleteUserCreds(DeleteUserCredsRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/databases/*/userCreds/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Gets information about a backup. + rpc GetBackup(GetBackupRequest) returns (Backup) { + option (google.api.http) = { + get: "/v1/{name=projects/*/locations/*/backups/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Lists all the backups. + rpc ListBackups(ListBackupsRequest) returns (ListBackupsResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/locations/*}/backups" + }; + option (google.api.method_signature) = "parent"; + } + + // Deletes a backup. + rpc DeleteBackup(DeleteBackupRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/locations/*/backups/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Creates a new database by restoring from an existing backup. + // + // The new database must be in the same cloud region or multi-region location + // as the existing backup. This behaves similar to + // [FirestoreAdmin.CreateDatabase][google.firestore.admin.v1.FirestoreAdmin.CreateDatabase] + // except instead of creating a new empty database, a new database is created + // with the database type, index configuration, and documents from an existing + // backup. + // + // The [long-running operation][google.longrunning.Operation] can be used to + // track the progress of the restore, with the Operation's + // [metadata][google.longrunning.Operation.metadata] field type being the + // [RestoreDatabaseMetadata][google.firestore.admin.v1.RestoreDatabaseMetadata]. + // The [response][google.longrunning.Operation.response] type is the + // [Database][google.firestore.admin.v1.Database] if the restore was + // successful. The new database is not readable or writeable until the LRO has + // completed. + rpc RestoreDatabase(RestoreDatabaseRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{parent=projects/*}/databases:restore" + body: "*" + }; + option (google.longrunning.operation_info) = { + response_type: "Database" + metadata_type: "RestoreDatabaseMetadata" + }; + } + + // Creates a backup schedule on a database. + // At most two backup schedules can be configured on a database, one daily + // backup schedule and one weekly backup schedule. + rpc CreateBackupSchedule(CreateBackupScheduleRequest) + returns (BackupSchedule) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/databases/*}/backupSchedules" + body: "backup_schedule" + }; + option (google.api.method_signature) = "parent,backup_schedule"; + } + + // Gets information about a backup schedule. + rpc GetBackupSchedule(GetBackupScheduleRequest) returns (BackupSchedule) { + option (google.api.http) = { + get: "/v1/{name=projects/*/databases/*/backupSchedules/*}" + }; + option (google.api.method_signature) = "name"; + } + + // List backup schedules. + rpc ListBackupSchedules(ListBackupSchedulesRequest) + returns (ListBackupSchedulesResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/databases/*}/backupSchedules" + }; + option (google.api.method_signature) = "parent"; + } + + // Updates a backup schedule. + rpc UpdateBackupSchedule(UpdateBackupScheduleRequest) + returns (BackupSchedule) { + option (google.api.http) = { + patch: "/v1/{backup_schedule.name=projects/*/databases/*/backupSchedules/*}" + body: "backup_schedule" + }; + option (google.api.method_signature) = "backup_schedule,update_mask"; + } + + // Deletes a backup schedule. + rpc DeleteBackupSchedule(DeleteBackupScheduleRequest) + returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/databases/*/backupSchedules/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Creates a new database by cloning an existing one. + // + // The new database must be in the same cloud region or multi-region location + // as the existing database. This behaves similar to + // [FirestoreAdmin.CreateDatabase][google.firestore.admin.v1.FirestoreAdmin.CreateDatabase] + // except instead of creating a new empty database, a new database is created + // with the database type, index configuration, and documents from an existing + // database. + // + // The [long-running operation][google.longrunning.Operation] can be used to + // track the progress of the clone, with the Operation's + // [metadata][google.longrunning.Operation.metadata] field type being the + // [CloneDatabaseMetadata][google.firestore.admin.v1.CloneDatabaseMetadata]. + // The [response][google.longrunning.Operation.response] type is the + // [Database][google.firestore.admin.v1.Database] if the clone was + // successful. The new database is not readable or writeable until the LRO has + // completed. + rpc CloneDatabase(CloneDatabaseRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{parent=projects/*}/databases:clone" + body: "*" + }; + option (google.api.routing) = { + routing_parameters { + field: "pitr_snapshot.database" + path_template: "projects/{project_id=*}/**" + } + routing_parameters { + field: "pitr_snapshot.database" + path_template: "projects/*/databases/{database_id=*}/**" + } + }; + option (google.longrunning.operation_info) = { + response_type: "Database" + metadata_type: "CloneDatabaseMetadata" + }; + } +} + +// A request to list the Firestore Databases in all locations for a project. +message ListDatabasesRequest { + // Required. A parent name of the form + // `projects/{project_id}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "firestore.googleapis.com/Database" + } + ]; + + // If true, also returns deleted resources. + bool show_deleted = 4; +} + +// The request for +// [FirestoreAdmin.CreateDatabase][google.firestore.admin.v1.FirestoreAdmin.CreateDatabase]. +message CreateDatabaseRequest { + // Required. A parent name of the form + // `projects/{project_id}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "firestore.googleapis.com/Database" + } + ]; + + // Required. The Database to create. + Database database = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. The ID to use for the database, which will become the final + // component of the database's resource name. + // + // This value should be 4-63 characters. Valid characters are /[a-z][0-9]-/ + // with first character a letter and the last a letter or a number. Must not + // be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + // + // "(default)" database ID is also valid. + string database_id = 3 [(google.api.field_behavior) = REQUIRED]; +} + +// Metadata related to the create database operation. +message CreateDatabaseMetadata {} + +// The list of databases for a project. +message ListDatabasesResponse { + // The databases in the project. + repeated Database databases = 1; + + // In the event that data about individual databases cannot be listed they + // will be recorded here. + // + // An example entry might be: projects/some_project/locations/some_location + // This can happen if the Cloud Region that the Database resides in is + // currently unavailable. In this case we can't fetch all the details about + // the database. You may be able to get a more detailed error message + // (or possibly fetch the resource) by sending a 'Get' request for the + // resource or a 'List' request for the specific location. + repeated string unreachable = 3; +} + +// The request for +// [FirestoreAdmin.GetDatabase][google.firestore.admin.v1.FirestoreAdmin.GetDatabase]. +message GetDatabaseRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; +} + +// The request for +// [FirestoreAdmin.UpdateDatabase][google.firestore.admin.v1.FirestoreAdmin.UpdateDatabase]. +message UpdateDatabaseRequest { + // Required. The database to update. + Database database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The list of fields to be updated. + google.protobuf.FieldMask update_mask = 2; +} + +// Metadata related to the update database operation. +message UpdateDatabaseMetadata {} + +// The request for +// [FirestoreAdmin.DeleteDatabase][google.firestore.admin.v1.FirestoreAdmin.DeleteDatabase]. +message DeleteDatabaseRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; + + // The current etag of the Database. + // If an etag is provided and does not match the current etag of the database, + // deletion will be blocked and a FAILED_PRECONDITION error will be returned. + string etag = 3; +} + +// Metadata related to the delete database operation. +message DeleteDatabaseMetadata {} + +// The request for +// [FirestoreAdmin.CreateUserCreds][google.firestore.admin.v1.FirestoreAdmin.CreateUserCreds]. +message CreateUserCredsRequest { + // Required. A parent name of the form + // `projects/{project_id}/databases/{database_id}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "firestore.googleapis.com/UserCreds" + } + ]; + + // Required. The user creds to create. + UserCreds user_creds = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. The ID to use for the user creds, which will become the final + // component of the user creds's resource name. + // + // This value should be 4-63 characters. Valid characters are /[a-z][0-9]-/ + // with first character a letter and the last a letter or a number. Must not + // be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + string user_creds_id = 3 [(google.api.field_behavior) = REQUIRED]; +} + +// The request for +// [FirestoreAdmin.GetUserCreds][google.firestore.admin.v1.FirestoreAdmin.GetUserCreds]. +message GetUserCredsRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/UserCreds" + } + ]; +} + +// The request for +// [FirestoreAdmin.ListUserCreds][google.firestore.admin.v1.FirestoreAdmin.ListUserCreds]. +message ListUserCredsRequest { + // Required. A parent database name of the form + // `projects/{project_id}/databases/{database_id}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "firestore.googleapis.com/UserCreds" + } + ]; +} + +// The response for +// [FirestoreAdmin.ListUserCreds][google.firestore.admin.v1.FirestoreAdmin.ListUserCreds]. +message ListUserCredsResponse { + // The user creds for the database. + repeated UserCreds user_creds = 1; +} + +// The request for +// [FirestoreAdmin.EnableUserCreds][google.firestore.admin.v1.FirestoreAdmin.EnableUserCreds]. +message EnableUserCredsRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/UserCreds" + } + ]; +} + +// The request for +// [FirestoreAdmin.DisableUserCreds][google.firestore.admin.v1.FirestoreAdmin.DisableUserCreds]. +message DisableUserCredsRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/UserCreds" + } + ]; +} + +// The request for +// [FirestoreAdmin.ResetUserPassword][google.firestore.admin.v1.FirestoreAdmin.ResetUserPassword]. +message ResetUserPasswordRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/UserCreds" + } + ]; +} + +// The request for +// [FirestoreAdmin.DeleteUserCreds][google.firestore.admin.v1.FirestoreAdmin.DeleteUserCreds]. +message DeleteUserCredsRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/UserCreds" + } + ]; +} + +// The request for +// [FirestoreAdmin.CreateBackupSchedule][google.firestore.admin.v1.FirestoreAdmin.CreateBackupSchedule]. +message CreateBackupScheduleRequest { + // Required. The parent database. + // + // Format `projects/{project}/databases/{database}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; + + // Required. The backup schedule to create. + BackupSchedule backup_schedule = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// The request for +// [FirestoreAdmin.GetBackupSchedule][google.firestore.admin.v1.FirestoreAdmin.GetBackupSchedule]. +message GetBackupScheduleRequest { + // Required. The name of the backup schedule. + // + // Format + // `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/BackupSchedule" + } + ]; +} + +// The request for +// [FirestoreAdmin.UpdateBackupSchedule][google.firestore.admin.v1.FirestoreAdmin.UpdateBackupSchedule]. +message UpdateBackupScheduleRequest { + // Required. The backup schedule to update. + BackupSchedule backup_schedule = 1 [(google.api.field_behavior) = REQUIRED]; + + // The list of fields to be updated. + google.protobuf.FieldMask update_mask = 2; +} + +// The request for +// [FirestoreAdmin.ListBackupSchedules][google.firestore.admin.v1.FirestoreAdmin.ListBackupSchedules]. +message ListBackupSchedulesRequest { + // Required. The parent database. + // + // Format is `projects/{project}/databases/{database}`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; +} + +// The response for +// [FirestoreAdmin.ListBackupSchedules][google.firestore.admin.v1.FirestoreAdmin.ListBackupSchedules]. +message ListBackupSchedulesResponse { + // List of all backup schedules. + repeated BackupSchedule backup_schedules = 1; +} + +// The request for [FirestoreAdmin.DeleteBackupSchedules][]. +message DeleteBackupScheduleRequest { + // Required. The name of the backup schedule. + // + // Format + // `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/BackupSchedule" + } + ]; +} + +// The request for +// [FirestoreAdmin.CreateIndex][google.firestore.admin.v1.FirestoreAdmin.CreateIndex]. +message CreateIndexRequest { + // Required. A parent name of the form + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/CollectionGroup" + } + ]; + + // Required. The composite index to create. + Index index = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// The request for +// [FirestoreAdmin.ListIndexes][google.firestore.admin.v1.FirestoreAdmin.ListIndexes]. +message ListIndexesRequest { + // Required. A parent name of the form + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/CollectionGroup" + } + ]; + + // The filter to apply to list results. + string filter = 2; + + // The number of results to return. + int32 page_size = 3; + + // A page token, returned from a previous call to + // [FirestoreAdmin.ListIndexes][google.firestore.admin.v1.FirestoreAdmin.ListIndexes], + // that may be used to get the next page of results. + string page_token = 4; +} + +// The response for +// [FirestoreAdmin.ListIndexes][google.firestore.admin.v1.FirestoreAdmin.ListIndexes]. +message ListIndexesResponse { + // The requested indexes. + repeated Index indexes = 1; + + // A page token that may be used to request another page of results. If blank, + // this is the last page. + string next_page_token = 2; +} + +// The request for +// [FirestoreAdmin.GetIndex][google.firestore.admin.v1.FirestoreAdmin.GetIndex]. +message GetIndexRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "firestore.googleapis.com/Index" } + ]; +} + +// The request for +// [FirestoreAdmin.DeleteIndex][google.firestore.admin.v1.FirestoreAdmin.DeleteIndex]. +message DeleteIndexRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "firestore.googleapis.com/Index" } + ]; +} + +// The request for +// [FirestoreAdmin.UpdateField][google.firestore.admin.v1.FirestoreAdmin.UpdateField]. +message UpdateFieldRequest { + // Required. The field to be updated. + Field field = 1 [(google.api.field_behavior) = REQUIRED]; + + // A mask, relative to the field. If specified, only configuration specified + // by this field_mask will be updated in the field. + google.protobuf.FieldMask update_mask = 2; +} + +// The request for +// [FirestoreAdmin.GetField][google.firestore.admin.v1.FirestoreAdmin.GetField]. +message GetFieldRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "firestore.googleapis.com/Field" } + ]; +} + +// The request for +// [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields]. +message ListFieldsRequest { + // Required. A parent name of the form + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/CollectionGroup" + } + ]; + + // The filter to apply to list results. Currently, + // [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] + // only supports listing fields that have been explicitly overridden. To issue + // this query, call + // [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] + // with a filter that includes `indexConfig.usesAncestorConfig:false` or + // `ttlConfig:*`. + string filter = 2; + + // The number of results to return. + int32 page_size = 3; + + // A page token, returned from a previous call to + // [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields], + // that may be used to get the next page of results. + string page_token = 4; +} + +// The response for +// [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields]. +message ListFieldsResponse { + // The requested fields. + repeated Field fields = 1; + + // A page token that may be used to request another page of results. If blank, + // this is the last page. + string next_page_token = 2; +} + +// The request for +// [FirestoreAdmin.ExportDocuments][google.firestore.admin.v1.FirestoreAdmin.ExportDocuments]. +message ExportDocumentsRequest { + // Required. Database to export. Should be of the form: + // `projects/{project_id}/databases/{database_id}`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; + + // Which collection IDs to export. Unspecified means all collections. Each + // collection ID in this list must be unique. + repeated string collection_ids = 2; + + // The output URI. Currently only supports Google Cloud Storage URIs of the + // form: `gs://BUCKET_NAME[/NAMESPACE_PATH]`, where `BUCKET_NAME` is the name + // of the Google Cloud Storage bucket and `NAMESPACE_PATH` is an optional + // Google Cloud Storage namespace path. When + // choosing a name, be sure to consider Google Cloud Storage naming + // guidelines: https://cloud.google.com/storage/docs/naming. + // If the URI is a bucket (without a namespace path), a prefix will be + // generated based on the start time. + string output_uri_prefix = 3; + + // An empty list represents all namespaces. This is the preferred + // usage for databases that don't use namespaces. + // + // An empty string element represents the default namespace. This should be + // used if the database has data in non-default namespaces, but doesn't want + // to include them. Each namespace in this list must be unique. + repeated string namespace_ids = 4; + + // The timestamp that corresponds to the version of the database to be + // exported. The timestamp must be in the past, rounded to the minute and not + // older than + // [earliestVersionTime][google.firestore.admin.v1.Database.earliest_version_time]. + // If specified, then the exported documents will represent a consistent view + // of the database at the provided time. Otherwise, there are no guarantees + // about the consistency of the exported documents. + google.protobuf.Timestamp snapshot_time = 5; +} + +// The request for +// [FirestoreAdmin.ImportDocuments][google.firestore.admin.v1.FirestoreAdmin.ImportDocuments]. +message ImportDocumentsRequest { + // Required. Database to import into. Should be of the form: + // `projects/{project_id}/databases/{database_id}`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; + + // Which collection IDs to import. Unspecified means all collections included + // in the import. Each collection ID in this list must be unique. + repeated string collection_ids = 2; + + // Location of the exported files. + // This must match the output_uri_prefix of an ExportDocumentsResponse from + // an export that has completed successfully. + // See: + // [google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix][google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix]. + string input_uri_prefix = 3; + + // An empty list represents all namespaces. This is the preferred + // usage for databases that don't use namespaces. + // + // An empty string element represents the default namespace. This should be + // used if the database has data in non-default namespaces, but doesn't want + // to include them. Each namespace in this list must be unique. + repeated string namespace_ids = 4; +} + +// The request for +// [FirestoreAdmin.BulkDeleteDocuments][google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocuments]. +// +// When both collection_ids and namespace_ids are set, only documents satisfying +// both conditions will be deleted. +// +// Requests with namespace_ids and collection_ids both empty will be rejected. +// Please use +// [FirestoreAdmin.DeleteDatabase][google.firestore.admin.v1.FirestoreAdmin.DeleteDatabase] +// instead. +message BulkDeleteDocumentsRequest { + // Required. Database to operate. Should be of the form: + // `projects/{project_id}/databases/{database_id}`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; + + // Optional. IDs of the collection groups to delete. Unspecified means all + // collection groups. + // + // Each collection group in this list must be unique. + repeated string collection_ids = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Namespaces to delete. + // + // An empty list means all namespaces. This is the recommended + // usage for databases that don't use namespaces. + // + // An empty string element represents the default namespace. This should be + // used if the database has data in non-default namespaces, but doesn't want + // to delete from them. + // + // Each namespace in this list must be unique. + repeated string namespace_ids = 3 [(google.api.field_behavior) = OPTIONAL]; +} + +// The response for +// [FirestoreAdmin.BulkDeleteDocuments][google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocuments]. +message BulkDeleteDocumentsResponse {} + +// The request for +// [FirestoreAdmin.GetBackup][google.firestore.admin.v1.FirestoreAdmin.GetBackup]. +message GetBackupRequest { + // Required. Name of the backup to fetch. + // + // Format is `projects/{project}/locations/{location}/backups/{backup}`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Backup" + } + ]; +} + +// The request for +// [FirestoreAdmin.ListBackups][google.firestore.admin.v1.FirestoreAdmin.ListBackups]. +message ListBackupsRequest { + // Required. The location to list backups from. + // + // Format is `projects/{project}/locations/{location}`. + // Use `{location} = '-'` to list backups from all locations for the given + // project. This allows listing backups from a single location or from all + // locations. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Location" + } + ]; + + // An expression that filters the list of returned backups. + // + // A filter expression consists of a field name, a comparison operator, and a + // value for filtering. + // The value must be a string, a number, or a boolean. The comparison operator + // must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + // Colon `:` is the contains operator. Filter rules are not case sensitive. + // + // The following fields in the [Backup][google.firestore.admin.v1.Backup] are + // eligible for filtering: + // + // * `database_uid` (supports `=` only) + string filter = 2; +} + +// The response for +// [FirestoreAdmin.ListBackups][google.firestore.admin.v1.FirestoreAdmin.ListBackups]. +message ListBackupsResponse { + // List of all backups for the project. + repeated Backup backups = 1; + + // List of locations that existing backups were not able to be fetched from. + // + // Instead of failing the entire requests when a single location is + // unreachable, this response returns a partial result set and list of + // locations unable to be reached here. The request can be retried against a + // single location to get a concrete error. + repeated string unreachable = 3; +} + +// The request for +// [FirestoreAdmin.DeleteBackup][google.firestore.admin.v1.FirestoreAdmin.DeleteBackup]. +message DeleteBackupRequest { + // Required. Name of the backup to delete. + // + // format is `projects/{project}/locations/{location}/backups/{backup}`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Backup" + } + ]; +} + +// The request message for +// [FirestoreAdmin.RestoreDatabase][google.firestore.admin.v1.FirestoreAdmin.RestoreDatabase]. +message RestoreDatabaseRequest { + // Required. The project to restore the database in. Format is + // `projects/{project_id}`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "firestore.googleapis.com/Database" + } + ]; + + // Required. The ID to use for the database, which will become the final + // component of the database's resource name. This database ID must not be + // associated with an existing database. + // + // This value should be 4-63 characters. Valid characters are /[a-z][0-9]-/ + // with first character a letter and the last a letter or a number. Must not + // be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + // + // "(default)" database ID is also valid. + string database_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. Backup to restore from. Must be from the same project as the + // parent. + // + // The restored database will be created in the same location as the source + // backup. + // + // Format is: `projects/{project_id}/locations/{location}/backups/{backup}` + string backup = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Backup" + } + ]; + + // Optional. Encryption configuration for the restored database. + // + // If this field is not specified, the restored database will use + // the same encryption configuration as the backup, namely + // [use_source_encryption][google.firestore.admin.v1.Database.EncryptionConfig.use_source_encryption]. + Database.EncryptionConfig encryption_config = 9 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Immutable. Tags to be bound to the restored database. + // + // The tags should be provided in the format of + // `tagKeys/{tag_key_id} -> tagValues/{tag_value_id}`. + map tags = 10 [ + (google.api.field_behavior) = IMMUTABLE, + (google.api.field_behavior) = OPTIONAL + ]; +} + +// The request message for +// [FirestoreAdmin.CloneDatabase][google.firestore.admin.v1.FirestoreAdmin.CloneDatabase]. +message CloneDatabaseRequest { + // Required. The project to clone the database in. Format is + // `projects/{project_id}`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "firestore.googleapis.com/Database" + } + ]; + + // Required. The ID to use for the database, which will become the final + // component of the database's resource name. This database ID must not be + // associated with an existing database. + // + // This value should be 4-63 characters. Valid characters are /[a-z][0-9]-/ + // with first character a letter and the last a letter or a number. Must not + // be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + // + // "(default)" database ID is also valid. + string database_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. Specification of the PITR data to clone from. The source database + // must exist. + // + // The cloned database will be created in the same location as the source + // database. + PitrSnapshot pitr_snapshot = 6 [(google.api.field_behavior) = REQUIRED]; + + // Optional. Encryption configuration for the cloned database. + // + // If this field is not specified, the cloned database will use + // the same encryption configuration as the source database, namely + // [use_source_encryption][google.firestore.admin.v1.Database.EncryptionConfig.use_source_encryption]. + Database.EncryptionConfig encryption_config = 4 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Immutable. Tags to be bound to the cloned database. + // + // The tags should be provided in the format of + // `tagKeys/{tag_key_id} -> tagValues/{tag_value_id}`. + map tags = 5 [ + (google.api.field_behavior) = IMMUTABLE, + (google.api.field_behavior) = OPTIONAL + ]; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/admin/v1/index.proto b/handwritten/firestore/dev/protos/google/firestore/admin/v1/index.proto new file mode 100644 index 00000000000..5dd4dc9fb97 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/admin/v1/index.proto @@ -0,0 +1,243 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "IndexProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; + +// Cloud Firestore indexes enable simple and complex queries against +// documents in a database. +message Index { + option (google.api.resource) = { + type: "firestore.googleapis.com/Index" + pattern: "projects/{project}/databases/{database}/collectionGroups/{collection}/indexes/{index}" + }; + + // Query Scope defines the scope at which a query is run. This is specified on + // a StructuredQuery's `from` field. + enum QueryScope { + // The query scope is unspecified. Not a valid option. + QUERY_SCOPE_UNSPECIFIED = 0; + + // Indexes with a collection query scope specified allow queries + // against a collection that is the child of a specific document, specified + // at query time, and that has the collection ID specified by the index. + COLLECTION = 1; + + // Indexes with a collection group query scope specified allow queries + // against all collections that has the collection ID specified by the + // index. + COLLECTION_GROUP = 2; + + // Include all the collections's ancestor in the index. Only available for + // Datastore Mode databases. + COLLECTION_RECURSIVE = 3; + } + + // API Scope defines the APIs (Firestore Native, or Firestore in + // Datastore Mode) that are supported for queries. + enum ApiScope { + // The index can only be used by the Firestore Native query API. + // This is the default. + ANY_API = 0; + + // The index can only be used by the Firestore in Datastore Mode query API. + DATASTORE_MODE_API = 1; + + // The index can only be used by the MONGODB_COMPATIBLE_API. + MONGODB_COMPATIBLE_API = 2; + } + + // A field in an index. + // The field_path describes which field is indexed, the value_mode describes + // how the field value is indexed. + message IndexField { + // The supported orderings. + enum Order { + // The ordering is unspecified. Not a valid option. + ORDER_UNSPECIFIED = 0; + + // The field is ordered by ascending field value. + ASCENDING = 1; + + // The field is ordered by descending field value. + DESCENDING = 2; + } + + // The supported array value configurations. + enum ArrayConfig { + // The index does not support additional array queries. + ARRAY_CONFIG_UNSPECIFIED = 0; + + // The index supports array containment queries. + CONTAINS = 1; + } + + // The index configuration to support vector search operations + message VectorConfig { + // An index that stores vectors in a flat data structure, and supports + // exhaustive search. + message FlatIndex {} + + // Required. The vector dimension this configuration applies to. + // + // The resulting index will only include vectors of this dimension, and + // can be used for vector search with the same dimension. + int32 dimension = 1 [(google.api.field_behavior) = REQUIRED]; + + // The type of index used. + oneof type { + // Indicates the vector index is a flat index. + FlatIndex flat = 2; + } + } + + // Can be __name__. + // For single field indexes, this must match the name of the field or may + // be omitted. + string field_path = 1; + + // How the field value is indexed. + oneof value_mode { + // Indicates that this field supports ordering by the specified order or + // comparing using =, !=, <, <=, >, >=. + Order order = 2; + + // Indicates that this field supports operations on `array_value`s. + ArrayConfig array_config = 3; + + // Indicates that this field supports nearest neighbor and distance + // operations on vector. + VectorConfig vector_config = 4; + } + } + + // The state of an index. During index creation, an index will be in the + // `CREATING` state. If the index is created successfully, it will transition + // to the `READY` state. If the index creation encounters a problem, the index + // will transition to the `NEEDS_REPAIR` state. + enum State { + // The state is unspecified. + STATE_UNSPECIFIED = 0; + + // The index is being created. + // There is an active long-running operation for the index. + // The index is updated when writing a document. + // Some index data may exist. + CREATING = 1; + + // The index is ready to be used. + // The index is updated when writing a document. + // The index is fully populated from all stored documents it applies to. + READY = 2; + + // The index was being created, but something went wrong. + // There is no active long-running operation for the index, + // and the most recently finished long-running operation failed. + // The index is not updated when writing a document. + // Some index data may exist. + // Use the google.longrunning.Operations API to determine why the operation + // that last attempted to create this index failed, then re-create the + // index. + NEEDS_REPAIR = 3; + } + + // The density configuration for the index. + enum Density { + // Unspecified. It will use database default setting. This value is input + // only. + DENSITY_UNSPECIFIED = 0; + + // In order for an index entry to be added, the document must + // contain all fields specified in the index. + // + // This is the only allowed value for indexes having ApiScope `ANY_API` and + // `DATASTORE_MODE_API`. + SPARSE_ALL = 1; + + // In order for an index entry to be added, the document must + // contain at least one of the fields specified in the index. + // Non-existent fields are treated as having a NULL value when generating + // index entries. + SPARSE_ANY = 2; + + // An index entry will be added regardless of whether the + // document contains any of the fields specified in the index. + // Non-existent fields are treated as having a NULL value when generating + // index entries. + DENSE = 3; + } + + // Output only. A server defined name for this index. + // The form of this name for composite indexes will be: + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{composite_index_id}` + // For single field indexes, this field will be empty. + string name = 1; + + // Indexes with a collection query scope specified allow queries + // against a collection that is the child of a specific document, specified at + // query time, and that has the same collection ID. + // + // Indexes with a collection group query scope specified allow queries against + // all collections descended from a specific document, specified at query + // time, and that have the same collection ID as this index. + QueryScope query_scope = 2; + + // The API scope supported by this index. + ApiScope api_scope = 5; + + // The fields supported by this index. + // + // For composite indexes, this requires a minimum of 2 and a maximum of 100 + // fields. The last field entry is always for the field path `__name__`. If, + // on creation, `__name__` was not specified as the last field, it will be + // added automatically with the same direction as that of the last field + // defined. If the final field in a composite index is not directional, the + // `__name__` will be ordered ASCENDING (unless explicitly specified). + // + // For single field indexes, this will always be exactly one entry with a + // field path equal to the field path of the associated field. + repeated IndexField fields = 3; + + // Output only. The serving state of the index. + State state = 4; + + // Immutable. The density configuration of the index. + Density density = 6 [(google.api.field_behavior) = IMMUTABLE]; + + // Optional. Whether the index is multikey. By default, the index is not + // multikey. For non-multikey indexes, none of the paths in the index + // definition reach or traverse an array, except via an explicit array index. + // For multikey indexes, at most one of the paths in the index definition + // reach or traverse an array, except via an explicit array index. Violations + // will result in errors. + // + // Note this field only applies to index with MONGODB_COMPATIBLE_API ApiScope. + bool multikey = 7 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The number of shards for the index. + int32 shard_count = 8 [(google.api.field_behavior) = OPTIONAL]; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/admin/v1/location.proto b/handwritten/firestore/dev/protos/google/firestore/admin/v1/location.proto new file mode 100644 index 00000000000..1eaa5df3314 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/admin/v1/location.proto @@ -0,0 +1,30 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "LocationProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; + +// The metadata message for +// [google.cloud.location.Location.metadata][google.cloud.location.Location.metadata]. +message LocationMetadata {} diff --git a/handwritten/firestore/dev/protos/google/firestore/admin/v1/operation.proto b/handwritten/firestore/dev/protos/google/firestore/admin/v1/operation.proto new file mode 100644 index 00000000000..6fa21489f77 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/admin/v1/operation.proto @@ -0,0 +1,325 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/resource.proto"; +import "google/firestore/admin/v1/index.proto"; +import "google/firestore/admin/v1/snapshot.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "OperationProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; + +// Metadata for [google.longrunning.Operation][google.longrunning.Operation] +// results from +// [FirestoreAdmin.CreateIndex][google.firestore.admin.v1.FirestoreAdmin.CreateIndex]. +message IndexOperationMetadata { + // The time this operation started. + google.protobuf.Timestamp start_time = 1; + + // The time this operation completed. Will be unset if operation still in + // progress. + google.protobuf.Timestamp end_time = 2; + + // The index resource that this operation is acting on. For example: + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + string index = 3; + + // The state of the operation. + OperationState state = 4; + + // The progress, in documents, of this operation. + Progress progress_documents = 5; + + // The progress, in bytes, of this operation. + Progress progress_bytes = 6; +} + +// Metadata for [google.longrunning.Operation][google.longrunning.Operation] +// results from +// [FirestoreAdmin.UpdateField][google.firestore.admin.v1.FirestoreAdmin.UpdateField]. +message FieldOperationMetadata { + // Information about an index configuration change. + message IndexConfigDelta { + // Specifies how the index is changing. + enum ChangeType { + // The type of change is not specified or known. + CHANGE_TYPE_UNSPECIFIED = 0; + + // The single field index is being added. + ADD = 1; + + // The single field index is being removed. + REMOVE = 2; + } + + // Specifies how the index is changing. + ChangeType change_type = 1; + + // The index being changed. + Index index = 2; + } + + // Information about a TTL configuration change. + message TtlConfigDelta { + // Specifies how the TTL config is changing. + enum ChangeType { + // The type of change is not specified or known. + CHANGE_TYPE_UNSPECIFIED = 0; + + // The TTL config is being added. + ADD = 1; + + // The TTL config is being removed. + REMOVE = 2; + } + + // Specifies how the TTL configuration is changing. + ChangeType change_type = 1; + } + + // The time this operation started. + google.protobuf.Timestamp start_time = 1; + + // The time this operation completed. Will be unset if operation still in + // progress. + google.protobuf.Timestamp end_time = 2; + + // The field resource that this operation is acting on. For example: + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_path}` + string field = 3; + + // A list of + // [IndexConfigDelta][google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta], + // which describe the intent of this operation. + repeated IndexConfigDelta index_config_deltas = 4; + + // The state of the operation. + OperationState state = 5; + + // The progress, in documents, of this operation. + Progress progress_documents = 6; + + // The progress, in bytes, of this operation. + Progress progress_bytes = 7; + + // Describes the deltas of TTL configuration. + TtlConfigDelta ttl_config_delta = 8; +} + +// Metadata for [google.longrunning.Operation][google.longrunning.Operation] +// results from +// [FirestoreAdmin.ExportDocuments][google.firestore.admin.v1.FirestoreAdmin.ExportDocuments]. +message ExportDocumentsMetadata { + // The time this operation started. + google.protobuf.Timestamp start_time = 1; + + // The time this operation completed. Will be unset if operation still in + // progress. + google.protobuf.Timestamp end_time = 2; + + // The state of the export operation. + OperationState operation_state = 3; + + // The progress, in documents, of this operation. + Progress progress_documents = 4; + + // The progress, in bytes, of this operation. + Progress progress_bytes = 5; + + // Which collection IDs are being exported. + repeated string collection_ids = 6; + + // Where the documents are being exported to. + string output_uri_prefix = 7; + + // Which namespace IDs are being exported. + repeated string namespace_ids = 8; + + // The timestamp that corresponds to the version of the database that is being + // exported. If unspecified, there are no guarantees about the consistency of + // the documents being exported. + google.protobuf.Timestamp snapshot_time = 9; +} + +// Metadata for [google.longrunning.Operation][google.longrunning.Operation] +// results from +// [FirestoreAdmin.ImportDocuments][google.firestore.admin.v1.FirestoreAdmin.ImportDocuments]. +message ImportDocumentsMetadata { + // The time this operation started. + google.protobuf.Timestamp start_time = 1; + + // The time this operation completed. Will be unset if operation still in + // progress. + google.protobuf.Timestamp end_time = 2; + + // The state of the import operation. + OperationState operation_state = 3; + + // The progress, in documents, of this operation. + Progress progress_documents = 4; + + // The progress, in bytes, of this operation. + Progress progress_bytes = 5; + + // Which collection IDs are being imported. + repeated string collection_ids = 6; + + // The location of the documents being imported. + string input_uri_prefix = 7; + + // Which namespace IDs are being imported. + repeated string namespace_ids = 8; +} + +// Metadata for [google.longrunning.Operation][google.longrunning.Operation] +// results from +// [FirestoreAdmin.BulkDeleteDocuments][google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocuments]. +message BulkDeleteDocumentsMetadata { + // The time this operation started. + google.protobuf.Timestamp start_time = 1; + + // The time this operation completed. Will be unset if operation still in + // progress. + google.protobuf.Timestamp end_time = 2; + + // The state of the operation. + OperationState operation_state = 3; + + // The progress, in documents, of this operation. + Progress progress_documents = 4; + + // The progress, in bytes, of this operation. + Progress progress_bytes = 5; + + // The IDs of the collection groups that are being deleted. + repeated string collection_ids = 6; + + // Which namespace IDs are being deleted. + repeated string namespace_ids = 7; + + // The timestamp that corresponds to the version of the database that is being + // read to get the list of documents to delete. This time can also be used as + // the timestamp of PITR in case of disaster recovery (subject to PITR window + // limit). + google.protobuf.Timestamp snapshot_time = 8; +} + +// Returned in the [google.longrunning.Operation][google.longrunning.Operation] +// response field. +message ExportDocumentsResponse { + // Location of the output files. This can be used to begin an import + // into Cloud Firestore (this project or another project) after the operation + // completes successfully. + string output_uri_prefix = 1; +} + +// Metadata for the [long-running operation][google.longrunning.Operation] from +// the [RestoreDatabase][google.firestore.admin.v1.RestoreDatabase] request. +message RestoreDatabaseMetadata { + // The time the restore was started. + google.protobuf.Timestamp start_time = 1; + + // The time the restore finished, unset for ongoing restores. + google.protobuf.Timestamp end_time = 2; + + // The operation state of the restore. + OperationState operation_state = 3; + + // The name of the database being restored to. + string database = 4 [(google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + }]; + + // The name of the backup restoring from. + string backup = 5 [(google.api.resource_reference) = { + type: "firestore.googleapis.com/Backup" + }]; + + // How far along the restore is as an estimated percentage of remaining time. + Progress progress_percentage = 8; +} + +// Metadata for the [long-running operation][google.longrunning.Operation] from +// the [CloneDatabase][google.firestore.admin.v1.CloneDatabase] request. +message CloneDatabaseMetadata { + // The time the clone was started. + google.protobuf.Timestamp start_time = 1; + + // The time the clone finished, unset for ongoing clones. + google.protobuf.Timestamp end_time = 2; + + // The operation state of the clone. + OperationState operation_state = 3; + + // The name of the database being cloned to. + string database = 4 [(google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + }]; + + // The snapshot from which this database was cloned. + PitrSnapshot pitr_snapshot = 7; + + // How far along the clone is as an estimated percentage of remaining time. + Progress progress_percentage = 6; +} + +// Describes the progress of the operation. +// Unit of work is generic and must be interpreted based on where +// [Progress][google.firestore.admin.v1.Progress] is used. +message Progress { + // The amount of work estimated. + int64 estimated_work = 1; + + // The amount of work completed. + int64 completed_work = 2; +} + +// Describes the state of the operation. +enum OperationState { + // Unspecified. + OPERATION_STATE_UNSPECIFIED = 0; + + // Request is being prepared for processing. + INITIALIZING = 1; + + // Request is actively being processed. + PROCESSING = 2; + + // Request is in the process of being cancelled after user called + // google.longrunning.Operations.CancelOperation on the operation. + CANCELLING = 3; + + // Request has been processed and is in its finalization stage. + FINALIZING = 4; + + // Request has completed successfully. + SUCCESSFUL = 5; + + // Request has finished being processed, but encountered an error. + FAILED = 6; + + // Request has finished being cancelled after user called + // google.longrunning.Operations.CancelOperation. + CANCELLED = 7; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/admin/v1/schedule.proto b/handwritten/firestore/dev/protos/google/firestore/admin/v1/schedule.proto new file mode 100644 index 00000000000..0f1798247e4 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/admin/v1/schedule.proto @@ -0,0 +1,95 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/timestamp.proto"; +import "google/type/dayofweek.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "ScheduleProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; + +// A backup schedule for a Cloud Firestore Database. +// +// This resource is owned by the database it is backing up, and is deleted along +// with the database. The actual backups are not though. +message BackupSchedule { + option (google.api.resource) = { + type: "firestore.googleapis.com/BackupSchedule" + pattern: "projects/{project}/databases/{database}/backupSchedules/{backup_schedule}" + }; + + // Output only. The unique backup schedule identifier across all locations and + // databases for the given project. + // + // This will be auto-assigned. + // + // Format is + // `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + string name = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The timestamp at which this backup schedule was created and + // effective since. + // + // No backups will be created for this schedule before this time. + google.protobuf.Timestamp create_time = 3 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The timestamp at which this backup schedule was most recently + // updated. When a backup schedule is first created, this is the same as + // create_time. + google.protobuf.Timestamp update_time = 10 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // At what relative time in the future, compared to its creation time, + // the backup should be deleted, e.g. keep backups for 7 days. + // + // The maximum supported retention period is 14 weeks. + google.protobuf.Duration retention = 6; + + // A oneof field to represent when backups will be taken. + oneof recurrence { + // For a schedule that runs daily. + DailyRecurrence daily_recurrence = 7; + + // For a schedule that runs weekly on a specific day. + WeeklyRecurrence weekly_recurrence = 8; + } +} + +// Represents a recurring schedule that runs every day. +// +// The time zone is UTC. +message DailyRecurrence {} + +// Represents a recurring schedule that runs on a specified day of the week. +// +// The time zone is UTC. +message WeeklyRecurrence { + // The day of week to run. + // + // DAY_OF_WEEK_UNSPECIFIED is not allowed. + google.type.DayOfWeek day = 2; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/admin/v1/snapshot.proto b/handwritten/firestore/dev/protos/google/firestore/admin/v1/snapshot.proto new file mode 100644 index 00000000000..895bed4dab6 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/admin/v1/snapshot.proto @@ -0,0 +1,53 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "PitrSnapshotProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; + +// A consistent snapshot of a database at a specific point in time. +// A PITR (Point-in-time recovery) snapshot with previous versions of a +// database's data is available for every minute up to the associated database's +// data retention period. If the PITR feature is enabled, the retention period +// is 7 days; otherwise, it is one hour. +message PitrSnapshot { + // Required. The name of the database that this was a snapshot of. Format: + // `projects/{project}/databases/{database}`. + string database = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; + + // Output only. Public UUID of the database the snapshot was associated with. + bytes database_uid = 2 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Required. Snapshot time of the database. + google.protobuf.Timestamp snapshot_time = 3 + [(google.api.field_behavior) = REQUIRED]; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/admin/v1/user_creds.proto b/handwritten/firestore/dev/protos/google/firestore/admin/v1/user_creds.proto new file mode 100644 index 00000000000..ae4db3e4615 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/admin/v1/user_creds.proto @@ -0,0 +1,86 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "UserCredsProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; + +// A Cloud Firestore User Creds. +message UserCreds { + option (google.api.resource) = { + type: "firestore.googleapis.com/UserCreds" + pattern: "projects/{project}/databases/{database}/userCreds/{user_creds}" + plural: "userCreds" + singular: "userCreds" + }; + + // The state of the user creds (ENABLED or DISABLED). + enum State { + // The default value. Should not be used. + STATE_UNSPECIFIED = 0; + + // The user creds are enabled. + ENABLED = 1; + + // The user creds are disabled. + DISABLED = 2; + } + + // Describes a Resource Identity principal. + message ResourceIdentity { + // Output only. Principal identifier string. + // See: https://cloud.google.com/iam/docs/principal-identifiers + string principal = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + } + + // Identifier. The resource name of the UserCreds. + // Format: + // `projects/{project}/databases/{database}/userCreds/{user_creds}` + string name = 1 [(google.api.field_behavior) = IDENTIFIER]; + + // Output only. The time the user creds were created. + google.protobuf.Timestamp create_time = 2 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The time the user creds were last updated. + google.protobuf.Timestamp update_time = 3 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Whether the user creds are enabled or disabled. Defaults to + // ENABLED on creation. + State state = 4 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The plaintext server-generated password for the user creds. + // Only populated in responses for CreateUserCreds and ResetUserPassword. + string secure_password = 5 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Identity associated with this User Creds. + oneof UserCredsIdentity { + // Resource Identity descriptor. + ResourceIdentity resource_identity = 6; + } +} diff --git a/handwritten/firestore/dev/protos/google/firestore/v1/aggregation_result.proto b/handwritten/firestore/dev/protos/google/firestore/v1/aggregation_result.proto new file mode 100644 index 00000000000..26c42b9be3e --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/v1/aggregation_result.proto @@ -0,0 +1,43 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/firestore/v1/document.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "AggregationResultProto"; +option java_package = "com.google.firestore.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// 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. +message AggregationResult { + // 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. + map aggregate_fields = 2; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/v1/bloom_filter.proto b/handwritten/firestore/dev/protos/google/firestore/v1/bloom_filter.proto new file mode 100644 index 00000000000..e697ede6f78 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/v1/bloom_filter.proto @@ -0,0 +1,73 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "BloomFilterProto"; +option java_package = "com.google.firestore.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// 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`. +message BitSequence { + // The bytes that encode the bit sequence. + // May have a length of zero. + bytes bitmap = 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. + int32 padding = 2; +} + +// 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. +message BloomFilter { + // The bloom filter data. + BitSequence bits = 1; + + // The number of hashes used by the algorithm. + int32 hash_count = 2; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/v1/common.proto b/handwritten/firestore/dev/protos/google/firestore/v1/common.proto new file mode 100644 index 00000000000..150e06e8b2d --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/v1/common.proto @@ -0,0 +1,90 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "CommonProto"; +option java_package = "com.google.firestore.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// 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]. +message DocumentMask { + // The list of field paths in the mask. See + // [Document.fields][google.firestore.v1.Document.fields] for a field path + // syntax reference. + repeated string field_paths = 1; +} + +// A precondition on a document, used for conditional operations. +message Precondition { + // The type of precondition. + oneof condition_type { + // When set to `true`, the target document must exist. + // When set to `false`, the target document must not exist. + bool exists = 1; + + // When set, the target document must exist and have been last updated at + // that time. Timestamp must be microsecond aligned. + google.protobuf.Timestamp update_time = 2; + } +} + +// Options for creating a new transaction. +message TransactionOptions { + // Options for a transaction that can be used to read and write documents. + // + // Firestore does not allow 3rd party auth requests to create read-write. + // transactions. + message ReadWrite { + // An optional transaction to retry. + bytes retry_transaction = 1; + } + + // Options for a transaction that can only be used to read documents. + message ReadOnly { + // The consistency mode for this transaction. If not set, defaults to strong + // consistency. + oneof consistency_selector { + // 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. + google.protobuf.Timestamp read_time = 2; + } + } + + // The mode of the transaction. + oneof mode { + // The transaction can only be used for read operations. + ReadOnly read_only = 2; + + // The transaction can be used for both read and write operations. + ReadWrite read_write = 3; + } +} diff --git a/handwritten/firestore/dev/protos/google/firestore/v1/document.proto b/handwritten/firestore/dev/protos/google/firestore/v1/document.proto new file mode 100644 index 00000000000..1eec17bf5d5 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/v1/document.proto @@ -0,0 +1,240 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/api/field_behavior.proto"; +import "google/protobuf/struct.proto"; +import "google/protobuf/timestamp.proto"; +import "google/type/latlng.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "DocumentProto"; +option java_package = "com.google.firestore.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// A Firestore document. +// +// Must not exceed 1 MiB - 4 bytes. +message Document { + // The resource name of the document, for example + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string name = 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 ``. + map fields = 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. + google.protobuf.Timestamp create_time = 3; + + // 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. + google.protobuf.Timestamp update_time = 4; +} + +// A message that can hold any of the supported value types. +message Value { + // Must have a value set. + oneof value_type { + // A null value. + google.protobuf.NullValue null_value = 11; + + // A boolean value. + bool boolean_value = 1; + + // An integer value. + int64 integer_value = 2; + + // A double value. + double double_value = 3; + + // A timestamp value. + // + // Precise only to microseconds. When stored, any additional precision is + // rounded down. + google.protobuf.Timestamp timestamp_value = 10; + + // 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. + string string_value = 17; + + // A bytes value. + // + // Must not exceed 1 MiB - 89 bytes. + // Only the first 1,500 bytes are considered by queries. + bytes bytes_value = 18; + + // A reference to a document. For example: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string reference_value = 5; + + // A geo point value representing a point on the surface of Earth. + google.type.LatLng geo_point_value = 8; + + // An array value. + // + // Cannot directly contain another array value, though can contain a + // map which contains another array. + ArrayValue array_value = 9; + + // A map value. + MapValue map_value = 6; + + // 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. + string field_reference_value = 19; + + // A value that represents an unevaluated expression. + // + // **Requires:** + // + // * Not allowed to be used when writing documents. + Function function_value = 20; + + // A value that represents an unevaluated pipeline. + // + // **Requires:** + // + // * Not allowed to be used when writing documents. + Pipeline pipeline_value = 21; + } +} + +// An array value. +message ArrayValue { + // Values in the array. + repeated Value values = 1; +} + +// A map value. +message MapValue { + // 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. + map fields = 1; +} + +// 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%" } +// ``` +message Function { + // Required. The name of the function to evaluate. + // + // **Requires:** + // + // * must be in snake case (lower case with underscore separator). + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // Optional. Ordered list of arguments the given function expects. + repeated Value args = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Optional named arguments that certain functions may support. + map options = 3 [(google.api.field_behavior) = OPTIONAL]; +} + +// A Firestore query represented as an ordered list of operations / stages. +message Pipeline { + // 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. + message Stage { + // Required. The name of the stage to evaluate. + // + // **Requires:** + // + // * must be in snake case (lower case with underscore separator). + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // Optional. Ordered list of arguments the given stage expects. + repeated Value args = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Optional named arguments that certain functions may support. + map options = 3 [(google.api.field_behavior) = OPTIONAL]; + } + + // Required. Ordered list of stages to evaluate. + repeated Stage stages = 1 [(google.api.field_behavior) = REQUIRED]; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/v1/explain_stats.proto b/handwritten/firestore/dev/protos/google/firestore/v1/explain_stats.proto new file mode 100644 index 00000000000..3ec7dbf71e8 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/v1/explain_stats.proto @@ -0,0 +1,41 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/protobuf/any.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "ExplainStatsProto"; +option java_package = "com.google.firestore.v1"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// Specification of Firestore Explain Stats fields. + +// Pipeline explain stats. +// +// Depending on the explain options in the original request, this can contain +// the optimized plan and / or execution stats. +message ExplainStats { + // 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`. + google.protobuf.Any data = 1; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/v1/firestore.proto b/handwritten/firestore/dev/protos/google/firestore/v1/firestore.proto new file mode 100644 index 00000000000..245d39d70dc --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/v1/firestore.proto @@ -0,0 +1,1229 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/routing.proto"; +import "google/firestore/v1/aggregation_result.proto"; +import "google/firestore/v1/common.proto"; +import "google/firestore/v1/document.proto"; +import "google/firestore/v1/explain_stats.proto"; +import "google/firestore/v1/pipeline.proto"; +import "google/firestore/v1/query.proto"; +import "google/firestore/v1/query_profile.proto"; +import "google/firestore/v1/write.proto"; +import "google/protobuf/empty.proto"; +import "google/protobuf/timestamp.proto"; +import "google/protobuf/wrappers.proto"; +import "google/rpc/status.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "FirestoreProto"; +option java_package = "com.google.firestore.v1"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// Specification of the Firestore API. + +// 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. +service Firestore { + option (google.api.default_host) = "firestore.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/datastore"; + + // Gets a single document. + rpc GetDocument(GetDocumentRequest) returns (Document) { + option (google.api.http) = { + get: "/v1/{name=projects/*/databases/*/documents/*/**}" + }; + } + + // Lists documents. + rpc ListDocuments(ListDocumentsRequest) returns (ListDocumentsResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}" + additional_bindings { + get: "/v1/{parent=projects/*/databases/*/documents}/{collection_id}" + } + }; + } + + // Updates or inserts a document. + rpc UpdateDocument(UpdateDocumentRequest) returns (Document) { + option (google.api.http) = { + patch: "/v1/{document.name=projects/*/databases/*/documents/*/**}" + body: "document" + }; + option (google.api.method_signature) = "document,update_mask"; + } + + // Deletes a document. + rpc DeleteDocument(DeleteDocumentRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/databases/*/documents/*/**}" + }; + option (google.api.method_signature) = "name"; + } + + // Gets multiple documents. + // + // Documents returned by this method are not guaranteed to be returned in the + // same order that they were requested. + rpc BatchGetDocuments(BatchGetDocumentsRequest) + returns (stream BatchGetDocumentsResponse) { + option (google.api.http) = { + post: "/v1/{database=projects/*/databases/*}/documents:batchGet" + body: "*" + }; + } + + // Starts a new transaction. + rpc BeginTransaction(BeginTransactionRequest) + returns (BeginTransactionResponse) { + option (google.api.http) = { + post: "/v1/{database=projects/*/databases/*}/documents:beginTransaction" + body: "*" + }; + option (google.api.method_signature) = "database"; + } + + // Commits a transaction, while optionally updating documents. + rpc Commit(CommitRequest) returns (CommitResponse) { + option (google.api.http) = { + post: "/v1/{database=projects/*/databases/*}/documents:commit" + body: "*" + }; + option (google.api.method_signature) = "database,writes"; + } + + // Rolls back a transaction. + rpc Rollback(RollbackRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + post: "/v1/{database=projects/*/databases/*}/documents:rollback" + body: "*" + }; + option (google.api.method_signature) = "database,transaction"; + } + + // Runs a query. + rpc RunQuery(RunQueryRequest) returns (stream RunQueryResponse) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/databases/*/documents}:runQuery" + body: "*" + additional_bindings { + post: "/v1/{parent=projects/*/databases/*/documents/*/**}:runQuery" + body: "*" + } + }; + } + + // Executes a pipeline query. + rpc ExecutePipeline(ExecutePipelineRequest) + returns (stream ExecutePipelineResponse) { + option (google.api.http) = { + post: "/v1/{database=projects/*/databases/*}/documents:executePipeline" + body: "*" + }; + option (google.api.routing) = { + routing_parameters { + field: "database" + path_template: "projects/{project_id=*}/**" + } + routing_parameters { + field: "database" + path_template: "projects/*/databases/{database_id=*}/**" + } + }; + } + + // 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 ); + // ``` + rpc RunAggregationQuery(RunAggregationQueryRequest) + returns (stream RunAggregationQueryResponse) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/databases/*/documents}:runAggregationQuery" + body: "*" + additional_bindings { + post: "/v1/{parent=projects/*/databases/*/documents/*/**}:runAggregationQuery" + body: "*" + } + }; + } + + // 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. + rpc PartitionQuery(PartitionQueryRequest) returns (PartitionQueryResponse) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/databases/*/documents}:partitionQuery" + body: "*" + additional_bindings { + post: "/v1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery" + body: "*" + } + }; + } + + // Streams batches of document updates and deletes, in order. This method is + // only available via gRPC or WebChannel (not REST). + rpc Write(stream WriteRequest) returns (stream WriteResponse) { + option (google.api.http) = { + post: "/v1/{database=projects/*/databases/*}/documents:write" + body: "*" + }; + } + + // Listens to changes. This method is only available via gRPC or WebChannel + // (not REST). + rpc Listen(stream ListenRequest) returns (stream ListenResponse) { + option (google.api.http) = { + post: "/v1/{database=projects/*/databases/*}/documents:listen" + body: "*" + }; + } + + // Lists all the collection IDs underneath a document. + rpc ListCollectionIds(ListCollectionIdsRequest) + returns (ListCollectionIdsResponse) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/databases/*/documents}:listCollectionIds" + body: "*" + additional_bindings { + post: "/v1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds" + body: "*" + } + }; + option (google.api.method_signature) = "parent"; + } + + // 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. + rpc BatchWrite(BatchWriteRequest) returns (BatchWriteResponse) { + option (google.api.http) = { + post: "/v1/{database=projects/*/databases/*}/documents:batchWrite" + body: "*" + }; + } + + // Creates a new document. + rpc CreateDocument(CreateDocumentRequest) returns (Document) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/databases/*/documents/**}/{collection_id}" + body: "document" + }; + } +} + +// The request for +// [Firestore.GetDocument][google.firestore.v1.Firestore.GetDocument]. +message GetDocumentRequest { + // Required. The resource name of the Document to get. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // 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. + DocumentMask mask = 2; + + // The consistency mode for this transaction. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Reads the document in a transaction. + bytes transaction = 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. + google.protobuf.Timestamp read_time = 5; + } +} + +// The request for +// [Firestore.ListDocuments][google.firestore.v1.Firestore.ListDocuments]. +message ListDocumentsRequest { + // 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` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // 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`. + string collection_id = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The maximum number of documents to return in a single response. + // + // Firestore may return fewer than this value. + int32 page_size = 3 [(google.api.field_behavior) = OPTIONAL]; + + // 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. + string page_token = 4 [(google.api.field_behavior) = OPTIONAL]; + + // 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`. + string order_by = 6 [(google.api.field_behavior) = OPTIONAL]; + + // 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. + DocumentMask mask = 7 [(google.api.field_behavior) = OPTIONAL]; + + // The consistency mode for this transaction. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Perform the read as part of an already active transaction. + bytes transaction = 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. + google.protobuf.Timestamp read_time = 10; + } + + // 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`. + bool show_missing = 12; +} + +// The response for +// [Firestore.ListDocuments][google.firestore.v1.Firestore.ListDocuments]. +message ListDocumentsResponse { + // The Documents found. + repeated Document documents = 1; + + // A token to retrieve the next page of documents. + // + // If this field is omitted, there are no subsequent pages. + string next_page_token = 2; +} + +// The request for +// [Firestore.CreateDocument][google.firestore.v1.Firestore.CreateDocument]. +message CreateDocumentRequest { + // Required. The parent resource. For example: + // `projects/{project_id}/databases/{database_id}/documents` or + // `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The collection ID, relative to `parent`, to list. For example: + // `chatrooms`. + string collection_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // The client-assigned document ID to use for this document. + // + // Optional. If not specified, an ID will be assigned by the service. + string document_id = 3; + + // Required. The document to create. `name` must not be set. + Document document = 4 [(google.api.field_behavior) = REQUIRED]; + + // 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. + DocumentMask mask = 5; +} + +// The request for +// [Firestore.UpdateDocument][google.firestore.v1.Firestore.UpdateDocument]. +message UpdateDocumentRequest { + // Required. The updated document. + // Creates the document if it does not already exist. + Document document = 1 [(google.api.field_behavior) = REQUIRED]; + + // 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. + DocumentMask update_mask = 2; + + // 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. + DocumentMask mask = 3; + + // An optional precondition on the document. + // The request will fail if this is set and not met by the target document. + Precondition current_document = 4; +} + +// The request for +// [Firestore.DeleteDocument][google.firestore.v1.Firestore.DeleteDocument]. +message DeleteDocumentRequest { + // Required. The resource name of the Document to delete. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // An optional precondition on the document. + // The request will fail if this is set and not met by the target document. + Precondition current_document = 2; +} + +// The request for +// [Firestore.BatchGetDocuments][google.firestore.v1.Firestore.BatchGetDocuments]. +message BatchGetDocumentsRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // 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. + repeated string documents = 2; + + // 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. + DocumentMask mask = 3; + + // The consistency mode for this transaction. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Reads documents in a transaction. + bytes transaction = 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. + TransactionOptions new_transaction = 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. + google.protobuf.Timestamp read_time = 7; + } +} + +// The streamed response for +// [Firestore.BatchGetDocuments][google.firestore.v1.Firestore.BatchGetDocuments]. +message BatchGetDocumentsResponse { + // A single result. + // This can be empty if the server is just returning a transaction. + oneof result { + // A document that was requested. + Document found = 1; + + // A document name that was requested but does not exist. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string missing = 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. + bytes transaction = 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. + google.protobuf.Timestamp read_time = 4; +} + +// The request for +// [Firestore.BeginTransaction][google.firestore.v1.Firestore.BeginTransaction]. +message BeginTransactionRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The options for the transaction. + // Defaults to a read-write transaction. + TransactionOptions options = 2; +} + +// The response for +// [Firestore.BeginTransaction][google.firestore.v1.Firestore.BeginTransaction]. +message BeginTransactionResponse { + // The transaction that was started. + bytes transaction = 1; +} + +// The request for [Firestore.Commit][google.firestore.v1.Firestore.Commit]. +message CommitRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The writes to apply. + // + // Always executed atomically and in order. + repeated Write writes = 2; + + // If set, applies all writes in this transaction, and commits it. + bytes transaction = 3; +} + +// The response for [Firestore.Commit][google.firestore.v1.Firestore.Commit]. +message CommitResponse { + // The result of applying the writes. + // + // This i-th write result corresponds to the i-th write in the + // request. + repeated WriteResult write_results = 1; + + // 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. + google.protobuf.Timestamp commit_time = 2; +} + +// The request for [Firestore.Rollback][google.firestore.v1.Firestore.Rollback]. +message RollbackRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The transaction to roll back. + bytes transaction = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// The request for [Firestore.RunQuery][google.firestore.v1.Firestore.RunQuery]. +message RunQueryRequest { + // 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` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // The query to run. + oneof query_type { + // A structured query. + StructuredQuery structured_query = 2; + } + + // The consistency mode for this transaction. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Run the query within an already active transaction. + // + // The value here is the opaque transaction ID to execute the query in. + bytes transaction = 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. + TransactionOptions new_transaction = 6; + + // 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. + google.protobuf.Timestamp read_time = 7; + } + + // Optional. Explain options for the query. If set, additional query + // statistics will be returned. If not, only query results will be returned. + ExplainOptions explain_options = 10 [(google.api.field_behavior) = OPTIONAL]; +} + +// The response for +// [Firestore.RunQuery][google.firestore.v1.Firestore.RunQuery]. +message RunQueryResponse { + // 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. + bytes transaction = 2; + + // A query result, not set when reporting partial progress. + Document document = 1; + + // 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. + google.protobuf.Timestamp read_time = 3; + + // The number of results that have been skipped due to an offset between + // the last response and the current response. + int32 skipped_results = 4; + + // 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. + oneof continuation_selector { + // If present, Firestore has completely finished the request and no more + // documents will be returned. + bool done = 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 explain_metrics = 11; +} + +// The request for +// [Firestore.ExecutePipeline][google.firestore.v1.Firestore.ExecutePipeline]. +message ExecutePipelineRequest { + // Required. Database identifier, in the form + // `projects/{project}/databases/{database}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + oneof pipeline_type { + // A pipelined operation. + StructuredPipeline structured_pipeline = 2; + } + + // Optional consistency arguments, defaults to strong consistency. + oneof consistency_selector { + // Run the query within an already active transaction. + // + // The value here is the opaque transaction ID to execute the query in. + bytes transaction = 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. + TransactionOptions new_transaction = 6; + + // 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. + google.protobuf.Timestamp read_time = 7; + } +} + +// The response for [Firestore.Execute][]. +message ExecutePipelineResponse { + // 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][]. + bytes transaction = 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]. + repeated Document results = 2; + + // 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. + google.protobuf.Timestamp execution_time = 3; + + // 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 explain_stats = 4; +} + +// The request for +// [Firestore.RunAggregationQuery][google.firestore.v1.Firestore.RunAggregationQuery]. +message RunAggregationQueryRequest { + // 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` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // The query to run. + oneof query_type { + // An aggregation query. + StructuredAggregationQuery structured_aggregation_query = 2; + } + + // The consistency mode for the query, defaults to strong consistency. + oneof consistency_selector { + // Run the aggregation within an already active transaction. + // + // The value here is the opaque transaction ID to execute the query in. + bytes transaction = 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. + TransactionOptions new_transaction = 5; + + // 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. + google.protobuf.Timestamp read_time = 6; + } + + // Optional. Explain options for the query. If set, additional query + // statistics will be returned. If not, only query results will be returned. + ExplainOptions explain_options = 8 [(google.api.field_behavior) = OPTIONAL]; +} + +// The response for +// [Firestore.RunAggregationQuery][google.firestore.v1.Firestore.RunAggregationQuery]. +message RunAggregationQueryResponse { + // A single aggregation result. + // + // Not present when reporting partial progress. + AggregationResult result = 1; + + // 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. + bytes transaction = 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. + google.protobuf.Timestamp read_time = 3; + + // 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 explain_metrics = 10; +} + +// The request for +// [Firestore.PartitionQuery][google.firestore.v1.Firestore.PartitionQuery]. +message PartitionQueryRequest { + // 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. + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // The query to partition. + oneof query_type { + // 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 structured_query = 2; + } + + // 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. + int64 partition_count = 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 + string page_token = 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`. + int32 page_size = 5; + + // The consistency mode for this request. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // 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. + google.protobuf.Timestamp read_time = 6; + } +} + +// The response for +// [Firestore.PartitionQuery][google.firestore.v1.Firestore.PartitionQuery]. +message PartitionQueryResponse { + // 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. + repeated Cursor partitions = 1; + + // 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. + string next_page_token = 2; +} + +// 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. +message WriteRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + // This is only required in the first message. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // 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. + string stream_id = 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. + repeated Write writes = 3; + + // 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. + bytes stream_token = 4; + + // Labels associated with this write request. + map labels = 5; +} + +// The response for [Firestore.Write][google.firestore.v1.Firestore.Write]. +message WriteResponse { + // The ID of the stream. + // Only set on the first message, when a new stream was created. + string stream_id = 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. + bytes stream_token = 2; + + // The result of applying the writes. + // + // This i-th write result corresponds to the i-th write in the + // request. + repeated WriteResult write_results = 3; + + // 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. + google.protobuf.Timestamp commit_time = 4; +} + +// A request for [Firestore.Listen][google.firestore.v1.Firestore.Listen] +message ListenRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The supported target changes. + oneof target_change { + // A target to add to this stream. + Target add_target = 2; + + // The ID of a target to remove from this stream. + int32 remove_target = 3; + } + + // Labels associated with this target change. + map labels = 4; +} + +// The response for [Firestore.Listen][google.firestore.v1.Firestore.Listen]. +message ListenResponse { + // The supported responses. + oneof response_type { + // Targets have changed. + TargetChange target_change = 2; + + // A [Document][google.firestore.v1.Document] has changed. + DocumentChange document_change = 3; + + // A [Document][google.firestore.v1.Document] has been deleted. + DocumentDelete document_delete = 4; + + // A [Document][google.firestore.v1.Document] has been removed from a target + // (because it is no longer relevant to that target). + DocumentRemove document_remove = 6; + + // 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. + ExistenceFilter filter = 5; + } +} + +// A specification of a set of documents to listen to. +message Target { + // A target specified by a set of documents names. + message DocumentsTarget { + // 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. + repeated string documents = 2; + } + + // A target specified by a query. + message QueryTarget { + // 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` + string parent = 1; + + // The query to run. + oneof query_type { + // A structured query. + StructuredQuery structured_query = 2; + } + } + + // The type of target to listen to. + oneof target_type { + // A target specified by a query. + QueryTarget query = 2; + + // A target specified by a set of document names. + DocumentsTarget documents = 3; + } + + // 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. + oneof resume_type { + // 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. + bytes resume_token = 4; + + // Start listening after a specific `read_time`. + // + // The client must know the state of matching documents at this time. + google.protobuf.Timestamp read_time = 11; + } + + // 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. + int32 target_id = 5; + + // If the target should be removed once it is current and consistent. + bool once = 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. + google.protobuf.Int32Value expected_count = 12; +} + +// Targets being watched have changed. +message TargetChange { + // The type of change. + enum TargetChangeType { + // No change has occurred. Used only to send an updated `resume_token`. + NO_CHANGE = 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 change that occurred. + TargetChangeType target_change_type = 1; + + // 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. + repeated int32 target_ids = 2; + + // The error that resulted in this change, if applicable. + google.rpc.Status cause = 3; + + // 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. + bytes resume_token = 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. + google.protobuf.Timestamp read_time = 6; +} + +// The request for +// [Firestore.ListCollectionIds][google.firestore.v1.Firestore.ListCollectionIds]. +message ListCollectionIdsRequest { + // 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` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // The maximum number of results to return. + int32 page_size = 2; + + // A page token. Must be a value from + // [ListCollectionIdsResponse][google.firestore.v1.ListCollectionIdsResponse]. + string page_token = 3; + + // The consistency mode for this request. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // 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. + google.protobuf.Timestamp read_time = 4; + } +} + +// The response from +// [Firestore.ListCollectionIds][google.firestore.v1.Firestore.ListCollectionIds]. +message ListCollectionIdsResponse { + // The collection ids. + repeated string collection_ids = 1; + + // A page token that may be used to continue the list. + string next_page_token = 2; +} + +// The request for +// [Firestore.BatchWrite][google.firestore.v1.Firestore.BatchWrite]. +message BatchWriteRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // 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. + repeated Write writes = 2; + + // Labels associated with this batch write. + map labels = 3; +} + +// The response from +// [Firestore.BatchWrite][google.firestore.v1.Firestore.BatchWrite]. +message BatchWriteResponse { + // The result of applying the writes. + // + // This i-th write result corresponds to the i-th write in the + // request. + repeated WriteResult write_results = 1; + + // The status of applying the writes. + // + // This i-th write status corresponds to the i-th write in the + // request. + repeated google.rpc.Status status = 2; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/v1/pipeline.proto b/handwritten/firestore/dev/protos/google/firestore/v1/pipeline.proto new file mode 100644 index 00000000000..484b12d00bd --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/v1/pipeline.proto @@ -0,0 +1,43 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/api/field_behavior.proto"; +import "google/firestore/v1/document.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "PipelineProto"; +option java_package = "com.google.firestore.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// 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. +message StructuredPipeline { + // Required. The pipeline query to execute. + Pipeline pipeline = 1 [(google.api.field_behavior) = REQUIRED]; + + // Optional. Optional query-level arguments. + // + map options = 2 [(google.api.field_behavior) = OPTIONAL]; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/v1/query.proto b/handwritten/firestore/dev/protos/google/firestore/v1/query.proto new file mode 100644 index 00000000000..492f67af7e5 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/v1/query.proto @@ -0,0 +1,590 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/api/field_behavior.proto"; +import "google/firestore/v1/document.proto"; +import "google/protobuf/wrappers.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "QueryProto"; +option java_package = "com.google.firestore.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// 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 +message StructuredQuery { + // A selection of a collection, such as `messages as m1`. + message CollectionSelector { + // The collection ID. + // When set, selects only collections with this ID. + string collection_id = 2; + + // When false, selects only collections that are immediate children of + // the `parent` specified in the containing `RunQueryRequest`. + // When true, selects all descendant collections. + bool all_descendants = 3; + } + + // A filter. + message Filter { + // The type of filter. + oneof filter_type { + // A composite filter. + CompositeFilter composite_filter = 1; + + // A filter on a document field. + FieldFilter field_filter = 2; + + // A filter that takes exactly one argument. + UnaryFilter unary_filter = 3; + } + } + + // A filter that merges multiple other filters using the given operator. + message CompositeFilter { + // A composite filter operator. + enum Operator { + // Unspecified. This value must not be used. + OPERATOR_UNSPECIFIED = 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; + } + + // The operator for combining multiple filters. + Operator op = 1; + + // The list of filters to combine. + // + // Requires: + // + // * At least one filter is present. + repeated Filter filters = 2; + } + + // A filter on a specific field. + message FieldFilter { + // A field filter operator. + enum Operator { + // Unspecified. This value must not be used. + OPERATOR_UNSPECIFIED = 0; + + // The given `field` is less than the given `value`. + // + // Requires: + // + // * That `field` come first in `order_by`. + LESS_THAN = 1; + + // The given `field` is less than or equal to the given `value`. + // + // Requires: + // + // * That `field` come first in `order_by`. + LESS_THAN_OR_EQUAL = 2; + + // The given `field` is greater than the given `value`. + // + // Requires: + // + // * That `field` come first in `order_by`. + GREATER_THAN = 3; + + // The given `field` is greater than or equal to the given `value`. + // + // Requires: + // + // * That `field` come first in `order_by`. + GREATER_THAN_OR_EQUAL = 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`. + NOT_EQUAL = 6; + + // The given `field` is an array that contains the given `value`. + ARRAY_CONTAINS = 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. + ARRAY_CONTAINS_ANY = 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`. + NOT_IN = 10; + } + + // The field to filter by. + FieldReference field = 1; + + // The operator to filter by. + Operator op = 2; + + // The value to compare to. + Value value = 3; + } + + // A filter with a single operand. + message UnaryFilter { + // A unary operator. + enum Operator { + // Unspecified. This value must not be used. + OPERATOR_UNSPECIFIED = 0; + + // The given `field` is equal to `NaN`. + IS_NAN = 2; + + // The given `field` is equal to `NULL`. + IS_NULL = 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`. + IS_NOT_NAN = 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`. + IS_NOT_NULL = 5; + } + + // The unary operator to apply. + Operator op = 1; + + // The argument to the filter. + oneof operand_type { + // The field to which to apply the operator. + FieldReference field = 2; + } + } + + // An order on a field. + message Order { + // The field to order by. + FieldReference field = 1; + + // The direction to order by. Defaults to `ASCENDING`. + Direction direction = 2; + } + + // A sort direction. + enum Direction { + // Unspecified. + DIRECTION_UNSPECIFIED = 0; + + // Ascending. + ASCENDING = 1; + + // Descending. + DESCENDING = 2; + } + + // A reference to a field in a document, ex: `stats.operations`. + message FieldReference { + // 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. + string field_path = 2; + } + + // The projection of document's fields to return. + message Projection { + // The fields to return. + // + // If empty, all fields are returned. To only return the name + // of the document, use `['__name__']`. + repeated FieldReference fields = 2; + } + + // 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. + message FindNearest { + // The distance measure to use when comparing vectors. + enum DistanceMeasure { + // Should not be set. + DISTANCE_MEASURE_UNSPECIFIED = 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. + DOT_PRODUCT = 3; + } + + // Required. An indexed vector field to search upon. Only documents which + // contain vectors whose dimensionality match the query_vector can be + // returned. + FieldReference vector_field = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The query vector that we are searching on. Must be a vector of + // no more than 2048 dimensions. + Value query_vector = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. The distance measure to use, required. + DistanceMeasure distance_measure = 3 + [(google.api.field_behavior) = REQUIRED]; + + // Required. The number of nearest neighbors to return. Must be a positive + // integer of no more than 1000. + google.protobuf.Int32Value limit = 4 + [(google.api.field_behavior) = REQUIRED]; + + // 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. + string distance_result_field = 5 [(google.api.field_behavior) = OPTIONAL]; + + // 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` + google.protobuf.DoubleValue distance_threshold = 6 + [(google.api.field_behavior) = OPTIONAL]; + } + + // 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. + Projection select = 1; + + // The collections to query. + repeated CollectionSelector from = 2; + + // The filter to apply. + Filter where = 3; + + // The order to apply to the query results. + // + // Firestore allows callers to provide a full ordering, a partial ordering, or + // no ordering at all. In all cases, 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` + repeated Order order_by = 4; + + // 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. + Cursor start_at = 7; + + // 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. + Cursor end_at = 8; + + // 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. + int32 offset = 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. + google.protobuf.Int32Value limit = 5; + + // Optional. A potential nearest neighbors search. + // + // Applies after all other filters and ordering. + // + // Finds the closest vector embeddings to the given query vector. + FindNearest find_nearest = 9 [(google.api.field_behavior) = OPTIONAL]; +} + +// Firestore query for running an aggregation over a +// [StructuredQuery][google.firestore.v1.StructuredQuery]. +message StructuredAggregationQuery { + // Defines an aggregation that produces a single result. + message Aggregation { + // Count of documents that match the query. + // + // The `COUNT(*)` aggregation function operates on the entire document + // so it does not require a field reference. + message Count { + // 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. + google.protobuf.Int64Value up_to = 1 + [(google.api.field_behavior) = OPTIONAL]; + } + + // 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. + message Sum { + // The field to aggregate on. + StructuredQuery.FieldReference field = 1; + } + + // 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. + message Avg { + // The field to aggregate on. + StructuredQuery.FieldReference field = 1; + } + + // The type of aggregation to perform, required. + oneof operator { + // Count aggregator. + Count count = 1; + + // Sum aggregator. + Sum sum = 2; + + // Average aggregator. + Avg avg = 3; + } + + // 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_`. 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. + string alias = 7 [(google.api.field_behavior) = OPTIONAL]; + } + + // The base query to aggregate over. + oneof query_type { + // Nested structured query. + StructuredQuery structured_query = 1; + } + + // 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. + repeated Aggregation aggregations = 3 + [(google.api.field_behavior) = OPTIONAL]; +} + +// A position in a query result set. +message Cursor { + // 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. + repeated Value values = 1; + + // If the position is just before or just after the given values, relative + // to the sort order defined by the query. + bool before = 2; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/v1/query_profile.proto b/handwritten/firestore/dev/protos/google/firestore/v1/query_profile.proto new file mode 100644 index 00000000000..73f8cb1bacd --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/v1/query_profile.proto @@ -0,0 +1,92 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/api/field_behavior.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/struct.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "QueryProfileProto"; +option java_package = "com.google.firestore.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// Specification of the Firestore Query Profile fields. + +// Explain options for the query. +message ExplainOptions { + // 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. + bool analyze = 1 [(google.api.field_behavior) = OPTIONAL]; +} + +// Explain metrics for the query. +message ExplainMetrics { + // Planning phase information for the query. + PlanSummary plan_summary = 1; + + // Aggregated stats from the execution of the query. Only present when + // [ExplainOptions.analyze][google.firestore.v1.ExplainOptions.analyze] is set + // to true. + ExecutionStats execution_stats = 2; +} + +// Planning phase information for the query. +message PlanSummary { + // The indexes selected for the query. For example: + // [ + // {"query_scope": "Collection", "properties": "(foo ASC, __name__ ASC)"}, + // {"query_scope": "Collection", "properties": "(bar ASC, __name__ ASC)"} + // ] + repeated google.protobuf.Struct indexes_used = 1; +} + +// Execution statistics for the query. +message ExecutionStats { + // Total number of results returned, including documents, projections, + // aggregation results, keys. + int64 results_returned = 1; + + // Total time to execute the query in the backend. + google.protobuf.Duration execution_duration = 3; + + // Total billable read operations. + int64 read_operations = 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" + // } + // } + google.protobuf.Struct debug_stats = 5; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/v1/write.proto b/handwritten/firestore/dev/protos/google/firestore/v1/write.proto new file mode 100644 index 00000000000..fa25cc2a505 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/v1/write.proto @@ -0,0 +1,286 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/firestore/v1/bloom_filter.proto"; +import "google/firestore/v1/common.proto"; +import "google/firestore/v1/document.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "WriteProto"; +option java_package = "com.google.firestore.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// A write on a document. +message Write { + // The operation to execute. + oneof operation { + // A document to write. + Document update = 1; + + // A document name to delete. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string delete = 2; + + // Applies a transformation to a document. + DocumentTransform transform = 6; + } + + // 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. + DocumentMask update_mask = 3; + + // 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. + repeated DocumentTransform.FieldTransform update_transforms = 7; + + // An optional precondition on the document. + // + // The write will fail if this is set and not met by the target document. + Precondition current_document = 4; +} + +// A transformation of a document. +message DocumentTransform { + // A transformation of a field of the document. + message FieldTransform { + // A value that is calculated by the server. + enum ServerValue { + // Unspecified. This value must not be used. + SERVER_VALUE_UNSPECIFIED = 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. + REQUEST_TIME = 1; + } + + // The path of the field. See + // [Document.fields][google.firestore.v1.Document.fields] for the field path + // syntax reference. + string field_path = 1; + + // The transformation to apply on the field. + oneof transform_type { + // Sets the field to the given server value. + ServerValue set_to_server_value = 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. + Value increment = 3; + + // 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. + Value maximum = 4; + + // 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. + Value minimum = 5; + + // 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. + ArrayValue append_missing_elements = 6; + + // 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. + ArrayValue remove_all_from_array = 7; + } + } + + // The name of the document to transform. + string document = 1; + + // The list of transformations to apply to the fields of the document, in + // order. + // This must not be empty. + repeated FieldTransform field_transforms = 2; +} + +// The result of applying a write. +message WriteResult { + // 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. + google.protobuf.Timestamp update_time = 1; + + // The results of applying each + // [DocumentTransform.FieldTransform][google.firestore.v1.DocumentTransform.FieldTransform], + // in the same order. + repeated Value transform_results = 2; +} + +// 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. +message DocumentChange { + // The new state of the [Document][google.firestore.v1.Document]. + // + // If `mask` is set, contains only fields that were updated or added. + Document document = 1; + + // A set of target IDs of targets that match this document. + repeated int32 target_ids = 5; + + // A set of target IDs for targets that no longer match this document. + repeated int32 removed_target_ids = 6; +} + +// 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. +message DocumentDelete { + // The resource name of the [Document][google.firestore.v1.Document] that was + // deleted. + string document = 1; + + // A set of target IDs for targets that previously matched this entity. + repeated int32 removed_target_ids = 6; + + // The read timestamp at which the delete was observed. + // + // Greater or equal to the `commit_time` of the delete. + google.protobuf.Timestamp read_time = 4; +} + +// 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. +message DocumentRemove { + // The resource name of the [Document][google.firestore.v1.Document] that has + // gone out of view. + string document = 1; + + // A set of target IDs for targets that previously matched this document. + repeated int32 removed_target_ids = 2; + + // The read timestamp at which the remove was observed. + // + // Greater or equal to the `commit_time` of the change/delete/remove. + google.protobuf.Timestamp read_time = 4; +} + +// A digest of all the documents that match a given target. +message ExistenceFilter { + // The target ID to which this filter applies. + int32 target_id = 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. + int32 count = 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. + BloomFilter unchanged_names = 3; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/v1beta1/common.proto b/handwritten/firestore/dev/protos/google/firestore/v1beta1/common.proto new file mode 100644 index 00000000000..b18e53398b7 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/v1beta1/common.proto @@ -0,0 +1,82 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1beta1; + +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1Beta1"; +option go_package = "cloud.google.com/go/firestore/apiv1beta1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "CommonProto"; +option java_package = "com.google.firestore.v1beta1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1beta1"; +option ruby_package = "Google::Cloud::Firestore::V1beta1"; + +// 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.v1beta1.Document], and takes in account the dynamic nature of [Value][google.firestore.v1beta1.Value]. +message DocumentMask { + // The list of field paths in the mask. See [Document.fields][google.firestore.v1beta1.Document.fields] for a field + // path syntax reference. + repeated string field_paths = 1; +} + +// A precondition on a document, used for conditional operations. +message Precondition { + // The type of precondition. + oneof condition_type { + // When set to `true`, the target document must exist. + // When set to `false`, the target document must not exist. + bool exists = 1; + + // When set, the target document must exist and have been last updated at + // that time. + google.protobuf.Timestamp update_time = 2; + } +} + +// Options for creating a new transaction. +message TransactionOptions { + // Options for a transaction that can be used to read and write documents. + message ReadWrite { + // An optional transaction to retry. + bytes retry_transaction = 1; + } + + // Options for a transaction that can only be used to read documents. + message ReadOnly { + // The consistency mode for this transaction. If not set, defaults to strong + // consistency. + oneof consistency_selector { + // Reads documents at the given time. + // This may not be older than 60 seconds. + google.protobuf.Timestamp read_time = 2; + } + } + + // The mode of the transaction. + oneof mode { + // The transaction can only be used for read operations. + ReadOnly read_only = 2; + + // The transaction can be used for both read and write operations. + ReadWrite read_write = 3; + } +} diff --git a/handwritten/firestore/dev/protos/google/firestore/v1beta1/document.proto b/handwritten/firestore/dev/protos/google/firestore/v1beta1/document.proto new file mode 100644 index 00000000000..36b30151cd6 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/v1beta1/document.proto @@ -0,0 +1,149 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1beta1; + +import "google/protobuf/struct.proto"; +import "google/protobuf/timestamp.proto"; +import "google/type/latlng.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1Beta1"; +option go_package = "cloud.google.com/go/firestore/apiv1beta1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "DocumentProto"; +option java_package = "com.google.firestore.v1beta1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1beta1"; +option ruby_package = "Google::Cloud::Firestore::V1beta1"; + +// A Firestore document. +// +// Must not exceed 1 MiB - 4 bytes. +message Document { + // The resource name of the document, for example + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string name = 1; + + // The document's fields. + // + // The map keys represent field names. + // + // 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`. + // + // 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. + // + // Field paths may be used in other contexts to refer to structured fields + // defined here. For `map_value`, the field path is represented by the simple + // or quoted field names of the containing fields, delimited by `.`. For + // example, the structured field + // `"foo" : { map_value: { "x&y" : { string_value: "hello" }}}` would be + // represented by the field path `foo.x&y`. + // + // Within a field path, 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 ``. + map fields = 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. + google.protobuf.Timestamp create_time = 3; + + // 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. + google.protobuf.Timestamp update_time = 4; +} + +// A message that can hold any of the supported value types. +message Value { + // Must have a value set. + oneof value_type { + // A null value. + google.protobuf.NullValue null_value = 11; + + // A boolean value. + bool boolean_value = 1; + + // An integer value. + int64 integer_value = 2; + + // A double value. + double double_value = 3; + + // A timestamp value. + // + // Precise only to microseconds. When stored, any additional precision is + // rounded down. + google.protobuf.Timestamp timestamp_value = 10; + + // 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. + string string_value = 17; + + // A bytes value. + // + // Must not exceed 1 MiB - 89 bytes. + // Only the first 1,500 bytes are considered by queries. + bytes bytes_value = 18; + + // A reference to a document. For example: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string reference_value = 5; + + // A geo point value representing a point on the surface of Earth. + google.type.LatLng geo_point_value = 8; + + // An array value. + // + // Cannot directly contain another array value, though can contain an + // map which contains another array. + ArrayValue array_value = 9; + + // A map value. + MapValue map_value = 6; + } +} + +// An array value. +message ArrayValue { + // Values in the array. + repeated Value values = 1; +} + +// A map value. +message MapValue { + // 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. + map fields = 1; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/v1beta1/firestore.proto b/handwritten/firestore/dev/protos/google/firestore/v1beta1/firestore.proto new file mode 100644 index 00000000000..07d4b3fe998 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/v1beta1/firestore.proto @@ -0,0 +1,900 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1beta1; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/firestore/v1beta1/common.proto"; +import "google/firestore/v1beta1/document.proto"; +import "google/firestore/v1beta1/query.proto"; +import "google/firestore/v1beta1/write.proto"; +import "google/protobuf/empty.proto"; +import "google/protobuf/timestamp.proto"; +import "google/rpc/status.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1Beta1"; +option go_package = "cloud.google.com/go/firestore/apiv1beta1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "FirestoreProto"; +option java_package = "com.google.firestore.v1beta1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1beta1"; +option ruby_package = "Google::Cloud::Firestore::V1beta1"; + +// Specification of the Firestore API. + +// 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 (GCP) accelerate +// building truly serverless apps. +service Firestore { + option (google.api.default_host) = "firestore.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/datastore"; + + // Gets a single document. + rpc GetDocument(GetDocumentRequest) returns (Document) { + option (google.api.http) = { + get: "/v1beta1/{name=projects/*/databases/*/documents/*/**}" + }; + } + + // Lists documents. + rpc ListDocuments(ListDocumentsRequest) returns (ListDocumentsResponse) { + option (google.api.http) = { + get: "/v1beta1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}" + }; + } + + // Updates or inserts a document. + rpc UpdateDocument(UpdateDocumentRequest) returns (Document) { + option (google.api.http) = { + patch: "/v1beta1/{document.name=projects/*/databases/*/documents/*/**}" + body: "document" + }; + option (google.api.method_signature) = "document,update_mask"; + } + + // Deletes a document. + rpc DeleteDocument(DeleteDocumentRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1beta1/{name=projects/*/databases/*/documents/*/**}" + }; + option (google.api.method_signature) = "name"; + } + + // Gets multiple documents. + // + // Documents returned by this method are not guaranteed to be returned in the + // same order that they were requested. + rpc BatchGetDocuments(BatchGetDocumentsRequest) returns (stream BatchGetDocumentsResponse) { + option (google.api.http) = { + post: "/v1beta1/{database=projects/*/databases/*}/documents:batchGet" + body: "*" + }; + } + + // Starts a new transaction. + rpc BeginTransaction(BeginTransactionRequest) returns (BeginTransactionResponse) { + option (google.api.http) = { + post: "/v1beta1/{database=projects/*/databases/*}/documents:beginTransaction" + body: "*" + }; + option (google.api.method_signature) = "database"; + } + + // Commits a transaction, while optionally updating documents. + rpc Commit(CommitRequest) returns (CommitResponse) { + option (google.api.http) = { + post: "/v1beta1/{database=projects/*/databases/*}/documents:commit" + body: "*" + }; + option (google.api.method_signature) = "database,writes"; + } + + // Rolls back a transaction. + rpc Rollback(RollbackRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + post: "/v1beta1/{database=projects/*/databases/*}/documents:rollback" + body: "*" + }; + option (google.api.method_signature) = "database,transaction"; + } + + // Runs a query. + rpc RunQuery(RunQueryRequest) returns (stream RunQueryResponse) { + option (google.api.http) = { + post: "/v1beta1/{parent=projects/*/databases/*/documents}:runQuery" + body: "*" + additional_bindings { + post: "/v1beta1/{parent=projects/*/databases/*/documents/*/**}:runQuery" + body: "*" + } + }; + } + + // 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. + rpc PartitionQuery(PartitionQueryRequest) returns (PartitionQueryResponse) { + option (google.api.http) = { + post: "/v1beta1/{parent=projects/*/databases/*/documents}:partitionQuery" + body: "*" + additional_bindings { + post: "/v1beta1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery" + body: "*" + } + }; + } + + // Streams batches of document updates and deletes, in order. + rpc Write(stream WriteRequest) returns (stream WriteResponse) { + option (google.api.http) = { + post: "/v1beta1/{database=projects/*/databases/*}/documents:write" + body: "*" + }; + } + + // Listens to changes. + rpc Listen(stream ListenRequest) returns (stream ListenResponse) { + option (google.api.http) = { + post: "/v1beta1/{database=projects/*/databases/*}/documents:listen" + body: "*" + }; + } + + // Lists all the collection IDs underneath a document. + rpc ListCollectionIds(ListCollectionIdsRequest) returns (ListCollectionIdsResponse) { + option (google.api.http) = { + post: "/v1beta1/{parent=projects/*/databases/*/documents}:listCollectionIds" + body: "*" + additional_bindings { + post: "/v1beta1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds" + body: "*" + } + }; + option (google.api.method_signature) = "parent"; + } + + // 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.v1beta1.BatchWriteResponse] for the success status of each write. + // + // If you require an atomically applied set of writes, use + // [Commit][google.firestore.v1beta1.Firestore.Commit] instead. + rpc BatchWrite(BatchWriteRequest) returns (BatchWriteResponse) { + option (google.api.http) = { + post: "/v1beta1/{database=projects/*/databases/*}/documents:batchWrite" + body: "*" + }; + } + + // Creates a new document. + rpc CreateDocument(CreateDocumentRequest) returns (Document) { + option (google.api.http) = { + post: "/v1beta1/{parent=projects/*/databases/*/documents/**}/{collection_id}" + body: "document" + }; + } +} + +// The request for [Firestore.GetDocument][google.firestore.v1beta1.Firestore.GetDocument]. +message GetDocumentRequest { + // Required. The resource name of the Document to get. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // 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. + DocumentMask mask = 2; + + // The consistency mode for this transaction. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Reads the document in a transaction. + bytes transaction = 3; + + // Reads the version of the document at the given time. + // This may not be older than 270 seconds. + google.protobuf.Timestamp read_time = 5; + } +} + +// The request for [Firestore.ListDocuments][google.firestore.v1beta1.Firestore.ListDocuments]. +message ListDocumentsRequest { + // 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` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` + // or `messages`. + string collection_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // The maximum number of documents to return. + int32 page_size = 3; + + // The `next_page_token` value returned from a previous List request, if any. + string page_token = 4; + + // The order to sort results by. For example: `priority desc, name`. + string order_by = 6; + + // 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. + DocumentMask mask = 7; + + // The consistency mode for this transaction. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Reads documents in a transaction. + bytes transaction = 8; + + // Reads documents as they were at the given time. + // This may not be older than 270 seconds. + google.protobuf.Timestamp read_time = 10; + } + + // If the list should show missing documents. A missing document is a + // document that does not exist but has sub-documents. These documents will + // be returned with a key but will not have fields, [Document.create_time][google.firestore.v1beta1.Document.create_time], + // or [Document.update_time][google.firestore.v1beta1.Document.update_time] set. + // + // Requests with `show_missing` may not specify `where` or + // `order_by`. + bool show_missing = 12; +} + +// The response for [Firestore.ListDocuments][google.firestore.v1beta1.Firestore.ListDocuments]. +message ListDocumentsResponse { + // The Documents found. + repeated Document documents = 1; + + // The next page token. + string next_page_token = 2; +} + +// The request for [Firestore.CreateDocument][google.firestore.v1beta1.Firestore.CreateDocument]. +message CreateDocumentRequest { + // Required. The parent resource. For example: + // `projects/{project_id}/databases/{database_id}/documents` or + // `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`. + string collection_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // The client-assigned document ID to use for this document. + // + // Optional. If not specified, an ID will be assigned by the service. + string document_id = 3; + + // Required. The document to create. `name` must not be set. + Document document = 4 [(google.api.field_behavior) = REQUIRED]; + + // 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. + DocumentMask mask = 5; +} + +// The request for [Firestore.UpdateDocument][google.firestore.v1beta1.Firestore.UpdateDocument]. +message UpdateDocumentRequest { + // Required. The updated document. + // Creates the document if it does not already exist. + Document document = 1 [(google.api.field_behavior) = REQUIRED]; + + // 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. + DocumentMask update_mask = 2; + + // 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. + DocumentMask mask = 3; + + // An optional precondition on the document. + // The request will fail if this is set and not met by the target document. + Precondition current_document = 4; +} + +// The request for [Firestore.DeleteDocument][google.firestore.v1beta1.Firestore.DeleteDocument]. +message DeleteDocumentRequest { + // Required. The resource name of the Document to delete. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // An optional precondition on the document. + // The request will fail if this is set and not met by the target document. + Precondition current_document = 2; +} + +// The request for [Firestore.BatchGetDocuments][google.firestore.v1beta1.Firestore.BatchGetDocuments]. +message BatchGetDocumentsRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // 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. + repeated string documents = 2; + + // 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. + DocumentMask mask = 3; + + // The consistency mode for this transaction. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Reads documents in a transaction. + bytes transaction = 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. + TransactionOptions new_transaction = 5; + + // Reads documents as they were at the given time. + // This may not be older than 270 seconds. + google.protobuf.Timestamp read_time = 7; + } +} + +// The streamed response for [Firestore.BatchGetDocuments][google.firestore.v1beta1.Firestore.BatchGetDocuments]. +message BatchGetDocumentsResponse { + // A single result. + // This can be empty if the server is just returning a transaction. + oneof result { + // A document that was requested. + Document found = 1; + + // A document name that was requested but does not exist. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string missing = 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.v1beta1.BatchGetDocumentsRequest.new_transaction] was set in the request. + bytes transaction = 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. + google.protobuf.Timestamp read_time = 4; +} + +// The request for [Firestore.BeginTransaction][google.firestore.v1beta1.Firestore.BeginTransaction]. +message BeginTransactionRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The options for the transaction. + // Defaults to a read-write transaction. + TransactionOptions options = 2; +} + +// The response for [Firestore.BeginTransaction][google.firestore.v1beta1.Firestore.BeginTransaction]. +message BeginTransactionResponse { + // The transaction that was started. + bytes transaction = 1; +} + +// The request for [Firestore.Commit][google.firestore.v1beta1.Firestore.Commit]. +message CommitRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The writes to apply. + // + // Always executed atomically and in order. + repeated Write writes = 2; + + // If set, applies all writes in this transaction, and commits it. + bytes transaction = 3; +} + +// The response for [Firestore.Commit][google.firestore.v1beta1.Firestore.Commit]. +message CommitResponse { + // The result of applying the writes. + // + // This i-th write result corresponds to the i-th write in the + // request. + repeated WriteResult write_results = 1; + + // 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. + google.protobuf.Timestamp commit_time = 2; +} + +// The request for [Firestore.Rollback][google.firestore.v1beta1.Firestore.Rollback]. +message RollbackRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The transaction to roll back. + bytes transaction = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// The request for [Firestore.RunQuery][google.firestore.v1beta1.Firestore.RunQuery]. +message RunQueryRequest { + // 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` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // The query to run. + oneof query_type { + // A structured query. + StructuredQuery structured_query = 2; + } + + // The consistency mode for this transaction. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Reads documents in a transaction. + bytes transaction = 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. + TransactionOptions new_transaction = 6; + + // Reads documents as they were at the given time. + // This may not be older than 270 seconds. + google.protobuf.Timestamp read_time = 7; + } +} + +// The response for [Firestore.RunQuery][google.firestore.v1beta1.Firestore.RunQuery]. +message RunQueryResponse { + // 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.v1beta1.RunQueryRequest.new_transaction] was set in the request. + // If set, no other fields will be set in this response. + bytes transaction = 2; + + // A query result. + // Not set when reporting partial progress. + Document document = 1; + + // 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. + google.protobuf.Timestamp read_time = 3; + + // The number of results that have been skipped due to an offset between + // the last response and the current response. + int32 skipped_results = 4; +} + +// The request for [Firestore.PartitionQuery][google.firestore.v1beta1.Firestore.PartitionQuery]. +message PartitionQueryRequest { + // 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. + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // The query to partition. + oneof query_type { + // 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 structured_query = 2; + } + + // 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. + int64 partition_count = 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 + string page_token = 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`. + int32 page_size = 5; +} + +// The response for [Firestore.PartitionQuery][google.firestore.v1beta1.Firestore.PartitionQuery]. +message PartitionQueryResponse { + // 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. + repeated Cursor partitions = 1; + + // 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. + string next_page_token = 2; +} + +// The request for [Firestore.Write][google.firestore.v1beta1.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. +message WriteRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + // This is only required in the first message. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // 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. + string stream_id = 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. + repeated Write writes = 3; + + // 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.v1beta1.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. + bytes stream_token = 4; + + // Labels associated with this write request. + map labels = 5; +} + +// The response for [Firestore.Write][google.firestore.v1beta1.Firestore.Write]. +message WriteResponse { + // The ID of the stream. + // Only set on the first message, when a new stream was created. + string stream_id = 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. + bytes stream_token = 2; + + // The result of applying the writes. + // + // This i-th write result corresponds to the i-th write in the + // request. + repeated WriteResult write_results = 3; + + // 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. + google.protobuf.Timestamp commit_time = 4; +} + +// A request for [Firestore.Listen][google.firestore.v1beta1.Firestore.Listen] +message ListenRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The supported target changes. + oneof target_change { + // A target to add to this stream. + Target add_target = 2; + + // The ID of a target to remove from this stream. + int32 remove_target = 3; + } + + // Labels associated with this target change. + map labels = 4; +} + +// The response for [Firestore.Listen][google.firestore.v1beta1.Firestore.Listen]. +message ListenResponse { + // The supported responses. + oneof response_type { + // Targets have changed. + TargetChange target_change = 2; + + // A [Document][google.firestore.v1beta1.Document] has changed. + DocumentChange document_change = 3; + + // A [Document][google.firestore.v1beta1.Document] has been deleted. + DocumentDelete document_delete = 4; + + // A [Document][google.firestore.v1beta1.Document] has been removed from a target (because it is no longer + // relevant to that target). + DocumentRemove document_remove = 6; + + // 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. + ExistenceFilter filter = 5; + } +} + +// A specification of a set of documents to listen to. +message Target { + // A target specified by a set of documents names. + message DocumentsTarget { + // 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. + repeated string documents = 2; + } + + // A target specified by a query. + message QueryTarget { + // 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` + string parent = 1; + + // The query to run. + oneof query_type { + // A structured query. + StructuredQuery structured_query = 2; + } + } + + // The type of target to listen to. + oneof target_type { + // A target specified by a query. + QueryTarget query = 2; + + // A target specified by a set of document names. + DocumentsTarget documents = 3; + } + + // When to start listening. + // + // If not specified, all matching Documents are returned before any + // subsequent changes. + oneof resume_type { + // A resume token from a prior [TargetChange][google.firestore.v1beta1.TargetChange] for an identical target. + // + // Using a resume token with a different target is unsupported and may fail. + bytes resume_token = 4; + + // Start listening after a specific `read_time`. + // + // The client must know the state of matching documents at this time. + google.protobuf.Timestamp read_time = 11; + } + + // The target ID that identifies the target on the stream. Must be a positive + // number and non-zero. + int32 target_id = 5; + + // If the target should be removed once it is current and consistent. + bool once = 6; +} + +// Targets being watched have changed. +message TargetChange { + // The type of change. + enum TargetChangeType { + // No change has occurred. Used only to send an updated `resume_token`. + NO_CHANGE = 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 change that occurred. + TargetChangeType target_change_type = 1; + + // 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. + repeated int32 target_ids = 2; + + // The error that resulted in this change, if applicable. + google.rpc.Status cause = 3; + + // 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. + bytes resume_token = 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. + google.protobuf.Timestamp read_time = 6; +} + +// The request for [Firestore.ListCollectionIds][google.firestore.v1beta1.Firestore.ListCollectionIds]. +message ListCollectionIdsRequest { + // 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` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // The maximum number of results to return. + int32 page_size = 2; + + // A page token. Must be a value from + // [ListCollectionIdsResponse][google.firestore.v1beta1.ListCollectionIdsResponse]. + string page_token = 3; +} + +// The response from [Firestore.ListCollectionIds][google.firestore.v1beta1.Firestore.ListCollectionIds]. +message ListCollectionIdsResponse { + // The collection ids. + repeated string collection_ids = 1; + + // A page token that may be used to continue the list. + string next_page_token = 2; +} + +// The request for [Firestore.BatchWrite][google.firestore.v1beta1.Firestore.BatchWrite]. +message BatchWriteRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // 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. + repeated Write writes = 2; + + // Labels associated with this batch write. + map labels = 3; +} + +// The response from [Firestore.BatchWrite][google.firestore.v1beta1.Firestore.BatchWrite]. +message BatchWriteResponse { + // The result of applying the writes. + // + // This i-th write result corresponds to the i-th write in the + // request. + repeated WriteResult write_results = 1; + + // The status of applying the writes. + // + // This i-th write status corresponds to the i-th write in the + // request. + repeated google.rpc.Status status = 2; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/v1beta1/query.proto b/handwritten/firestore/dev/protos/google/firestore/v1beta1/query.proto new file mode 100644 index 00000000000..f107ab72177 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/v1beta1/query.proto @@ -0,0 +1,300 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1beta1; + +import "google/firestore/v1beta1/document.proto"; +import "google/protobuf/wrappers.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1Beta1"; +option go_package = "cloud.google.com/go/firestore/apiv1beta1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "QueryProto"; +option java_package = "com.google.firestore.v1beta1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1beta1"; +option ruby_package = "Google::Cloud::Firestore::V1beta1"; + +// A Firestore query. +message StructuredQuery { + // A selection of a collection, such as `messages as m1`. + message CollectionSelector { + // The collection ID. + // When set, selects only collections with this ID. + string collection_id = 2; + + // When false, selects only collections that are immediate children of + // the `parent` specified in the containing `RunQueryRequest`. + // When true, selects all descendant collections. + bool all_descendants = 3; + } + + // A filter. + message Filter { + // The type of filter. + oneof filter_type { + // A composite filter. + CompositeFilter composite_filter = 1; + + // A filter on a document field. + FieldFilter field_filter = 2; + + // A filter that takes exactly one argument. + UnaryFilter unary_filter = 3; + } + } + + // A filter that merges multiple other filters using the given operator. + message CompositeFilter { + // A composite filter operator. + enum Operator { + // Unspecified. This value must not be used. + OPERATOR_UNSPECIFIED = 0; + + // The results are required to satisfy each of the combined filters. + AND = 1; + } + + // The operator for combining multiple filters. + Operator op = 1; + + // The list of filters to combine. + // Must contain at least one filter. + repeated Filter filters = 2; + } + + // A filter on a specific field. + message FieldFilter { + // A field filter operator. + enum Operator { + // Unspecified. This value must not be used. + OPERATOR_UNSPECIFIED = 0; + + // The given `field` is less than the given `value`. + // + // Requires: + // + // * That `field` come first in `order_by`. + LESS_THAN = 1; + + // The given `field` is less than or equal to the given `value`. + // + // Requires: + // + // * That `field` come first in `order_by`. + LESS_THAN_OR_EQUAL = 2; + + // The given `field` is greater than the given `value`. + // + // Requires: + // + // * That `field` come first in `order_by`. + GREATER_THAN = 3; + + // The given `field` is greater than or equal to the given `value`. + // + // Requires: + // + // * That `field` come first in `order_by`. + GREATER_THAN_OR_EQUAL = 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`. + NOT_EQUAL = 6; + + // The given `field` is an array that contains the given `value`. + ARRAY_CONTAINS = 7; + + // The given `field` is equal to at least one value in the given array. + // + // Requires: + // + // * That `value` is a non-empty `ArrayValue` with at most 10 values. + // * No other `IN` or `ARRAY_CONTAINS_ANY` or `NOT_IN`. + 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` with at most 10 values. + // * No other `IN` or `ARRAY_CONTAINS_ANY` or `NOT_IN`. + ARRAY_CONTAINS_ANY = 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 `IN`, `ARRAY_CONTAINS_ANY`, `NOT_IN`, `NOT_EQUAL`, + // `IS_NOT_NULL`, or `IS_NOT_NAN`. + // * That `field` comes first in the `order_by`. + NOT_IN = 10; + } + + // The field to filter by. + FieldReference field = 1; + + // The operator to filter by. + Operator op = 2; + + // The value to compare to. + Value value = 3; + } + + // A filter with a single operand. + message UnaryFilter { + // A unary operator. + enum Operator { + // Unspecified. This value must not be used. + OPERATOR_UNSPECIFIED = 0; + + // The given `field` is equal to `NaN`. + IS_NAN = 2; + + // The given `field` is equal to `NULL`. + IS_NULL = 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`. + IS_NOT_NAN = 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`. + IS_NOT_NULL = 5; + } + + // The unary operator to apply. + Operator op = 1; + + // The argument to the filter. + oneof operand_type { + // The field to which to apply the operator. + FieldReference field = 2; + } + } + + // A reference to a field, such as `max(messages.time) as max_time`. + message FieldReference { + string field_path = 2; + } + + // An order on a field. + message Order { + // The field to order by. + FieldReference field = 1; + + // The direction to order by. Defaults to `ASCENDING`. + Direction direction = 2; + } + + // The projection of document's fields to return. + message Projection { + // The fields to return. + // + // If empty, all fields are returned. To only return the name + // of the document, use `['__name__']`. + repeated FieldReference fields = 2; + } + + // A sort direction. + enum Direction { + // Unspecified. + DIRECTION_UNSPECIFIED = 0; + + // Ascending. + ASCENDING = 1; + + // Descending. + DESCENDING = 2; + } + + // The projection to return. + Projection select = 1; + + // The collections to query. + repeated CollectionSelector from = 2; + + // The filter to apply. + Filter where = 3; + + // The order to apply to the query results. + // + // Firestore guarantees a stable ordering through the following rules: + // + // * Any field required to appear in `order_by`, that is not already + // specified in `order_by`, is appended to the order in field name order + // by default. + // * 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: + // + // * `SELECT * FROM Foo ORDER BY A` becomes + // `SELECT * FROM Foo ORDER BY A, __name__` + // * `SELECT * FROM Foo ORDER BY A DESC` becomes + // `SELECT * FROM Foo ORDER BY A DESC, __name__ DESC` + // * `SELECT * FROM Foo WHERE A > 1` becomes + // `SELECT * FROM Foo WHERE A > 1 ORDER BY A, __name__` + repeated Order order_by = 4; + + // A starting point for the query results. + Cursor start_at = 7; + + // A end point for the query results. + Cursor end_at = 8; + + // The number of results to skip. + // + // Applies before limit, but after all other constraints. Must be >= 0 if + // specified. + int32 offset = 6; + + // The maximum number of results to return. + // + // Applies after all other constraints. + // Must be >= 0 if specified. + google.protobuf.Int32Value limit = 5; +} + +// A position in a query result set. +message Cursor { + // 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. + repeated Value values = 1; + + // If the position is just before or just after the given values, relative + // to the sort order defined by the query. + bool before = 2; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/v1beta1/undeliverable_first_gen_event.proto b/handwritten/firestore/dev/protos/google/firestore/v1beta1/undeliverable_first_gen_event.proto new file mode 100644 index 00000000000..0f7841eb9d6 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/v1beta1/undeliverable_first_gen_event.proto @@ -0,0 +1,75 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1beta1; + +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1Beta1"; +option go_package = "cloud.google.com/go/firestore/apiv1beta1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "UndeliverableFirstGenEventProto"; +option java_package = "com.google.firestore.v1beta1"; +option php_namespace = "Google\\Cloud\\Firestore\\V1beta1"; +option ruby_package = "Google::Cloud::Firestore::V1beta1"; + +// A message signifying an event that cannot be delivered to Cloud Functions +// from Firestore using [Cloud Firestore triggers 1st +// gen](https://cloud.google.com/functions/docs/calling/cloud-firestore) +message UndeliverableFirstGenEvent { + // Reason for events being undeliverable. + enum Reason { + // Unspecified. + REASON_UNSPECIFIED = 0; + + // Exceeding maximum event size limit + EXCEEDING_SIZE_LIMIT = 1; + } + + // Document change type. + enum DocumentChangeType { + // Unspecified. + DOCUMENT_CHANGE_TYPE_UNSPECIFIED = 0; + + // Represent creation operation. + CREATE = 1; + + // Represent delete operation. + DELETE = 2; + + // Represent update operation. + UPDATE = 3; + } + + // Error message for events being undeliverable. + string message = 1; + + // Reason for events being undeliverable. + Reason reason = 2; + + // The resource name of the changed document, in the format of + // `projects/{projectId}/databases/{databaseId}/documents/{document_path}`. + string document_name = 3; + + // The type of the document change. + DocumentChangeType document_change_type = 4; + + // The names of the functions that were supposed to be triggered. + repeated string function_name = 5; + + // The commit time of triggered write operation. + google.protobuf.Timestamp triggered_time = 6; +} diff --git a/handwritten/firestore/dev/protos/google/firestore/v1beta1/write.proto b/handwritten/firestore/dev/protos/google/firestore/v1beta1/write.proto new file mode 100644 index 00000000000..2fbe127ebe8 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/firestore/v1beta1/write.proto @@ -0,0 +1,258 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1beta1; + +import "google/firestore/v1beta1/common.proto"; +import "google/firestore/v1beta1/document.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1Beta1"; +option go_package = "cloud.google.com/go/firestore/apiv1beta1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "WriteProto"; +option java_package = "com.google.firestore.v1beta1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1beta1"; +option ruby_package = "Google::Cloud::Firestore::V1beta1"; + +// A write on a document. +message Write { + // The operation to execute. + oneof operation { + // A document to write. + Document update = 1; + + // A document name to delete. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string delete = 2; + + // Applies a transformation to a document. + DocumentTransform transform = 6; + } + + // 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. + DocumentMask update_mask = 3; + + // 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. + repeated DocumentTransform.FieldTransform update_transforms = 7; + + // An optional precondition on the document. + // + // The write will fail if this is set and not met by the target document. + Precondition current_document = 4; +} + +// A transformation of a document. +message DocumentTransform { + // A transformation of a field of the document. + message FieldTransform { + // A value that is calculated by the server. + enum ServerValue { + // Unspecified. This value must not be used. + SERVER_VALUE_UNSPECIFIED = 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. + REQUEST_TIME = 1; + } + + // The path of the field. See [Document.fields][google.firestore.v1beta1.Document.fields] for the field path syntax + // reference. + string field_path = 1; + + // The transformation to apply on the field. + oneof transform_type { + // Sets the field to the given server value. + ServerValue set_to_server_value = 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. + Value increment = 3; + + // 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. + Value maximum = 4; + + // 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. + Value minimum = 5; + + // 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. + ArrayValue append_missing_elements = 6; + + // 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. + ArrayValue remove_all_from_array = 7; + } + } + + // The name of the document to transform. + string document = 1; + + // The list of transformations to apply to the fields of the document, in + // order. + // This must not be empty. + repeated FieldTransform field_transforms = 2; +} + +// The result of applying a write. +message WriteResult { + // 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. + google.protobuf.Timestamp update_time = 1; + + // The results of applying each [DocumentTransform.FieldTransform][google.firestore.v1beta1.DocumentTransform.FieldTransform], in the + // same order. + repeated Value transform_results = 2; +} + +// A [Document][google.firestore.v1beta1.Document] has changed. +// +// May be the result of multiple [writes][google.firestore.v1beta1.Write], including deletes, that +// ultimately resulted in a new value for the [Document][google.firestore.v1beta1.Document]. +// +// Multiple [DocumentChange][google.firestore.v1beta1.DocumentChange] messages may be returned for the same logical +// change, if multiple targets are affected. +message DocumentChange { + // The new state of the [Document][google.firestore.v1beta1.Document]. + // + // If `mask` is set, contains only fields that were updated or added. + Document document = 1; + + // A set of target IDs of targets that match this document. + repeated int32 target_ids = 5; + + // A set of target IDs for targets that no longer match this document. + repeated int32 removed_target_ids = 6; +} + +// A [Document][google.firestore.v1beta1.Document] has been deleted. +// +// May be the result of multiple [writes][google.firestore.v1beta1.Write], including updates, the +// last of which deleted the [Document][google.firestore.v1beta1.Document]. +// +// Multiple [DocumentDelete][google.firestore.v1beta1.DocumentDelete] messages may be returned for the same logical +// delete, if multiple targets are affected. +message DocumentDelete { + // The resource name of the [Document][google.firestore.v1beta1.Document] that was deleted. + string document = 1; + + // A set of target IDs for targets that previously matched this entity. + repeated int32 removed_target_ids = 6; + + // The read timestamp at which the delete was observed. + // + // Greater or equal to the `commit_time` of the delete. + google.protobuf.Timestamp read_time = 4; +} + +// A [Document][google.firestore.v1beta1.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.v1beta1.DocumentRemove] messages may be returned for the same logical +// write or delete, if multiple targets are affected. +message DocumentRemove { + // The resource name of the [Document][google.firestore.v1beta1.Document] that has gone out of view. + string document = 1; + + // A set of target IDs for targets that previously matched this document. + repeated int32 removed_target_ids = 2; + + // The read timestamp at which the remove was observed. + // + // Greater or equal to the `commit_time` of the change/delete/remove. + google.protobuf.Timestamp read_time = 4; +} + +// A digest of all the documents that match a given target. +message ExistenceFilter { + // The target ID to which this filter applies. + int32 target_id = 1; + + // The total count of documents that match [target_id][google.firestore.v1beta1.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. + int32 count = 2; +} diff --git a/handwritten/firestore/dev/protos/google/longrunning/operations.proto b/handwritten/firestore/dev/protos/google/longrunning/operations.proto new file mode 100644 index 00000000000..63df207d258 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/longrunning/operations.proto @@ -0,0 +1,265 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.longrunning; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/protobuf/any.proto"; +import "google/protobuf/descriptor.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/empty.proto"; +import "google/rpc/status.proto"; + +option csharp_namespace = "Google.LongRunning"; +option go_package = "cloud.google.com/go/longrunning/autogen/longrunningpb;longrunningpb"; +option java_multiple_files = true; +option java_outer_classname = "OperationsProto"; +option java_package = "com.google.longrunning"; +option objc_class_prefix = "GLRUN"; +option php_namespace = "Google\\LongRunning"; + +extend google.protobuf.MethodOptions { + // Additional information regarding long-running operations. + // In particular, this specifies the types that are returned from + // long-running operations. + // + // Required for methods that return `google.longrunning.Operation`; invalid + // otherwise. + google.longrunning.OperationInfo operation_info = 1049; +} + +// Manages long-running operations with an API service. +// +// When an API method normally takes long time to complete, it can be designed +// to return [Operation][google.longrunning.Operation] to the client, and the +// client can use this interface to receive the real response asynchronously by +// polling the operation resource, or pass the operation resource to another API +// (such as Pub/Sub API) to receive the response. Any API service that returns +// long-running operations should implement the `Operations` interface so +// developers can have a consistent client experience. +service Operations { + option (google.api.default_host) = "longrunning.googleapis.com"; + + // Lists operations that match the specified filter in the request. If the + // server doesn't support this method, it returns `UNIMPLEMENTED`. + rpc ListOperations(ListOperationsRequest) returns (ListOperationsResponse) { + option (google.api.http) = { + get: "/v1/{name=operations}" + }; + option (google.api.method_signature) = "name,filter"; + } + + // Gets the latest state of a long-running operation. Clients can use this + // method to poll the operation result at intervals as recommended by the API + // service. + rpc GetOperation(GetOperationRequest) returns (Operation) { + option (google.api.http) = { + get: "/v1/{name=operations/**}" + }; + option (google.api.method_signature) = "name"; + } + + // Deletes a long-running operation. This method indicates that the client is + // no longer interested in the operation result. It does not cancel the + // operation. If the server doesn't support this method, it returns + // `google.rpc.Code.UNIMPLEMENTED`. + rpc DeleteOperation(DeleteOperationRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=operations/**}" + }; + option (google.api.method_signature) = "name"; + } + + // Starts asynchronous cancellation on a long-running operation. The server + // makes a best effort to cancel the operation, but success is not + // guaranteed. If the server doesn't support this method, it returns + // `google.rpc.Code.UNIMPLEMENTED`. Clients can use + // [Operations.GetOperation][google.longrunning.Operations.GetOperation] or + // other methods to check whether the cancellation succeeded or whether the + // operation completed despite cancellation. On successful cancellation, + // the operation is not deleted; instead, it becomes an operation with + // an [Operation.error][google.longrunning.Operation.error] value with a + // [google.rpc.Status.code][google.rpc.Status.code] of `1`, corresponding to + // `Code.CANCELLED`. + rpc CancelOperation(CancelOperationRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + post: "/v1/{name=operations/**}:cancel" + body: "*" + }; + option (google.api.method_signature) = "name"; + } + + // Waits until the specified long-running operation is done or reaches at most + // a specified timeout, returning the latest state. If the operation is + // already done, the latest state is immediately returned. If the timeout + // specified is greater than the default HTTP/RPC timeout, the HTTP/RPC + // timeout is used. If the server does not support this method, it returns + // `google.rpc.Code.UNIMPLEMENTED`. + // Note that this method is on a best-effort basis. It may return the latest + // state before the specified timeout (including immediately), meaning even an + // immediate response is no guarantee that the operation is done. + rpc WaitOperation(WaitOperationRequest) returns (Operation) {} +} + +// This resource represents a long-running operation that is the result of a +// network API call. +message Operation { + // The server-assigned name, which is only unique within the same service that + // originally returns it. If you use the default HTTP mapping, the + // `name` should be a resource name ending with `operations/{unique_id}`. + string name = 1; + + // Service-specific metadata associated with the operation. It typically + // contains progress information and common metadata such as create time. + // Some services might not provide such metadata. Any method that returns a + // long-running operation should document the metadata type, if any. + google.protobuf.Any metadata = 2; + + // If the value is `false`, it means the operation is still in progress. + // If `true`, the operation is completed, and either `error` or `response` is + // available. + bool done = 3; + + // The operation result, which can be either an `error` or a valid `response`. + // If `done` == `false`, neither `error` nor `response` is set. + // If `done` == `true`, exactly one of `error` or `response` can be set. + // Some services might not provide the result. + oneof result { + // The error result of the operation in case of failure or cancellation. + google.rpc.Status error = 4; + + // The normal, successful response of the operation. If the original + // method returns no data on success, such as `Delete`, the response is + // `google.protobuf.Empty`. If the original method is standard + // `Get`/`Create`/`Update`, the response should be the resource. For other + // methods, the response should have the type `XxxResponse`, where `Xxx` + // is the original method name. For example, if the original method name + // is `TakeSnapshot()`, the inferred response type is + // `TakeSnapshotResponse`. + google.protobuf.Any response = 5; + } +} + +// The request message for +// [Operations.GetOperation][google.longrunning.Operations.GetOperation]. +message GetOperationRequest { + // The name of the operation resource. + string name = 1; +} + +// The request message for +// [Operations.ListOperations][google.longrunning.Operations.ListOperations]. +message ListOperationsRequest { + // The name of the operation's parent resource. + string name = 4; + + // The standard list filter. + string filter = 1; + + // The standard list page size. + int32 page_size = 2; + + // The standard list page token. + string page_token = 3; + + // When set to `true`, operations that are reachable are returned as normal, + // and those that are unreachable are returned in the + // [ListOperationsResponse.unreachable] field. + // + // This can only be `true` when reading across collections e.g. when `parent` + // is set to `"projects/example/locations/-"`. + // + // This field is not by default supported and will result in an + // `UNIMPLEMENTED` error if set unless explicitly documented otherwise in + // service or product specific documentation. + bool return_partial_success = 5; +} + +// The response message for +// [Operations.ListOperations][google.longrunning.Operations.ListOperations]. +message ListOperationsResponse { + // A list of operations that matches the specified filter in the request. + repeated Operation operations = 1; + + // The standard List next-page token. + string next_page_token = 2; + + // Unordered list. Unreachable resources. Populated when the request sets + // `ListOperationsRequest.return_partial_success` and reads across + // collections e.g. when attempting to list all resources across all supported + // locations. + repeated string unreachable = 3 + [(google.api.field_behavior) = UNORDERED_LIST]; +} + +// The request message for +// [Operations.CancelOperation][google.longrunning.Operations.CancelOperation]. +message CancelOperationRequest { + // The name of the operation resource to be cancelled. + string name = 1; +} + +// The request message for +// [Operations.DeleteOperation][google.longrunning.Operations.DeleteOperation]. +message DeleteOperationRequest { + // The name of the operation resource to be deleted. + string name = 1; +} + +// The request message for +// [Operations.WaitOperation][google.longrunning.Operations.WaitOperation]. +message WaitOperationRequest { + // The name of the operation resource to wait on. + string name = 1; + + // The maximum duration to wait before timing out. If left blank, the wait + // will be at most the time permitted by the underlying HTTP/RPC protocol. + // If RPC context deadline is also specified, the shorter one will be used. + google.protobuf.Duration timeout = 2; +} + +// A message representing the message types used by a long-running operation. +// +// Example: +// +// rpc Export(ExportRequest) returns (google.longrunning.Operation) { +// option (google.longrunning.operation_info) = { +// response_type: "ExportResponse" +// metadata_type: "ExportMetadata" +// }; +// } +message OperationInfo { + // Required. The message name of the primary return type for this + // long-running operation. + // This type will be used to deserialize the LRO's response. + // + // If the response is in a different package from the rpc, a fully-qualified + // message name must be used (e.g. `google.protobuf.Struct`). + // + // Note: Altering this value constitutes a breaking change. + string response_type = 1; + + // Required. The message name of the metadata type for this long-running + // operation. + // + // If the response is in a different package from the rpc, a fully-qualified + // message name must be used (e.g. `google.protobuf.Struct`). + // + // Note: Altering this value constitutes a breaking change. + string metadata_type = 2; +} diff --git a/handwritten/firestore/dev/protos/google/protobuf/any.proto b/handwritten/firestore/dev/protos/google/protobuf/any.proto new file mode 100644 index 00000000000..eff44e5099d --- /dev/null +++ b/handwritten/firestore/dev/protos/google/protobuf/any.proto @@ -0,0 +1,162 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option go_package = "google.golang.org/protobuf/types/known/anypb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "AnyProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; + +// `Any` contains an arbitrary serialized protocol buffer message along with a +// URL that describes the type of the serialized message. +// +// Protobuf library provides support to pack/unpack Any values in the form +// of utility functions or additional generated methods of the Any type. +// +// Example 1: Pack and unpack a message in C++. +// +// Foo foo = ...; +// Any any; +// any.PackFrom(foo); +// ... +// if (any.UnpackTo(&foo)) { +// ... +// } +// +// Example 2: Pack and unpack a message in Java. +// +// Foo foo = ...; +// Any any = Any.pack(foo); +// ... +// if (any.is(Foo.class)) { +// foo = any.unpack(Foo.class); +// } +// // or ... +// if (any.isSameTypeAs(Foo.getDefaultInstance())) { +// foo = any.unpack(Foo.getDefaultInstance()); +// } +// +// Example 3: Pack and unpack a message in Python. +// +// foo = Foo(...) +// any = Any() +// any.Pack(foo) +// ... +// if any.Is(Foo.DESCRIPTOR): +// any.Unpack(foo) +// ... +// +// Example 4: Pack and unpack a message in Go +// +// foo := &pb.Foo{...} +// any, err := anypb.New(foo) +// if err != nil { +// ... +// } +// ... +// foo := &pb.Foo{} +// if err := any.UnmarshalTo(foo); err != nil { +// ... +// } +// +// The pack methods provided by protobuf library will by default use +// 'type.googleapis.com/full.type.name' as the type URL and the unpack +// methods only use the fully qualified type name after the last '/' +// in the type URL, for example "foo.bar.com/x/y.z" will yield type +// name "y.z". +// +// JSON +// ==== +// The JSON representation of an `Any` value uses the regular +// representation of the deserialized, embedded message, with an +// additional field `@type` which contains the type URL. Example: +// +// package google.profile; +// message Person { +// string first_name = 1; +// string last_name = 2; +// } +// +// { +// "@type": "type.googleapis.com/google.profile.Person", +// "firstName": , +// "lastName": +// } +// +// If the embedded message type is well-known and has a custom JSON +// representation, that representation will be embedded adding a field +// `value` which holds the custom JSON in addition to the `@type` +// field. Example (for message [google.protobuf.Duration][]): +// +// { +// "@type": "type.googleapis.com/google.protobuf.Duration", +// "value": "1.212s" +// } +// +message Any { + // A URL/resource name that uniquely identifies the type of the serialized + // protocol buffer message. This string must contain at least + // one "/" character. The last segment of the URL's path must represent + // the fully qualified name of the type (as in + // `path/google.protobuf.Duration`). The name should be in a canonical form + // (e.g., leading "." is not accepted). + // + // In practice, teams usually precompile into the binary all types that they + // expect it to use in the context of Any. However, for URLs which use the + // scheme `http`, `https`, or no scheme, one can optionally set up a type + // server that maps type URLs to message definitions as follows: + // + // * If no scheme is provided, `https` is assumed. + // * An HTTP GET on the URL must yield a [google.protobuf.Type][] + // value in binary format, or produce an error. + // * Applications are allowed to cache lookup results based on the + // URL, or have them precompiled into a binary to avoid any + // lookup. Therefore, binary compatibility needs to be preserved + // on changes to types. (Use versioned type names to manage + // breaking changes.) + // + // Note: this functionality is not currently available in the official + // protobuf release, and it is not used for type URLs beginning with + // type.googleapis.com. As of May 2023, there are no widely used type server + // implementations and no plans to implement one. + // + // Schemes other than `http`, `https` (or the empty scheme) might be + // used with implementation specific semantics. + // + string type_url = 1; + + // Must be a valid serialized protocol buffer of the above specified type. + bytes value = 2; +} diff --git a/handwritten/firestore/dev/protos/google/protobuf/descriptor.proto b/handwritten/firestore/dev/protos/google/protobuf/descriptor.proto new file mode 100644 index 00000000000..8f619e85cd4 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/protobuf/descriptor.proto @@ -0,0 +1,1219 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// The messages in this file describe the definitions found in .proto files. +// A valid .proto file can be translated directly to a FileDescriptorProto +// without any other information (e.g. without reading its imports). + +syntax = "proto2"; + +package google.protobuf; + +option go_package = "google.golang.org/protobuf/types/descriptorpb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "DescriptorProtos"; +option csharp_namespace = "Google.Protobuf.Reflection"; +option objc_class_prefix = "GPB"; +option cc_enable_arenas = true; + +// descriptor.proto must be optimized for speed because reflection-based +// algorithms don't work during bootstrapping. +option optimize_for = SPEED; + +// The protocol compiler can output a FileDescriptorSet containing the .proto +// files it parses. +message FileDescriptorSet { + repeated FileDescriptorProto file = 1; +} + +// The full set of known editions. +enum Edition { + // A placeholder for an unknown edition value. + EDITION_UNKNOWN = 0; + + // Legacy syntax "editions". These pre-date editions, but behave much like + // distinct editions. These can't be used to specify the edition of proto + // files, but feature definitions must supply proto2/proto3 defaults for + // backwards compatibility. + EDITION_PROTO2 = 998; + EDITION_PROTO3 = 999; + + // Editions that have been released. The specific values are arbitrary and + // should not be depended on, but they will always be time-ordered for easy + // comparison. + EDITION_2023 = 1000; + EDITION_2024 = 1001; + + // Placeholder editions for testing feature resolution. These should not be + // used or relyed on outside of tests. + EDITION_1_TEST_ONLY = 1; + EDITION_2_TEST_ONLY = 2; + EDITION_99997_TEST_ONLY = 99997; + EDITION_99998_TEST_ONLY = 99998; + EDITION_99999_TEST_ONLY = 99999; + + // Placeholder for specifying unbounded edition support. This should only + // ever be used by plugins that can expect to never require any changes to + // support a new edition. + EDITION_MAX = 0x7FFFFFFF; +} + +// Describes a complete .proto file. +message FileDescriptorProto { + optional string name = 1; // file name, relative to root of source tree + optional string package = 2; // e.g. "foo", "foo.bar", etc. + + // Names of files imported by this file. + repeated string dependency = 3; + // Indexes of the public imported files in the dependency list above. + repeated int32 public_dependency = 10; + // Indexes of the weak imported files in the dependency list. + // For Google-internal migration only. Do not use. + repeated int32 weak_dependency = 11; + + // All top-level definitions in this file. + repeated DescriptorProto message_type = 4; + repeated EnumDescriptorProto enum_type = 5; + repeated ServiceDescriptorProto service = 6; + repeated FieldDescriptorProto extension = 7; + + optional FileOptions options = 8; + + // This field contains optional information about the original source code. + // You may safely remove this entire field without harming runtime + // functionality of the descriptors -- the information is needed only by + // development tools. + optional SourceCodeInfo source_code_info = 9; + + // The syntax of the proto file. + // The supported values are "proto2", "proto3", and "editions". + // + // If `edition` is present, this value must be "editions". + optional string syntax = 12; + + // The edition of the proto file. + optional Edition edition = 14; +} + +// Describes a message type. +message DescriptorProto { + optional string name = 1; + + repeated FieldDescriptorProto field = 2; + repeated FieldDescriptorProto extension = 6; + + repeated DescriptorProto nested_type = 3; + repeated EnumDescriptorProto enum_type = 4; + + message ExtensionRange { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Exclusive. + + optional ExtensionRangeOptions options = 3; + } + repeated ExtensionRange extension_range = 5; + + repeated OneofDescriptorProto oneof_decl = 8; + + optional MessageOptions options = 7; + + // Range of reserved tag numbers. Reserved tag numbers may not be used by + // fields or extension ranges in the same message. Reserved ranges may + // not overlap. + message ReservedRange { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Exclusive. + } + repeated ReservedRange reserved_range = 9; + // Reserved field names, which may not be used by fields in the same message. + // A given name may only be reserved once. + repeated string reserved_name = 10; +} + +message ExtensionRangeOptions { + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + message Declaration { + // The extension number declared within the extension range. + optional int32 number = 1; + + // The fully-qualified name of the extension field. There must be a leading + // dot in front of the full name. + optional string full_name = 2; + + // The fully-qualified type name of the extension field. Unlike + // Metadata.type, Declaration.type must have a leading dot for messages + // and enums. + optional string type = 3; + + // If true, indicates that the number is reserved in the extension range, + // and any extension field with the number will fail to compile. Set this + // when a declared extension field is deleted. + optional bool reserved = 5; + + // If true, indicates that the extension must be defined as repeated. + // Otherwise the extension must be defined as optional. + optional bool repeated = 6; + + reserved 4; // removed is_repeated + } + + // For external users: DO NOT USE. We are in the process of open sourcing + // extension declaration and executing internal cleanups before it can be + // used externally. + repeated Declaration declaration = 2 [retention = RETENTION_SOURCE]; + + // Any features defined in the specific edition. + optional FeatureSet features = 50; + + // The verification state of the extension range. + enum VerificationState { + // All the extensions of the range must be declared. + DECLARATION = 0; + UNVERIFIED = 1; + } + + // The verification state of the range. + // TODO: flip the default to DECLARATION once all empty ranges + // are marked as UNVERIFIED. + optional VerificationState verification = 3 + [default = UNVERIFIED, retention = RETENTION_SOURCE]; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +// Describes a field within a message. +message FieldDescriptorProto { + enum Type { + // 0 is reserved for errors. + // Order is weird for historical reasons. + TYPE_DOUBLE = 1; + TYPE_FLOAT = 2; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + // negative values are likely. + TYPE_INT64 = 3; + TYPE_UINT64 = 4; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + // negative values are likely. + TYPE_INT32 = 5; + TYPE_FIXED64 = 6; + TYPE_FIXED32 = 7; + TYPE_BOOL = 8; + TYPE_STRING = 9; + // Tag-delimited aggregate. + // Group type is deprecated and not supported after google.protobuf. However, Proto3 + // implementations should still be able to parse the group wire format and + // treat group fields as unknown fields. In Editions, the group wire format + // can be enabled via the `message_encoding` feature. + TYPE_GROUP = 10; + TYPE_MESSAGE = 11; // Length-delimited aggregate. + + // New in version 2. + TYPE_BYTES = 12; + TYPE_UINT32 = 13; + TYPE_ENUM = 14; + TYPE_SFIXED32 = 15; + TYPE_SFIXED64 = 16; + TYPE_SINT32 = 17; // Uses ZigZag encoding. + TYPE_SINT64 = 18; // Uses ZigZag encoding. + } + + enum Label { + // 0 is reserved for errors + LABEL_OPTIONAL = 1; + LABEL_REPEATED = 3; + // The required label is only allowed in google.protobuf. In proto3 and Editions + // it's explicitly prohibited. In Editions, the `field_presence` feature + // can be used to get this behavior. + LABEL_REQUIRED = 2; + } + + optional string name = 1; + optional int32 number = 3; + optional Label label = 4; + + // If type_name is set, this need not be set. If both this and type_name + // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. + optional Type type = 5; + + // For message and enum types, this is the name of the type. If the name + // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping + // rules are used to find the type (i.e. first the nested types within this + // message are searched, then within the parent, on up to the root + // namespace). + optional string type_name = 6; + + // For extensions, this is the name of the type being extended. It is + // resolved in the same manner as type_name. + optional string extendee = 2; + + // For numeric types, contains the original text representation of the value. + // For booleans, "true" or "false". + // For strings, contains the default text contents (not escaped in any way). + // For bytes, contains the C escaped value. All bytes >= 128 are escaped. + optional string default_value = 7; + + // If set, gives the index of a oneof in the containing type's oneof_decl + // list. This field is a member of that oneof. + optional int32 oneof_index = 9; + + // JSON name of this field. The value is set by protocol compiler. If the + // user has set a "json_name" option on this field, that option's value + // will be used. Otherwise, it's deduced from the field's name by converting + // it to camelCase. + optional string json_name = 10; + + optional FieldOptions options = 8; + + // If true, this is a proto3 "optional". When a proto3 field is optional, it + // tracks presence regardless of field type. + // + // When proto3_optional is true, this field must belong to a oneof to signal + // to old proto3 clients that presence is tracked for this field. This oneof + // is known as a "synthetic" oneof, and this field must be its sole member + // (each proto3 optional field gets its own synthetic oneof). Synthetic oneofs + // exist in the descriptor only, and do not generate any API. Synthetic oneofs + // must be ordered after all "real" oneofs. + // + // For message fields, proto3_optional doesn't create any semantic change, + // since non-repeated message fields always track presence. However it still + // indicates the semantic detail of whether the user wrote "optional" or not. + // This can be useful for round-tripping the .proto file. For consistency we + // give message fields a synthetic oneof also, even though it is not required + // to track presence. This is especially important because the parser can't + // tell if a field is a message or an enum, so it must always create a + // synthetic oneof. + // + // Proto2 optional fields do not set this flag, because they already indicate + // optional with `LABEL_OPTIONAL`. + optional bool proto3_optional = 17; +} + +// Describes a oneof. +message OneofDescriptorProto { + optional string name = 1; + optional OneofOptions options = 2; +} + +// Describes an enum type. +message EnumDescriptorProto { + optional string name = 1; + + repeated EnumValueDescriptorProto value = 2; + + optional EnumOptions options = 3; + + // Range of reserved numeric values. Reserved values may not be used by + // entries in the same enum. Reserved ranges may not overlap. + // + // Note that this is distinct from DescriptorProto.ReservedRange in that it + // is inclusive such that it can appropriately represent the entire int32 + // domain. + message EnumReservedRange { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Inclusive. + } + + // Range of reserved numeric values. Reserved numeric values may not be used + // by enum values in the same enum declaration. Reserved ranges may not + // overlap. + repeated EnumReservedRange reserved_range = 4; + + // Reserved enum value names, which may not be reused. A given name may only + // be reserved once. + repeated string reserved_name = 5; +} + +// Describes a value within an enum. +message EnumValueDescriptorProto { + optional string name = 1; + optional int32 number = 2; + + optional EnumValueOptions options = 3; +} + +// Describes a service. +message ServiceDescriptorProto { + optional string name = 1; + repeated MethodDescriptorProto method = 2; + + optional ServiceOptions options = 3; +} + +// Describes a method of a service. +message MethodDescriptorProto { + optional string name = 1; + + // Input and output type names. These are resolved in the same way as + // FieldDescriptorProto.type_name, but must refer to a message type. + optional string input_type = 2; + optional string output_type = 3; + + optional MethodOptions options = 4; + + // Identifies if client streams multiple client messages + optional bool client_streaming = 5 [default = false]; + // Identifies if server streams multiple server messages + optional bool server_streaming = 6 [default = false]; +} + +// =================================================================== +// Options + +// Each of the definitions above may have "options" attached. These are +// just annotations which may cause code to be generated slightly differently +// or may contain hints for code that manipulates protocol messages. +// +// Clients may define custom options as extensions of the *Options messages. +// These extensions may not yet be known at parsing time, so the parser cannot +// store the values in them. Instead it stores them in a field in the *Options +// message called uninterpreted_option. This field must have the same name +// across all *Options messages. We then use this field to populate the +// extensions when we build a descriptor, at which point all protos have been +// parsed and so all extensions are known. +// +// Extension numbers for custom options may be chosen as follows: +// * For options which will only be used within a single application or +// organization, or for experimental options, use field numbers 50000 +// through 99999. It is up to you to ensure that you do not use the +// same number for multiple options. +// * For options which will be published and used publicly by multiple +// independent entities, e-mail protobuf-global-extension-registry@google.com +// to reserve extension numbers. Simply provide your project name (e.g. +// Objective-C plugin) and your project website (if available) -- there's no +// need to explain how you intend to use them. Usually you only need one +// extension number. You can declare multiple options with only one extension +// number by putting them in a sub-message. See the Custom Options section of +// the docs for examples: +// https://developers.google.com/protocol-buffers/docs/proto#options +// If this turns out to be popular, a web service will be set up +// to automatically assign option numbers. + +message FileOptions { + + // Sets the Java package where classes generated from this .proto will be + // placed. By default, the proto package is used, but this is often + // inappropriate because proto packages do not normally start with backwards + // domain names. + optional string java_package = 1; + + // Controls the name of the wrapper Java class generated for the .proto file. + // That class will always contain the .proto file's getDescriptor() method as + // well as any top-level extensions defined in the .proto file. + // If java_multiple_files is disabled, then all the other classes from the + // .proto file will be nested inside the single wrapper outer class. + optional string java_outer_classname = 8; + + // If enabled, then the Java code generator will generate a separate .java + // file for each top-level message, enum, and service defined in the .proto + // file. Thus, these types will *not* be nested inside the wrapper class + // named by java_outer_classname. However, the wrapper class will still be + // generated to contain the file's getDescriptor() method as well as any + // top-level extensions defined in the file. + optional bool java_multiple_files = 10 [default = false]; + + // This option does nothing. + optional bool java_generate_equals_and_hash = 20 [deprecated=true]; + + // If set true, then the Java2 code generator will generate code that + // throws an exception whenever an attempt is made to assign a non-UTF-8 + // byte sequence to a string field. + // Message reflection will do the same. + // However, an extension field still accepts non-UTF-8 byte sequences. + // This option has no effect on when used with the lite runtime. + optional bool java_string_check_utf8 = 27 [default = false]; + + // Generated classes can be optimized for speed or code size. + enum OptimizeMode { + SPEED = 1; // Generate complete code for parsing, serialization, + // etc. + CODE_SIZE = 2; // Use ReflectionOps to implement these methods. + LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. + } + optional OptimizeMode optimize_for = 9 [default = SPEED]; + + // Sets the Go package where structs generated from this .proto will be + // placed. If omitted, the Go package will be derived from the following: + // - The basename of the package import path, if provided. + // - Otherwise, the package statement in the .proto file, if present. + // - Otherwise, the basename of the .proto file, without extension. + optional string go_package = 11; + + // Should generic services be generated in each language? "Generic" services + // are not specific to any particular RPC system. They are generated by the + // main code generators in each language (without additional plugins). + // Generic services were the only kind of service generation supported by + // early versions of google.protobuf. + // + // Generic services are now considered deprecated in favor of using plugins + // that generate code specific to your particular RPC system. Therefore, + // these default to false. Old code which depends on generic services should + // explicitly set them to true. + optional bool cc_generic_services = 16 [default = false]; + optional bool java_generic_services = 17 [default = false]; + optional bool py_generic_services = 18 [default = false]; + reserved 42; // removed php_generic_services + + // Is this file deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for everything in the file, or it will be completely ignored; in the very + // least, this is a formalization for deprecating files. + optional bool deprecated = 23 [default = false]; + + // Enables the use of arenas for the proto messages in this file. This applies + // only to generated classes for C++. + optional bool cc_enable_arenas = 31 [default = true]; + + // Sets the objective c class prefix which is prepended to all objective c + // generated classes from this .proto. There is no default. + optional string objc_class_prefix = 36; + + // Namespace for generated classes; defaults to the package. + optional string csharp_namespace = 37; + + // By default Swift generators will take the proto package and CamelCase it + // replacing '.' with underscore and use that to prefix the types/symbols + // defined. When this options is provided, they will use this value instead + // to prefix the types/symbols defined. + optional string swift_prefix = 39; + + // Sets the php class prefix which is prepended to all php generated classes + // from this .proto. Default is empty. + optional string php_class_prefix = 40; + + // Use this option to change the namespace of php generated classes. Default + // is empty. When this option is empty, the package name will be used for + // determining the namespace. + optional string php_namespace = 41; + + // Use this option to change the namespace of php generated metadata classes. + // Default is empty. When this option is empty, the proto file name will be + // used for determining the namespace. + optional string php_metadata_namespace = 44; + + // Use this option to change the package of ruby generated classes. Default + // is empty. When this option is not set, the package name will be used for + // determining the ruby package. + optional string ruby_package = 45; + + // Any features defined in the specific edition. + optional FeatureSet features = 50; + + // The parser stores options it doesn't recognize here. + // See the documentation for the "Options" section above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. + // See the documentation for the "Options" section above. + extensions 1000 to max; + + reserved 38; +} + +message MessageOptions { + // Set true to use the old proto1 MessageSet wire format for extensions. + // This is provided for backwards-compatibility with the MessageSet wire + // format. You should not use this for any other reason: It's less + // efficient, has fewer features, and is more complicated. + // + // The message must be defined exactly as follows: + // message Foo { + // option message_set_wire_format = true; + // extensions 4 to max; + // } + // Note that the message cannot have any defined fields; MessageSets only + // have extensions. + // + // All extensions of your type must be singular messages; e.g. they cannot + // be int32s, enums, or repeated messages. + // + // Because this is an option, the above two restrictions are not enforced by + // the protocol compiler. + optional bool message_set_wire_format = 1 [default = false]; + + // Disables the generation of the standard "descriptor()" accessor, which can + // conflict with a field of the same name. This is meant to make migration + // from proto1 easier; new code should avoid fields named "descriptor". + optional bool no_standard_descriptor_accessor = 2 [default = false]; + + // Is this message deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the message, or it will be completely ignored; in the very least, + // this is a formalization for deprecating messages. + optional bool deprecated = 3 [default = false]; + + reserved 4, 5, 6; + + // Whether the message is an automatically generated map entry type for the + // maps field. + // + // For maps fields: + // map map_field = 1; + // The parsed descriptor looks like: + // message MapFieldEntry { + // option map_entry = true; + // optional KeyType key = 1; + // optional ValueType value = 2; + // } + // repeated MapFieldEntry map_field = 1; + // + // Implementations may choose not to generate the map_entry=true message, but + // use a native map in the target language to hold the keys and values. + // The reflection APIs in such implementations still need to work as + // if the field is a repeated message field. + // + // NOTE: Do not set the option in .proto files. Always use the maps syntax + // instead. The option should only be implicitly set by the proto compiler + // parser. + optional bool map_entry = 7; + + reserved 8; // javalite_serializable + reserved 9; // javanano_as_lite + + // Enable the legacy handling of JSON field name conflicts. This lowercases + // and strips underscored from the fields before comparison in proto3 only. + // The new behavior takes `json_name` into account and applies to proto2 as + // well. + // + // This should only be used as a temporary measure against broken builds due + // to the change in behavior for JSON field name conflicts. + // + // TODO This is legacy behavior we plan to remove once downstream + // teams have had time to migrate. + optional bool deprecated_legacy_json_field_conflicts = 11 [deprecated = true]; + + // Any features defined in the specific edition. + optional FeatureSet features = 12; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message FieldOptions { + // The ctype option instructs the C++ code generator to use a different + // representation of the field than it normally would. See the specific + // options below. This option is only implemented to support use of + // [ctype=CORD] and [ctype=STRING] (the default) on non-repeated fields of + // type "bytes" in the open source release -- sorry, we'll try to include + // other types in a future version! + optional CType ctype = 1 [default = STRING]; + enum CType { + // Default mode. + STRING = 0; + + // The option [ctype=CORD] may be applied to a non-repeated field of type + // "bytes". It indicates that in C++, the data should be stored in a Cord + // instead of a string. For very large strings, this may reduce memory + // fragmentation. It may also allow better performance when parsing from a + // Cord, or when parsing with aliasing enabled, as the parsed Cord may then + // alias the original buffer. + CORD = 1; + + STRING_PIECE = 2; + } + // The packed option can be enabled for repeated primitive fields to enable + // a more efficient representation on the wire. Rather than repeatedly + // writing the tag and type for each element, the entire array is encoded as + // a single length-delimited blob. In proto3, only explicit setting it to + // false will avoid using packed encoding. This option is prohibited in + // Editions, but the `repeated_field_encoding` feature can be used to control + // the behavior. + optional bool packed = 2; + + // The jstype option determines the JavaScript type used for values of the + // field. The option is permitted only for 64 bit integral and fixed types + // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING + // is represented as JavaScript string, which avoids loss of precision that + // can happen when a large value is converted to a floating point JavaScript. + // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to + // use the JavaScript "number" type. The behavior of the default option + // JS_NORMAL is implementation dependent. + // + // This option is an enum to permit additional types to be added, e.g. + // goog.math.Integer. + optional JSType jstype = 6 [default = JS_NORMAL]; + enum JSType { + // Use the default type. + JS_NORMAL = 0; + + // Use JavaScript strings. + JS_STRING = 1; + + // Use JavaScript numbers. + JS_NUMBER = 2; + } + + // Should this field be parsed lazily? Lazy applies only to message-type + // fields. It means that when the outer message is initially parsed, the + // inner message's contents will not be parsed but instead stored in encoded + // form. The inner message will actually be parsed when it is first accessed. + // + // This is only a hint. Implementations are free to choose whether to use + // eager or lazy parsing regardless of the value of this option. However, + // setting this option true suggests that the protocol author believes that + // using lazy parsing on this field is worth the additional bookkeeping + // overhead typically needed to implement it. + // + // This option does not affect the public interface of any generated code; + // all method signatures remain the same. Furthermore, thread-safety of the + // interface is not affected by this option; const methods remain safe to + // call from multiple threads concurrently, while non-const methods continue + // to require exclusive access. + // + // Note that lazy message fields are still eagerly verified to check + // ill-formed wireformat or missing required fields. Calling IsInitialized() + // on the outer message would fail if the inner message has missing required + // fields. Failed verification would result in parsing failure (except when + // uninitialized messages are acceptable). + optional bool lazy = 5 [default = false]; + + // unverified_lazy does no correctness checks on the byte stream. This should + // only be used where lazy with verification is prohibitive for performance + // reasons. + optional bool unverified_lazy = 15 [default = false]; + + // Is this field deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for accessors, or it will be completely ignored; in the very least, this + // is a formalization for deprecating fields. + optional bool deprecated = 3 [default = false]; + + // For Google-internal migration only. Do not use. + optional bool weak = 10 [default = false]; + + // Indicate that the field value should not be printed out when using debug + // formats, e.g. when the field contains sensitive credentials. + optional bool debug_redact = 16 [default = false]; + + // If set to RETENTION_SOURCE, the option will be omitted from the binary. + // Note: as of January 2023, support for this is in progress and does not yet + // have an effect (b/264593489). + enum OptionRetention { + RETENTION_UNKNOWN = 0; + RETENTION_RUNTIME = 1; + RETENTION_SOURCE = 2; + } + + optional OptionRetention retention = 17; + + // This indicates the types of entities that the field may apply to when used + // as an option. If it is unset, then the field may be freely used as an + // option on any kind of entity. Note: as of January 2023, support for this is + // in progress and does not yet have an effect (b/264593489). + enum OptionTargetType { + TARGET_TYPE_UNKNOWN = 0; + TARGET_TYPE_FILE = 1; + TARGET_TYPE_EXTENSION_RANGE = 2; + TARGET_TYPE_MESSAGE = 3; + TARGET_TYPE_FIELD = 4; + TARGET_TYPE_ONEOF = 5; + TARGET_TYPE_ENUM = 6; + TARGET_TYPE_ENUM_ENTRY = 7; + TARGET_TYPE_SERVICE = 8; + TARGET_TYPE_METHOD = 9; + } + + repeated OptionTargetType targets = 19; + + message EditionDefault { + optional Edition edition = 3; + optional string value = 2; // Textproto value. + } + repeated EditionDefault edition_defaults = 20; + + // Any features defined in the specific edition. + optional FeatureSet features = 21; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; + + reserved 4; // removed jtype + reserved 18; // reserve target, target_obsolete_do_not_use +} + +message OneofOptions { + // Any features defined in the specific edition. + optional FeatureSet features = 1; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message EnumOptions { + + // Set this option to true to allow mapping different tag names to the same + // value. + optional bool allow_alias = 2; + + // Is this enum deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the enum, or it will be completely ignored; in the very least, this + // is a formalization for deprecating enums. + optional bool deprecated = 3 [default = false]; + + reserved 5; // javanano_as_lite + + // Enable the legacy handling of JSON field name conflicts. This lowercases + // and strips underscored from the fields before comparison in proto3 only. + // The new behavior takes `json_name` into account and applies to proto2 as + // well. + // TODO Remove this legacy behavior once downstream teams have + // had time to migrate. + optional bool deprecated_legacy_json_field_conflicts = 6 [deprecated = true]; + + // Any features defined in the specific edition. + optional FeatureSet features = 7; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message EnumValueOptions { + // Is this enum value deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the enum value, or it will be completely ignored; in the very least, + // this is a formalization for deprecating enum values. + optional bool deprecated = 1 [default = false]; + + // Any features defined in the specific edition. + optional FeatureSet features = 2; + + // Indicate that fields annotated with this enum value should not be printed + // out when using debug formats, e.g. when the field contains sensitive + // credentials. + optional bool debug_redact = 3 [default = false]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message ServiceOptions { + + // Any features defined in the specific edition. + optional FeatureSet features = 34; + + // Note: Field numbers 1 through 32 are reserved for Google's internal RPC + // framework. We apologize for hoarding these numbers to ourselves, but + // we were already using them long before we decided to release Protocol + // Buffers. + + // Is this service deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the service, or it will be completely ignored; in the very least, + // this is a formalization for deprecating services. + optional bool deprecated = 33 [default = false]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message MethodOptions { + + // Note: Field numbers 1 through 32 are reserved for Google's internal RPC + // framework. We apologize for hoarding these numbers to ourselves, but + // we were already using them long before we decided to release Protocol + // Buffers. + + // Is this method deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the method, or it will be completely ignored; in the very least, + // this is a formalization for deprecating methods. + optional bool deprecated = 33 [default = false]; + + // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, + // or neither? HTTP based RPC implementation may choose GET verb for safe + // methods, and PUT verb for idempotent methods instead of the default POST. + enum IdempotencyLevel { + IDEMPOTENCY_UNKNOWN = 0; + NO_SIDE_EFFECTS = 1; // implies idempotent + IDEMPOTENT = 2; // idempotent, but may have side effects + } + optional IdempotencyLevel idempotency_level = 34 + [default = IDEMPOTENCY_UNKNOWN]; + + // Any features defined in the specific edition. + optional FeatureSet features = 35; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +// A message representing a option the parser does not recognize. This only +// appears in options protos created by the compiler::Parser class. +// DescriptorPool resolves these when building Descriptor objects. Therefore, +// options protos in descriptor objects (e.g. returned by Descriptor::options(), +// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions +// in them. +message UninterpretedOption { + // The name of the uninterpreted option. Each string represents a segment in + // a dot-separated name. is_extension is true iff a segment represents an + // extension (denoted with parentheses in options specs in .proto files). + // E.g.,{ ["foo", false], ["bar.baz", true], ["moo", false] } represents + // "foo.(bar.baz).moo". + message NamePart { + required string name_part = 1; + required bool is_extension = 2; + } + repeated NamePart name = 2; + + // The value of the uninterpreted option, in whatever type the tokenizer + // identified it as during parsing. Exactly one of these should be set. + optional string identifier_value = 3; + optional uint64 positive_int_value = 4; + optional int64 negative_int_value = 5; + optional double double_value = 6; + optional bytes string_value = 7; + optional string aggregate_value = 8; +} + +// =================================================================== +// Features + +// TODO Enums in C++ gencode (and potentially other languages) are +// not well scoped. This means that each of the feature enums below can clash +// with each other. The short names we've chosen maximize call-site +// readability, but leave us very open to this scenario. A future feature will +// be designed and implemented to handle this, hopefully before we ever hit a +// conflict here. +message FeatureSet { + enum FieldPresence { + FIELD_PRESENCE_UNKNOWN = 0; + EXPLICIT = 1; + IMPLICIT = 2; + LEGACY_REQUIRED = 3; + } + optional FieldPresence field_presence = 1 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "EXPLICIT" }, + edition_defaults = { edition: EDITION_PROTO3, value: "IMPLICIT" }, + edition_defaults = { edition: EDITION_2023, value: "EXPLICIT" } + ]; + + enum EnumType { + ENUM_TYPE_UNKNOWN = 0; + OPEN = 1; + CLOSED = 2; + } + optional EnumType enum_type = 2 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_ENUM, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "CLOSED" }, + edition_defaults = { edition: EDITION_PROTO3, value: "OPEN" } + ]; + + enum RepeatedFieldEncoding { + REPEATED_FIELD_ENCODING_UNKNOWN = 0; + PACKED = 1; + EXPANDED = 2; + } + optional RepeatedFieldEncoding repeated_field_encoding = 3 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "EXPANDED" }, + edition_defaults = { edition: EDITION_PROTO3, value: "PACKED" } + ]; + + enum Utf8Validation { + UTF8_VALIDATION_UNKNOWN = 0; + VERIFY = 2; + NONE = 3; + } + optional Utf8Validation utf8_validation = 4 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "NONE" }, + edition_defaults = { edition: EDITION_PROTO3, value: "VERIFY" } + ]; + + enum MessageEncoding { + MESSAGE_ENCODING_UNKNOWN = 0; + LENGTH_PREFIXED = 1; + DELIMITED = 2; + } + optional MessageEncoding message_encoding = 5 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "LENGTH_PREFIXED" } + ]; + + enum JsonFormat { + JSON_FORMAT_UNKNOWN = 0; + ALLOW = 1; + LEGACY_BEST_EFFORT = 2; + } + optional JsonFormat json_format = 6 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_MESSAGE, + targets = TARGET_TYPE_ENUM, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "LEGACY_BEST_EFFORT" }, + edition_defaults = { edition: EDITION_PROTO3, value: "ALLOW" } + ]; + + reserved 999; + + extensions 1000; // for Protobuf C++ + extensions 1001; // for Protobuf Java + extensions 1002; // for Protobuf Go + + extensions 9995 to 9999; // For internal testing + extensions 10000; // for https://github.com/bufbuild/protobuf-es +} + +// A compiled specification for the defaults of a set of features. These +// messages are generated from FeatureSet extensions and can be used to seed +// feature resolution. The resolution with this object becomes a simple search +// for the closest matching edition, followed by proto merges. +message FeatureSetDefaults { + // A map from every known edition with a unique set of defaults to its + // defaults. Not all editions may be contained here. For a given edition, + // the defaults at the closest matching edition ordered at or before it should + // be used. This field must be in strict ascending order by edition. + message FeatureSetEditionDefault { + optional Edition edition = 3; + optional FeatureSet features = 2; + } + repeated FeatureSetEditionDefault defaults = 1; + + // The minimum supported edition (inclusive) when this was constructed. + // Editions before this will not have defaults. + optional Edition minimum_edition = 4; + + // The maximum known edition (inclusive) when this was constructed. Editions + // after this will not have reliable defaults. + optional Edition maximum_edition = 5; +} + +// =================================================================== +// Optional source code info + +// Encapsulates information about the original source file from which a +// FileDescriptorProto was generated. +message SourceCodeInfo { + // A Location identifies a piece of source code in a .proto file which + // corresponds to a particular definition. This information is intended + // to be useful to IDEs, code indexers, documentation generators, and similar + // tools. + // + // For example, say we have a file like: + // message Foo { + // optional string foo = 1; + // } + // Let's look at just the field definition: + // optional string foo = 1; + // ^ ^^ ^^ ^ ^^^ + // a bc de f ghi + // We have the following locations: + // span path represents + // [a,i) [ 4, 0, 2, 0 ] The whole field definition. + // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). + // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). + // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). + // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). + // + // Notes: + // - A location may refer to a repeated field itself (i.e. not to any + // particular index within it). This is used whenever a set of elements are + // logically enclosed in a single code segment. For example, an entire + // extend block (possibly containing multiple extension definitions) will + // have an outer location whose path refers to the "extensions" repeated + // field without an index. + // - Multiple locations may have the same path. This happens when a single + // logical declaration is spread out across multiple places. The most + // obvious example is the "extend" block again -- there may be multiple + // extend blocks in the same scope, each of which will have the same path. + // - A location's span is not always a subset of its parent's span. For + // example, the "extendee" of an extension declaration appears at the + // beginning of the "extend" block and is shared by all extensions within + // the block. + // - Just because a location's span is a subset of some other location's span + // does not mean that it is a descendant. For example, a "group" defines + // both a type and a field in a single declaration. Thus, the locations + // corresponding to the type and field and their components will overlap. + // - Code which tries to interpret locations should probably be designed to + // ignore those that it doesn't understand, as more types of locations could + // be recorded in the future. + repeated Location location = 1; + message Location { + // Identifies which part of the FileDescriptorProto was defined at this + // location. + // + // Each element is a field number or an index. They form a path from + // the root FileDescriptorProto to the place where the definition appears. + // For example, this path: + // [ 4, 3, 2, 7, 1 ] + // refers to: + // file.message_type(3) // 4, 3 + // .field(7) // 2, 7 + // .name() // 1 + // This is because FileDescriptorProto.message_type has field number 4: + // repeated DescriptorProto message_type = 4; + // and DescriptorProto.field has field number 2: + // repeated FieldDescriptorProto field = 2; + // and FieldDescriptorProto.name has field number 1: + // optional string name = 1; + // + // Thus, the above path gives the location of a field name. If we removed + // the last element: + // [ 4, 3, 2, 7 ] + // this path refers to the whole field declaration (from the beginning + // of the label to the terminating semicolon). + repeated int32 path = 1 [packed = true]; + + // Always has exactly three or four elements: start line, start column, + // end line (optional, otherwise assumed same as start line), end column. + // These are packed into a single field for efficiency. Note that line + // and column numbers are zero-based -- typically you will want to add + // 1 to each before displaying to a user. + repeated int32 span = 2 [packed = true]; + + // If this SourceCodeInfo represents a complete declaration, these are any + // comments appearing before and after the declaration which appear to be + // attached to the declaration. + // + // A series of line comments appearing on consecutive lines, with no other + // tokens appearing on those lines, will be treated as a single comment. + // + // leading_detached_comments will keep paragraphs of comments that appear + // before (but not connected to) the current element. Each paragraph, + // separated by empty lines, will be one comment element in the repeated + // field. + // + // Only the comment content is provided; comment markers (e.g. //) are + // stripped out. For block comments, leading whitespace and an asterisk + // will be stripped from the beginning of each line other than the first. + // Newlines are included in the output. + // + // Examples: + // + // optional int32 foo = 1; // Comment attached to foo. + // // Comment attached to bar. + // optional int32 bar = 2; + // + // optional string baz = 3; + // // Comment attached to baz. + // // Another line attached to baz. + // + // // Comment attached to moo. + // // + // // Another line attached to moo. + // optional double moo = 4; + // + // // Detached comment for corge. This is not leading or trailing comments + // // to moo or corge because there are blank lines separating it from + // // both. + // + // // Detached comment for corge paragraph 2. + // + // optional string corge = 5; + // /* Block comment attached + // * to corge. Leading asterisks + // * will be removed. */ + // /* Block comment attached to + // * grault. */ + // optional int32 grault = 6; + // + // // ignored detached comments. + optional string leading_comments = 3; + optional string trailing_comments = 4; + repeated string leading_detached_comments = 6; + } +} + +// Describes the relationship between generated code and its original source +// file. A GeneratedCodeInfo message is associated with only one generated +// source file, but may contain references to different source .proto files. +message GeneratedCodeInfo { + // An Annotation connects some span of text in generated code to an element + // of its generating .proto file. + repeated Annotation annotation = 1; + message Annotation { + // Identifies the element in the original source .proto file. This field + // is formatted the same as SourceCodeInfo.Location.path. + repeated int32 path = 1 [packed = true]; + + // Identifies the filesystem path to the original source .proto. + optional string source_file = 2; + + // Identifies the starting offset in bytes in the generated code + // that relates to the identified object. + optional int32 begin = 3; + + // Identifies the ending offset in bytes in the generated code that + // relates to the identified object. The end offset should be one past + // the last relevant byte (so the length of the text = end - begin). + optional int32 end = 4; + + // Represents the identified object's effect on the element in the original + // .proto file. + enum Semantic { + // There is no effect or the effect is indescribable. + NONE = 0; + // The element is set or otherwise mutated. + SET = 1; + // An alias to the element is returned. + ALIAS = 2; + } + optional Semantic semantic = 5; + } +} diff --git a/handwritten/firestore/dev/protos/google/protobuf/duration.proto b/handwritten/firestore/dev/protos/google/protobuf/duration.proto new file mode 100644 index 00000000000..41f40c22247 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/protobuf/duration.proto @@ -0,0 +1,115 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/protobuf/types/known/durationpb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "DurationProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; + +// 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". +// +message Duration { + // 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 + int64 seconds = 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. + int32 nanos = 2; +} diff --git a/handwritten/firestore/dev/protos/google/protobuf/empty.proto b/handwritten/firestore/dev/protos/google/protobuf/empty.proto new file mode 100644 index 00000000000..b87c89dcfce --- /dev/null +++ b/handwritten/firestore/dev/protos/google/protobuf/empty.proto @@ -0,0 +1,51 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option go_package = "google.golang.org/protobuf/types/known/emptypb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "EmptyProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; +option cc_enable_arenas = true; + +// 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); +// } +// +message Empty {} diff --git a/handwritten/firestore/dev/protos/google/protobuf/field_mask.proto b/handwritten/firestore/dev/protos/google/protobuf/field_mask.proto new file mode 100644 index 00000000000..b28334b9439 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/protobuf/field_mask.proto @@ -0,0 +1,245 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option java_package = "com.google.protobuf"; +option java_outer_classname = "FieldMaskProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; +option go_package = "google.golang.org/protobuf/types/known/fieldmaskpb"; +option cc_enable_arenas = true; + +// `FieldMask` represents a set of symbolic field paths, for example: +// +// paths: "f.a" +// paths: "f.b.d" +// +// Here `f` represents a field in some root message, `a` and `b` +// fields in the message found in `f`, and `d` a field found in the +// message in `f.b`. +// +// Field masks are used to specify a subset of fields that should be +// returned by a get operation or modified by an update operation. +// Field masks also have a custom JSON encoding (see below). +// +// # Field Masks in Projections +// +// When used in the context of a projection, a response message or +// sub-message is filtered by the API to only contain those fields as +// specified in the mask. For example, if the mask in the previous +// example is applied to a response message as follows: +// +// f { +// a : 22 +// b { +// d : 1 +// x : 2 +// } +// y : 13 +// } +// z: 8 +// +// The result will not contain specific values for fields x,y and z +// (their value will be set to the default, and omitted in proto text +// output): +// +// +// f { +// a : 22 +// b { +// d : 1 +// } +// } +// +// A repeated field is not allowed except at the last position of a +// paths string. +// +// If a FieldMask object is not present in a get operation, the +// operation applies to all fields (as if a FieldMask of all fields +// had been specified). +// +// Note that a field mask does not necessarily apply to the +// top-level response message. In case of a REST get operation, the +// field mask applies directly to the response, but in case of a REST +// list operation, the mask instead applies to each individual message +// in the returned resource list. In case of a REST custom method, +// other definitions may be used. Where the mask applies will be +// clearly documented together with its declaration in the API. In +// any case, the effect on the returned resource/resources is required +// behavior for APIs. +// +// # Field Masks in Update Operations +// +// A field mask in update operations specifies which fields of the +// targeted resource are going to be updated. The API is required +// to only change the values of the fields as specified in the mask +// and leave the others untouched. If a resource is passed in to +// describe the updated values, the API ignores the values of all +// fields not covered by the mask. +// +// If a repeated field is specified for an update operation, new values will +// be appended to the existing repeated field in the target resource. Note that +// a repeated field is only allowed in the last position of a `paths` string. +// +// If a sub-message is specified in the last position of the field mask for an +// update operation, then new value will be merged into the existing sub-message +// in the target resource. +// +// For example, given the target message: +// +// f { +// b { +// d: 1 +// x: 2 +// } +// c: [1] +// } +// +// And an update message: +// +// f { +// b { +// d: 10 +// } +// c: [2] +// } +// +// then if the field mask is: +// +// paths: ["f.b", "f.c"] +// +// then the result will be: +// +// f { +// b { +// d: 10 +// x: 2 +// } +// c: [1, 2] +// } +// +// An implementation may provide options to override this default behavior for +// repeated and message fields. +// +// In order to reset a field's value to the default, the field must +// be in the mask and set to the default value in the provided resource. +// Hence, in order to reset all fields of a resource, provide a default +// instance of the resource and set all fields in the mask, or do +// not provide a mask as described below. +// +// If a field mask is not present on update, the operation applies to +// all fields (as if a field mask of all fields has been specified). +// Note that in the presence of schema evolution, this may mean that +// fields the client does not know and has therefore not filled into +// the request will be reset to their default. If this is unwanted +// behavior, a specific service may require a client to always specify +// a field mask, producing an error if not. +// +// As with get operations, the location of the resource which +// describes the updated values in the request message depends on the +// operation kind. In any case, the effect of the field mask is +// required to be honored by the API. +// +// ## Considerations for HTTP REST +// +// The HTTP kind of an update operation which uses a field mask must +// be set to PATCH instead of PUT in order to satisfy HTTP semantics +// (PUT must only be used for full updates). +// +// # JSON Encoding of Field Masks +// +// In JSON, a field mask is encoded as a single string where paths are +// separated by a comma. Fields name in each path are converted +// to/from lower-camel naming conventions. +// +// As an example, consider the following message declarations: +// +// message Profile { +// User user = 1; +// Photo photo = 2; +// } +// message User { +// string display_name = 1; +// string address = 2; +// } +// +// In proto a field mask for `Profile` may look as such: +// +// mask { +// paths: "user.display_name" +// paths: "photo" +// } +// +// In JSON, the same mask is represented as below: +// +// { +// mask: "user.displayName,photo" +// } +// +// # Field Masks and Oneof Fields +// +// Field masks treat fields in oneofs just as regular fields. Consider the +// following message: +// +// message SampleMessage { +// oneof test_oneof { +// string name = 4; +// SubMessage sub_message = 9; +// } +// } +// +// The field mask can be: +// +// mask { +// paths: "name" +// } +// +// Or: +// +// mask { +// paths: "sub_message" +// } +// +// Note that oneof type names ("test_oneof" in this case) cannot be used in +// paths. +// +// ## Field Mask Verification +// +// The implementation of any API method which has a FieldMask type field in the +// request should verify the included field paths, and return an +// `INVALID_ARGUMENT` error if any path is unmappable. +message FieldMask { + // The set of field mask paths. + repeated string paths = 1; +} diff --git a/handwritten/firestore/dev/protos/google/protobuf/struct.proto b/handwritten/firestore/dev/protos/google/protobuf/struct.proto new file mode 100644 index 00000000000..1bf0c1ad958 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/protobuf/struct.proto @@ -0,0 +1,95 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/protobuf/types/known/structpb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "StructProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; + +// `Struct` represents a structured data value, consisting of fields +// which map to dynamically typed values. In some languages, `Struct` +// might be supported by a native representation. For example, in +// scripting languages like JS a struct is represented as an +// object. The details of that representation are described together +// with the proto support for the language. +// +// The JSON representation for `Struct` is JSON object. +message Struct { + // Unordered map of dynamically typed values. + map fields = 1; +} + +// `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 indicates an error. +// +// The JSON representation for `Value` is JSON value. +message Value { + // The kind of value. + oneof kind { + // Represents a null value. + NullValue null_value = 1; + // Represents a double value. + double number_value = 2; + // Represents a string value. + string string_value = 3; + // Represents a boolean value. + bool bool_value = 4; + // Represents a structured value. + Struct struct_value = 5; + // Represents a repeated `Value`. + ListValue list_value = 6; + } +} + +// `NullValue` is a singleton enumeration to represent the null value for the +// `Value` type union. +// +// The JSON representation for `NullValue` is JSON `null`. +enum NullValue { + // Null value. + NULL_VALUE = 0; +} + +// `ListValue` is a wrapper around a repeated field of values. +// +// The JSON representation for `ListValue` is JSON array. +message ListValue { + // Repeated field of dynamically typed values. + repeated Value values = 1; +} diff --git a/handwritten/firestore/dev/protos/google/protobuf/timestamp.proto b/handwritten/firestore/dev/protos/google/protobuf/timestamp.proto new file mode 100644 index 00000000000..fd0bc07dc3c --- /dev/null +++ b/handwritten/firestore/dev/protos/google/protobuf/timestamp.proto @@ -0,0 +1,144 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/protobuf/types/known/timestamppb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "TimestampProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; + +// 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 proto3 JSON serializer should always use UTC (as indicated by +// "Z") when printing the Timestamp type and a proto3 JSON 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. +// +message Timestamp { + // Represents seconds of UTC time since Unix epoch + // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + // 9999-12-31T23:59:59Z inclusive. + int64 seconds = 1; + + // Non-negative fractions of a second at nanosecond resolution. Negative + // second values with fractions must still have non-negative nanos values + // that count forward in time. Must be from 0 to 999,999,999 + // inclusive. + int32 nanos = 2; +} diff --git a/handwritten/firestore/dev/protos/google/protobuf/wrappers.proto b/handwritten/firestore/dev/protos/google/protobuf/wrappers.proto new file mode 100644 index 00000000000..1959fa55a4e --- /dev/null +++ b/handwritten/firestore/dev/protos/google/protobuf/wrappers.proto @@ -0,0 +1,123 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Wrappers for primitive (non-message) types. These types are useful +// for embedding primitives in the `google.protobuf.Any` type and for places +// where we need to distinguish between the absence of a primitive +// typed field and its default value. +// +// These wrappers have no meaningful use within repeated fields as they lack +// the ability to detect presence on individual elements. +// These wrappers have no meaningful use within a map or a oneof since +// individual entries of a map or fields of a oneof can already detect presence. + +syntax = "proto3"; + +package google.protobuf; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/protobuf/types/known/wrapperspb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "WrappersProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; + +// Wrapper message for `double`. +// +// The JSON representation for `DoubleValue` is JSON number. +message DoubleValue { + // The double value. + double value = 1; +} + +// Wrapper message for `float`. +// +// The JSON representation for `FloatValue` is JSON number. +message FloatValue { + // The float value. + float value = 1; +} + +// Wrapper message for `int64`. +// +// The JSON representation for `Int64Value` is JSON string. +message Int64Value { + // The int64 value. + int64 value = 1; +} + +// Wrapper message for `uint64`. +// +// The JSON representation for `UInt64Value` is JSON string. +message UInt64Value { + // The uint64 value. + uint64 value = 1; +} + +// Wrapper message for `int32`. +// +// The JSON representation for `Int32Value` is JSON number. +message Int32Value { + // The int32 value. + int32 value = 1; +} + +// Wrapper message for `uint32`. +// +// The JSON representation for `UInt32Value` is JSON number. +message UInt32Value { + // The uint32 value. + uint32 value = 1; +} + +// Wrapper message for `bool`. +// +// The JSON representation for `BoolValue` is JSON `true` and `false`. +message BoolValue { + // The bool value. + bool value = 1; +} + +// Wrapper message for `string`. +// +// The JSON representation for `StringValue` is JSON string. +message StringValue { + // The string value. + string value = 1; +} + +// Wrapper message for `bytes`. +// +// The JSON representation for `BytesValue` is JSON string. +message BytesValue { + // The bytes value. + bytes value = 1; +} diff --git a/handwritten/firestore/dev/protos/google/rpc/status.proto b/handwritten/firestore/dev/protos/google/rpc/status.proto new file mode 100644 index 00000000000..dc14c9438ca --- /dev/null +++ b/handwritten/firestore/dev/protos/google/rpc/status.proto @@ -0,0 +1,49 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.rpc; + +import "google/protobuf/any.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/rpc/status;status"; +option java_multiple_files = true; +option java_outer_classname = "StatusProto"; +option java_package = "com.google.rpc"; +option objc_class_prefix = "RPC"; + +// 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). +message Status { + // The status code, which should be an enum value of + // [google.rpc.Code][google.rpc.Code]. + int32 code = 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. + string message = 2; + + // A list of messages that carry the error details. There is a common set of + // message types for APIs to use. + repeated google.protobuf.Any details = 3; +} diff --git a/handwritten/firestore/dev/protos/google/type/dayofweek.proto b/handwritten/firestore/dev/protos/google/type/dayofweek.proto new file mode 100644 index 00000000000..5684bec35e6 --- /dev/null +++ b/handwritten/firestore/dev/protos/google/type/dayofweek.proto @@ -0,0 +1,50 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/dayofweek;dayofweek"; +option java_multiple_files = true; +option java_outer_classname = "DayOfWeekProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a day of the week. +enum DayOfWeek { + // The day of the week is unspecified. + DAY_OF_WEEK_UNSPECIFIED = 0; + + // Monday + MONDAY = 1; + + // Tuesday + TUESDAY = 2; + + // Wednesday + WEDNESDAY = 3; + + // Thursday + THURSDAY = 4; + + // Friday + FRIDAY = 5; + + // Saturday + SATURDAY = 6; + + // Sunday + SUNDAY = 7; +} diff --git a/handwritten/firestore/dev/protos/google/type/latlng.proto b/handwritten/firestore/dev/protos/google/type/latlng.proto new file mode 100644 index 00000000000..6714f65bd5e --- /dev/null +++ b/handwritten/firestore/dev/protos/google/type/latlng.proto @@ -0,0 +1,37 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/type/latlng;latlng"; +option java_multiple_files = true; +option java_outer_classname = "LatLngProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// 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 must conform to the +// WGS84 +// standard. Values must be within normalized ranges. +message LatLng { + // The latitude in degrees. It must be in the range [-90.0, +90.0]. + double latitude = 1; + + // The longitude in degrees. It must be in the range [-180.0, +180.0]. + double longitude = 2; +} diff --git a/handwritten/firestore/dev/protos/update.sh b/handwritten/firestore/dev/protos/update.sh new file mode 100755 index 00000000000..74a21233bce --- /dev/null +++ b/handwritten/firestore/dev/protos/update.sh @@ -0,0 +1,157 @@ +#!/bin/bash + +# Copyright 2018 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -euo pipefail +IFS=$'\n\t' + +echo "Running update.sh" +echo $(npm --version) +# Variables +PROTOS_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +WORK_DIR=`mktemp -d` +cd ${PROTOS_DIR} + +# deletes the temp directory on exit +function cleanup { + rm -rf "$WORK_DIR" + echo "Deleted temp working directory $WORK_DIR" +} + +# register the cleanup function to be called on the EXIT signal +trap cleanup EXIT + +# Capture location of pbjs / pbts before we pushd. +PBJS="$(npm root)/.bin/pbjs" +PBTS="$(npm root)/.bin/pbts" + +# Enter work dir +pushd "$WORK_DIR" + +# Clone necessary git repos. +# If the USE_PREVIEW_BRANCH environment variable is set, clone the 'preview' branch. +if [[ -n "${USE_PREVIEW_BRANCH-}" ]]; then + echo "Cloning 'preview' branch of googleapis.git..." + git clone --depth 1 --branch preview https://github.com/googleapis/googleapis.git +else + echo "Cloning default branch of googleapis.git..." + git clone --depth 1 https://github.com/googleapis/googleapis.git +fi +# Protobuf may have breaking changes, so it will be pinned to a specific release. +# TODO(version) nodejs-firestore should maintain the version number of protobuf manually +git clone --single-branch --branch v26.1 --depth 1 https://github.com/google/protobuf.git + +# Copy necessary protos. +mkdir -p "${PROTOS_DIR}/google/api" +cp googleapis/google/api/{annotations,client,field_behavior,http,launch_stage,resource,routing}.proto \ + "${PROTOS_DIR}/google/api/" + +mkdir -p "${PROTOS_DIR}/google/firestore/v1" +cp googleapis/google/firestore/v1/*.proto \ + "${PROTOS_DIR}/google/firestore/v1/" + +# If the USE_PREVIEW_BRANCH environment variable is set, skip v1beta1. +# v1beta1/ does not exist in the 'preview' branch +mkdir -p "${PROTOS_DIR}/google/firestore/v1beta1" +if [[ -n "${USE_PREVIEW_BRANCH-}" ]]; then + echo "Skipping v1beta1 for 'preview' branch" +else + cp googleapis/google/firestore/v1beta1/*.proto \ + "${PROTOS_DIR}/google/firestore/v1beta1/" +fi + +mkdir -p "${PROTOS_DIR}/google/firestore/admin/v1" +cp googleapis/google/firestore/admin/v1/*.proto \ + "${PROTOS_DIR}/google/firestore/admin/v1/" + +mkdir -p "${PROTOS_DIR}/google/longrunning" +cp googleapis/google/longrunning/operations.proto \ + "${PROTOS_DIR}/google/longrunning/" + +mkdir -p "${PROTOS_DIR}/google/rpc" +cp googleapis/google/rpc/status.proto \ + "${PROTOS_DIR}/google/rpc/" + +mkdir -p "${PROTOS_DIR}/google/type" +cp googleapis/google/type/{latlng,dayofweek}.proto \ + "${PROTOS_DIR}/google/type/" + +mkdir -p "${PROTOS_DIR}/google/protobuf" +cp protobuf/src/google/protobuf/{any,descriptor,empty,field_mask,struct,timestamp,wrappers,duration}.proto \ + "${PROTOS_DIR}/google/protobuf/" + +popd + +# Generate the Protobuf typings +PBJS_ARGS=( -p . \ + --js_out=import_style=commonjs,binary:library \ + --target=static-module \ + --no-create \ + --no-encode \ + --no-decode \ + --no-verify \ + --no-delimited \ + --force-enum-string) + +"${PBJS}" "${PBJS_ARGS[@]}" -o firestore_v1_proto_api.js \ + -r firestore_v1 \ + "google/firestore/v1/*.proto" \ + "firestore/*.proto" \ + "google/protobuf/*.proto" "google/type/*.proto" \ + "google/rpc/*.proto" "google/api/*.proto" \ + "google/longrunning/*.proto" +perl -pi -e 's/number\|Long/number\|string/g' firestore_v1_proto_api.js +"${PBTS}" -o firestore_v1_proto_api.d.ts firestore_v1_proto_api.js + +"${PBJS}" "${PBJS_ARGS[@]}" -o firestore_admin_v1_proto_api.js \ + -r firestore_admin_v1 \ + "google/firestore/admin/v1/*.proto" \ + "google/protobuf/*.proto" "google/type/*.proto" \ + "google/rpc/*.proto" "google/api/*.proto" \ + "google/longrunning/*.proto" +perl -pi -e 's/number\|Long/number\|string/g' firestore_admin_v1_proto_api.js +"${PBTS}" -o firestore_admin_v1_proto_api.d.ts firestore_admin_v1_proto_api.js + +"${PBJS}" "${PBJS_ARGS[@]}" -o firestore_v1beta1_proto_api.js \ + -r firestore_v1beta1 \ + "google/firestore/v1beta1/*.proto" \ + "google/protobuf/*.proto" "google/type/*.proto" \ + "google/rpc/*.proto" "google/api/*.proto" \ + "google/longrunning/*.proto" +perl -pi -e 's/number\|Long/number\|string/g' firestore_v1beta1_proto_api.js +"${PBTS}" -o firestore_v1beta1_proto_api.d.ts firestore_v1beta1_proto_api.js + +"${PBJS}" -p . --target=json -o v1.json \ + -r firestore_v1 \ + "google/firestore/v1/*.proto" \ + "google/protobuf/*.proto" "google/type/*.proto" \ + "google/rpc/*.proto" "google/api/*.proto" + +"${PBJS}" -p . --target=json -o admin_v1.json \ + -r firestore_admin_v1 \ + "google/firestore/admin/v1/*.proto" \ + "google/protobuf/*.proto" "google/type/*.proto" \ + "google/rpc/*.proto" "google/api/*.proto" \ + "google/longrunning/*.proto" + +"${PBJS}" -p . --target=json -o v1beta1.json \ + -r firestore_v1beta1 \ + "google/firestore/v1beta1/*.proto" \ + "google/protobuf/*.proto" "google/type/*.proto" \ + "google/rpc/*.proto" "google/api/*.proto" + +echo "Finished running update.sh" + +node ../../scripts/license.js ../../build ../protos diff --git a/handwritten/firestore/dev/protos/v1.json b/handwritten/firestore/dev/protos/v1.json new file mode 100644 index 00000000000..465e1689ff3 --- /dev/null +++ b/handwritten/firestore/dev/protos/v1.json @@ -0,0 +1,4323 @@ +{ + "nested": { + "google": { + "nested": { + "firestore": { + "nested": { + "v1": { + "options": { + "csharp_namespace": "Google.Cloud.Firestore.V1", + "go_package": "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb", + "java_multiple_files": true, + "java_outer_classname": "WriteProto", + "java_package": "com.google.firestore.v1", + "objc_class_prefix": "GCFS", + "php_namespace": "Google\\Cloud\\Firestore\\V1", + "ruby_package": "Google::Cloud::Firestore::V1" + }, + "nested": { + "AggregationResult": { + "fields": { + "aggregateFields": { + "keyType": "string", + "type": "Value", + "id": 2 + } + } + }, + "Document": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "fields": { + "keyType": "string", + "type": "Value", + "id": 2 + }, + "createTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + }, + "updateTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + } + } + }, + "Value": { + "oneofs": { + "valueType": { + "oneof": [ + "nullValue", + "booleanValue", + "integerValue", + "doubleValue", + "timestampValue", + "stringValue", + "bytesValue", + "referenceValue", + "geoPointValue", + "arrayValue", + "mapValue", + "fieldReferenceValue", + "functionValue", + "pipelineValue" + ] + } + }, + "fields": { + "nullValue": { + "type": "google.protobuf.NullValue", + "id": 11 + }, + "booleanValue": { + "type": "bool", + "id": 1 + }, + "integerValue": { + "type": "int64", + "id": 2 + }, + "doubleValue": { + "type": "double", + "id": 3 + }, + "timestampValue": { + "type": "google.protobuf.Timestamp", + "id": 10 + }, + "stringValue": { + "type": "string", + "id": 17 + }, + "bytesValue": { + "type": "bytes", + "id": 18 + }, + "referenceValue": { + "type": "string", + "id": 5 + }, + "geoPointValue": { + "type": "google.type.LatLng", + "id": 8 + }, + "arrayValue": { + "type": "ArrayValue", + "id": 9 + }, + "mapValue": { + "type": "MapValue", + "id": 6 + }, + "fieldReferenceValue": { + "type": "string", + "id": 19 + }, + "functionValue": { + "type": "Function", + "id": 20 + }, + "pipelineValue": { + "type": "Pipeline", + "id": 21 + } + } + }, + "ArrayValue": { + "fields": { + "values": { + "rule": "repeated", + "type": "Value", + "id": 1 + } + } + }, + "MapValue": { + "fields": { + "fields": { + "keyType": "string", + "type": "Value", + "id": 1 + } + } + }, + "Function": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "args": { + "rule": "repeated", + "type": "Value", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "options": { + "keyType": "string", + "type": "Value", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "Pipeline": { + "fields": { + "stages": { + "rule": "repeated", + "type": "Stage", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + }, + "nested": { + "Stage": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "args": { + "rule": "repeated", + "type": "Value", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "options": { + "keyType": "string", + "type": "Value", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + } + } + }, + "BitSequence": { + "fields": { + "bitmap": { + "type": "bytes", + "id": 1 + }, + "padding": { + "type": "int32", + "id": 2 + } + } + }, + "BloomFilter": { + "fields": { + "bits": { + "type": "BitSequence", + "id": 1 + }, + "hashCount": { + "type": "int32", + "id": 2 + } + } + }, + "DocumentMask": { + "fields": { + "fieldPaths": { + "rule": "repeated", + "type": "string", + "id": 1 + } + } + }, + "Precondition": { + "oneofs": { + "conditionType": { + "oneof": [ + "exists", + "updateTime" + ] + } + }, + "fields": { + "exists": { + "type": "bool", + "id": 1 + }, + "updateTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + } + } + }, + "TransactionOptions": { + "oneofs": { + "mode": { + "oneof": [ + "readOnly", + "readWrite" + ] + } + }, + "fields": { + "readOnly": { + "type": "ReadOnly", + "id": 2 + }, + "readWrite": { + "type": "ReadWrite", + "id": 3 + } + }, + "nested": { + "ReadWrite": { + "fields": { + "retryTransaction": { + "type": "bytes", + "id": 1 + } + } + }, + "ReadOnly": { + "oneofs": { + "consistencySelector": { + "oneof": [ + "readTime" + ] + } + }, + "fields": { + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + } + } + } + } + }, + "ExplainStats": { + "fields": { + "data": { + "type": "google.protobuf.Any", + "id": 1 + } + } + }, + "Firestore": { + "options": { + "(google.api.default_host)": "firestore.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/datastore" + }, + "methods": { + "GetDocument": { + "requestType": "GetDocumentRequest", + "responseType": "Document", + "options": { + "(google.api.http).get": "/v1/{name=projects/*/databases/*/documents/*/**}" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=projects/*/databases/*/documents/*/**}" + } + } + ] + }, + "ListDocuments": { + "requestType": "ListDocumentsRequest", + "responseType": "ListDocumentsResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}", + "(google.api.http).additional_bindings.get": "/v1/{parent=projects/*/databases/*/documents}/{collection_id}" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}", + "additional_bindings": { + "get": "/v1/{parent=projects/*/databases/*/documents}/{collection_id}" + } + } + } + ] + }, + "UpdateDocument": { + "requestType": "UpdateDocumentRequest", + "responseType": "Document", + "options": { + "(google.api.http).patch": "/v1/{document.name=projects/*/databases/*/documents/*/**}", + "(google.api.http).body": "document", + "(google.api.method_signature)": "document,update_mask" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "patch": "/v1/{document.name=projects/*/databases/*/documents/*/**}", + "body": "document" + } + }, + { + "(google.api.method_signature)": "document,update_mask" + } + ] + }, + "DeleteDocument": { + "requestType": "DeleteDocumentRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=projects/*/databases/*/documents/*/**}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=projects/*/databases/*/documents/*/**}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "BatchGetDocuments": { + "requestType": "BatchGetDocumentsRequest", + "responseType": "BatchGetDocumentsResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:batchGet", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/databases/*}/documents:batchGet", + "body": "*" + } + } + ] + }, + "BeginTransaction": { + "requestType": "BeginTransactionRequest", + "responseType": "BeginTransactionResponse", + "options": { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:beginTransaction", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/databases/*}/documents:beginTransaction", + "body": "*" + } + }, + { + "(google.api.method_signature)": "database" + } + ] + }, + "Commit": { + "requestType": "CommitRequest", + "responseType": "CommitResponse", + "options": { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:commit", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database,writes" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/databases/*}/documents:commit", + "body": "*" + } + }, + { + "(google.api.method_signature)": "database,writes" + } + ] + }, + "Rollback": { + "requestType": "RollbackRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:rollback", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database,transaction" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/databases/*}/documents:rollback", + "body": "*" + } + }, + { + "(google.api.method_signature)": "database,transaction" + } + ] + }, + "RunQuery": { + "requestType": "RunQueryRequest", + "responseType": "RunQueryResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:runQuery", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runQuery", + "(google.api.http).additional_bindings.body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/databases/*/documents}:runQuery", + "body": "*", + "additional_bindings": { + "post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runQuery", + "body": "*" + } + } + } + ] + }, + "ExecutePipeline": { + "requestType": "ExecutePipelineRequest", + "responseType": "ExecutePipelineResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:executePipeline", + "(google.api.http).body": "*", + "(google.api.routing).routing_parameters.field": "database", + "(google.api.routing).routing_parameters.path_template": "projects/*/databases/{database_id=*}/**" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/databases/*}/documents:executePipeline", + "body": "*" + } + }, + { + "(google.api.routing)": { + "routing_parameters": [ + { + "field": "database", + "path_template": "projects/{project_id=*}/**" + }, + { + "field": "database", + "path_template": "projects/*/databases/{database_id=*}/**" + } + ] + } + } + ] + }, + "RunAggregationQuery": { + "requestType": "RunAggregationQueryRequest", + "responseType": "RunAggregationQueryResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:runAggregationQuery", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runAggregationQuery", + "(google.api.http).additional_bindings.body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/databases/*/documents}:runAggregationQuery", + "body": "*", + "additional_bindings": { + "post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runAggregationQuery", + "body": "*" + } + } + } + ] + }, + "PartitionQuery": { + "requestType": "PartitionQueryRequest", + "responseType": "PartitionQueryResponse", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:partitionQuery", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery", + "(google.api.http).additional_bindings.body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/databases/*/documents}:partitionQuery", + "body": "*", + "additional_bindings": { + "post": "/v1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery", + "body": "*" + } + } + } + ] + }, + "Write": { + "requestType": "WriteRequest", + "requestStream": true, + "responseType": "WriteResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:write", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/databases/*}/documents:write", + "body": "*" + } + } + ] + }, + "Listen": { + "requestType": "ListenRequest", + "requestStream": true, + "responseType": "ListenResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:listen", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/databases/*}/documents:listen", + "body": "*" + } + } + ] + }, + "ListCollectionIds": { + "requestType": "ListCollectionIdsRequest", + "responseType": "ListCollectionIdsResponse", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:listCollectionIds", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds", + "(google.api.http).additional_bindings.body": "*", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/databases/*/documents}:listCollectionIds", + "body": "*", + "additional_bindings": { + "post": "/v1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds", + "body": "*" + } + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "BatchWrite": { + "requestType": "BatchWriteRequest", + "responseType": "BatchWriteResponse", + "options": { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:batchWrite", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/databases/*}/documents:batchWrite", + "body": "*" + } + } + ] + }, + "CreateDocument": { + "requestType": "CreateDocumentRequest", + "responseType": "Document", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents/**}/{collection_id}", + "(google.api.http).body": "document" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/databases/*/documents/**}/{collection_id}", + "body": "document" + } + } + ] + } + } + }, + "GetDocumentRequest": { + "oneofs": { + "consistencySelector": { + "oneof": [ + "transaction", + "readTime" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "mask": { + "type": "DocumentMask", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 3 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 5 + } + } + }, + "ListDocumentsRequest": { + "oneofs": { + "consistencySelector": { + "oneof": [ + "transaction", + "readTime" + ] + } + }, + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "collectionId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pageSize": { + "type": "int32", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pageToken": { + "type": "string", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "orderBy": { + "type": "string", + "id": 6, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "mask": { + "type": "DocumentMask", + "id": 7, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "transaction": { + "type": "bytes", + "id": 8 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 10 + }, + "showMissing": { + "type": "bool", + "id": 12 + } + } + }, + "ListDocumentsResponse": { + "fields": { + "documents": { + "rule": "repeated", + "type": "Document", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "CreateDocumentRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "collectionId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "documentId": { + "type": "string", + "id": 3 + }, + "document": { + "type": "Document", + "id": 4, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "mask": { + "type": "DocumentMask", + "id": 5 + } + } + }, + "UpdateDocumentRequest": { + "fields": { + "document": { + "type": "Document", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "updateMask": { + "type": "DocumentMask", + "id": 2 + }, + "mask": { + "type": "DocumentMask", + "id": 3 + }, + "currentDocument": { + "type": "Precondition", + "id": 4 + } + } + }, + "DeleteDocumentRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "currentDocument": { + "type": "Precondition", + "id": 2 + } + } + }, + "BatchGetDocumentsRequest": { + "oneofs": { + "consistencySelector": { + "oneof": [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "documents": { + "rule": "repeated", + "type": "string", + "id": 2 + }, + "mask": { + "type": "DocumentMask", + "id": 3 + }, + "transaction": { + "type": "bytes", + "id": 4 + }, + "newTransaction": { + "type": "TransactionOptions", + "id": 5 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 7 + } + } + }, + "BatchGetDocumentsResponse": { + "oneofs": { + "result": { + "oneof": [ + "found", + "missing" + ] + } + }, + "fields": { + "found": { + "type": "Document", + "id": 1 + }, + "missing": { + "type": "string", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 3 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + } + } + }, + "BeginTransactionRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "options": { + "type": "TransactionOptions", + "id": 2 + } + } + }, + "BeginTransactionResponse": { + "fields": { + "transaction": { + "type": "bytes", + "id": 1 + } + } + }, + "CommitRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "writes": { + "rule": "repeated", + "type": "Write", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 3 + } + } + }, + "CommitResponse": { + "fields": { + "writeResults": { + "rule": "repeated", + "type": "WriteResult", + "id": 1 + }, + "commitTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + } + } + }, + "RollbackRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "transaction": { + "type": "bytes", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "RunQueryRequest": { + "oneofs": { + "queryType": { + "oneof": [ + "structuredQuery" + ] + }, + "consistencySelector": { + "oneof": [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "structuredQuery": { + "type": "StructuredQuery", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 5 + }, + "newTransaction": { + "type": "TransactionOptions", + "id": 6 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 7 + }, + "explainOptions": { + "type": "ExplainOptions", + "id": 10, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "RunQueryResponse": { + "oneofs": { + "continuationSelector": { + "oneof": [ + "done" + ] + } + }, + "fields": { + "transaction": { + "type": "bytes", + "id": 2 + }, + "document": { + "type": "Document", + "id": 1 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + }, + "skippedResults": { + "type": "int32", + "id": 4 + }, + "done": { + "type": "bool", + "id": 6 + }, + "explainMetrics": { + "type": "ExplainMetrics", + "id": 11 + } + } + }, + "ExecutePipelineRequest": { + "oneofs": { + "pipelineType": { + "oneof": [ + "structuredPipeline" + ] + }, + "consistencySelector": { + "oneof": [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "structuredPipeline": { + "type": "StructuredPipeline", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 5 + }, + "newTransaction": { + "type": "TransactionOptions", + "id": 6 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 7 + } + } + }, + "ExecutePipelineResponse": { + "fields": { + "transaction": { + "type": "bytes", + "id": 1 + }, + "results": { + "rule": "repeated", + "type": "Document", + "id": 2 + }, + "executionTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + }, + "explainStats": { + "type": "ExplainStats", + "id": 4 + } + } + }, + "RunAggregationQueryRequest": { + "oneofs": { + "queryType": { + "oneof": [ + "structuredAggregationQuery" + ] + }, + "consistencySelector": { + "oneof": [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "structuredAggregationQuery": { + "type": "StructuredAggregationQuery", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 4 + }, + "newTransaction": { + "type": "TransactionOptions", + "id": 5 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 6 + }, + "explainOptions": { + "type": "ExplainOptions", + "id": 8, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "RunAggregationQueryResponse": { + "fields": { + "result": { + "type": "AggregationResult", + "id": 1 + }, + "transaction": { + "type": "bytes", + "id": 2 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + }, + "explainMetrics": { + "type": "ExplainMetrics", + "id": 10 + } + } + }, + "PartitionQueryRequest": { + "oneofs": { + "queryType": { + "oneof": [ + "structuredQuery" + ] + }, + "consistencySelector": { + "oneof": [ + "readTime" + ] + } + }, + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "structuredQuery": { + "type": "StructuredQuery", + "id": 2 + }, + "partitionCount": { + "type": "int64", + "id": 3 + }, + "pageToken": { + "type": "string", + "id": 4 + }, + "pageSize": { + "type": "int32", + "id": 5 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 6 + } + } + }, + "PartitionQueryResponse": { + "fields": { + "partitions": { + "rule": "repeated", + "type": "Cursor", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "WriteRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "streamId": { + "type": "string", + "id": 2 + }, + "writes": { + "rule": "repeated", + "type": "Write", + "id": 3 + }, + "streamToken": { + "type": "bytes", + "id": 4 + }, + "labels": { + "keyType": "string", + "type": "string", + "id": 5 + } + } + }, + "WriteResponse": { + "fields": { + "streamId": { + "type": "string", + "id": 1 + }, + "streamToken": { + "type": "bytes", + "id": 2 + }, + "writeResults": { + "rule": "repeated", + "type": "WriteResult", + "id": 3 + }, + "commitTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + } + } + }, + "ListenRequest": { + "oneofs": { + "targetChange": { + "oneof": [ + "addTarget", + "removeTarget" + ] + } + }, + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "addTarget": { + "type": "Target", + "id": 2 + }, + "removeTarget": { + "type": "int32", + "id": 3 + }, + "labels": { + "keyType": "string", + "type": "string", + "id": 4 + } + } + }, + "ListenResponse": { + "oneofs": { + "responseType": { + "oneof": [ + "targetChange", + "documentChange", + "documentDelete", + "documentRemove", + "filter" + ] + } + }, + "fields": { + "targetChange": { + "type": "TargetChange", + "id": 2 + }, + "documentChange": { + "type": "DocumentChange", + "id": 3 + }, + "documentDelete": { + "type": "DocumentDelete", + "id": 4 + }, + "documentRemove": { + "type": "DocumentRemove", + "id": 6 + }, + "filter": { + "type": "ExistenceFilter", + "id": 5 + } + } + }, + "Target": { + "oneofs": { + "targetType": { + "oneof": [ + "query", + "documents" + ] + }, + "resumeType": { + "oneof": [ + "resumeToken", + "readTime" + ] + } + }, + "fields": { + "query": { + "type": "QueryTarget", + "id": 2 + }, + "documents": { + "type": "DocumentsTarget", + "id": 3 + }, + "resumeToken": { + "type": "bytes", + "id": 4 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 11 + }, + "targetId": { + "type": "int32", + "id": 5 + }, + "once": { + "type": "bool", + "id": 6 + }, + "expectedCount": { + "type": "google.protobuf.Int32Value", + "id": 12 + } + }, + "nested": { + "DocumentsTarget": { + "fields": { + "documents": { + "rule": "repeated", + "type": "string", + "id": 2 + } + } + }, + "QueryTarget": { + "oneofs": { + "queryType": { + "oneof": [ + "structuredQuery" + ] + } + }, + "fields": { + "parent": { + "type": "string", + "id": 1 + }, + "structuredQuery": { + "type": "StructuredQuery", + "id": 2 + } + } + } + } + }, + "TargetChange": { + "fields": { + "targetChangeType": { + "type": "TargetChangeType", + "id": 1 + }, + "targetIds": { + "rule": "repeated", + "type": "int32", + "id": 2 + }, + "cause": { + "type": "google.rpc.Status", + "id": 3 + }, + "resumeToken": { + "type": "bytes", + "id": 4 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 6 + } + }, + "nested": { + "TargetChangeType": { + "values": { + "NO_CHANGE": 0, + "ADD": 1, + "REMOVE": 2, + "CURRENT": 3, + "RESET": 4 + } + } + } + }, + "ListCollectionIdsRequest": { + "oneofs": { + "consistencySelector": { + "oneof": [ + "readTime" + ] + } + }, + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "pageSize": { + "type": "int32", + "id": 2 + }, + "pageToken": { + "type": "string", + "id": 3 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + } + } + }, + "ListCollectionIdsResponse": { + "fields": { + "collectionIds": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "BatchWriteRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "writes": { + "rule": "repeated", + "type": "Write", + "id": 2 + }, + "labels": { + "keyType": "string", + "type": "string", + "id": 3 + } + } + }, + "BatchWriteResponse": { + "fields": { + "writeResults": { + "rule": "repeated", + "type": "WriteResult", + "id": 1 + }, + "status": { + "rule": "repeated", + "type": "google.rpc.Status", + "id": 2 + } + } + }, + "StructuredPipeline": { + "fields": { + "pipeline": { + "type": "Pipeline", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "options": { + "keyType": "string", + "type": "Value", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "StructuredQuery": { + "fields": { + "select": { + "type": "Projection", + "id": 1 + }, + "from": { + "rule": "repeated", + "type": "CollectionSelector", + "id": 2 + }, + "where": { + "type": "Filter", + "id": 3 + }, + "orderBy": { + "rule": "repeated", + "type": "Order", + "id": 4 + }, + "startAt": { + "type": "Cursor", + "id": 7 + }, + "endAt": { + "type": "Cursor", + "id": 8 + }, + "offset": { + "type": "int32", + "id": 6 + }, + "limit": { + "type": "google.protobuf.Int32Value", + "id": 5 + }, + "findNearest": { + "type": "FindNearest", + "id": 9, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "CollectionSelector": { + "fields": { + "collectionId": { + "type": "string", + "id": 2 + }, + "allDescendants": { + "type": "bool", + "id": 3 + } + } + }, + "Filter": { + "oneofs": { + "filterType": { + "oneof": [ + "compositeFilter", + "fieldFilter", + "unaryFilter" + ] + } + }, + "fields": { + "compositeFilter": { + "type": "CompositeFilter", + "id": 1 + }, + "fieldFilter": { + "type": "FieldFilter", + "id": 2 + }, + "unaryFilter": { + "type": "UnaryFilter", + "id": 3 + } + } + }, + "CompositeFilter": { + "fields": { + "op": { + "type": "Operator", + "id": 1 + }, + "filters": { + "rule": "repeated", + "type": "Filter", + "id": 2 + } + }, + "nested": { + "Operator": { + "values": { + "OPERATOR_UNSPECIFIED": 0, + "AND": 1, + "OR": 2 + } + } + } + }, + "FieldFilter": { + "fields": { + "field": { + "type": "FieldReference", + "id": 1 + }, + "op": { + "type": "Operator", + "id": 2 + }, + "value": { + "type": "Value", + "id": 3 + } + }, + "nested": { + "Operator": { + "values": { + "OPERATOR_UNSPECIFIED": 0, + "LESS_THAN": 1, + "LESS_THAN_OR_EQUAL": 2, + "GREATER_THAN": 3, + "GREATER_THAN_OR_EQUAL": 4, + "EQUAL": 5, + "NOT_EQUAL": 6, + "ARRAY_CONTAINS": 7, + "IN": 8, + "ARRAY_CONTAINS_ANY": 9, + "NOT_IN": 10 + } + } + } + }, + "UnaryFilter": { + "oneofs": { + "operandType": { + "oneof": [ + "field" + ] + } + }, + "fields": { + "op": { + "type": "Operator", + "id": 1 + }, + "field": { + "type": "FieldReference", + "id": 2 + } + }, + "nested": { + "Operator": { + "values": { + "OPERATOR_UNSPECIFIED": 0, + "IS_NAN": 2, + "IS_NULL": 3, + "IS_NOT_NAN": 4, + "IS_NOT_NULL": 5 + } + } + } + }, + "Order": { + "fields": { + "field": { + "type": "FieldReference", + "id": 1 + }, + "direction": { + "type": "Direction", + "id": 2 + } + } + }, + "Direction": { + "values": { + "DIRECTION_UNSPECIFIED": 0, + "ASCENDING": 1, + "DESCENDING": 2 + } + }, + "FieldReference": { + "fields": { + "fieldPath": { + "type": "string", + "id": 2 + } + } + }, + "Projection": { + "fields": { + "fields": { + "rule": "repeated", + "type": "FieldReference", + "id": 2 + } + } + }, + "FindNearest": { + "fields": { + "vectorField": { + "type": "FieldReference", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "queryVector": { + "type": "Value", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "distanceMeasure": { + "type": "DistanceMeasure", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "limit": { + "type": "google.protobuf.Int32Value", + "id": 4, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "distanceResultField": { + "type": "string", + "id": 5, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "distanceThreshold": { + "type": "google.protobuf.DoubleValue", + "id": 6, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "DistanceMeasure": { + "values": { + "DISTANCE_MEASURE_UNSPECIFIED": 0, + "EUCLIDEAN": 1, + "COSINE": 2, + "DOT_PRODUCT": 3 + } + } + } + } + } + }, + "StructuredAggregationQuery": { + "oneofs": { + "queryType": { + "oneof": [ + "structuredQuery" + ] + } + }, + "fields": { + "structuredQuery": { + "type": "StructuredQuery", + "id": 1 + }, + "aggregations": { + "rule": "repeated", + "type": "Aggregation", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "Aggregation": { + "oneofs": { + "operator": { + "oneof": [ + "count", + "sum", + "avg" + ] + } + }, + "fields": { + "count": { + "type": "Count", + "id": 1 + }, + "sum": { + "type": "Sum", + "id": 2 + }, + "avg": { + "type": "Avg", + "id": 3 + }, + "alias": { + "type": "string", + "id": 7, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "Count": { + "fields": { + "upTo": { + "type": "google.protobuf.Int64Value", + "id": 1, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "Sum": { + "fields": { + "field": { + "type": "StructuredQuery.FieldReference", + "id": 1 + } + } + }, + "Avg": { + "fields": { + "field": { + "type": "StructuredQuery.FieldReference", + "id": 1 + } + } + } + } + } + } + }, + "Cursor": { + "fields": { + "values": { + "rule": "repeated", + "type": "Value", + "id": 1 + }, + "before": { + "type": "bool", + "id": 2 + } + } + }, + "ExplainOptions": { + "fields": { + "analyze": { + "type": "bool", + "id": 1, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "ExplainMetrics": { + "fields": { + "planSummary": { + "type": "PlanSummary", + "id": 1 + }, + "executionStats": { + "type": "ExecutionStats", + "id": 2 + } + } + }, + "PlanSummary": { + "fields": { + "indexesUsed": { + "rule": "repeated", + "type": "google.protobuf.Struct", + "id": 1 + } + } + }, + "ExecutionStats": { + "fields": { + "resultsReturned": { + "type": "int64", + "id": 1 + }, + "executionDuration": { + "type": "google.protobuf.Duration", + "id": 3 + }, + "readOperations": { + "type": "int64", + "id": 4 + }, + "debugStats": { + "type": "google.protobuf.Struct", + "id": 5 + } + } + }, + "Write": { + "oneofs": { + "operation": { + "oneof": [ + "update", + "delete", + "transform" + ] + } + }, + "fields": { + "update": { + "type": "Document", + "id": 1 + }, + "delete": { + "type": "string", + "id": 2 + }, + "transform": { + "type": "DocumentTransform", + "id": 6 + }, + "updateMask": { + "type": "DocumentMask", + "id": 3 + }, + "updateTransforms": { + "rule": "repeated", + "type": "DocumentTransform.FieldTransform", + "id": 7 + }, + "currentDocument": { + "type": "Precondition", + "id": 4 + } + } + }, + "DocumentTransform": { + "fields": { + "document": { + "type": "string", + "id": 1 + }, + "fieldTransforms": { + "rule": "repeated", + "type": "FieldTransform", + "id": 2 + } + }, + "nested": { + "FieldTransform": { + "oneofs": { + "transformType": { + "oneof": [ + "setToServerValue", + "increment", + "maximum", + "minimum", + "appendMissingElements", + "removeAllFromArray" + ] + } + }, + "fields": { + "fieldPath": { + "type": "string", + "id": 1 + }, + "setToServerValue": { + "type": "ServerValue", + "id": 2 + }, + "increment": { + "type": "Value", + "id": 3 + }, + "maximum": { + "type": "Value", + "id": 4 + }, + "minimum": { + "type": "Value", + "id": 5 + }, + "appendMissingElements": { + "type": "ArrayValue", + "id": 6 + }, + "removeAllFromArray": { + "type": "ArrayValue", + "id": 7 + } + }, + "nested": { + "ServerValue": { + "values": { + "SERVER_VALUE_UNSPECIFIED": 0, + "REQUEST_TIME": 1 + } + } + } + } + } + }, + "WriteResult": { + "fields": { + "updateTime": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "transformResults": { + "rule": "repeated", + "type": "Value", + "id": 2 + } + } + }, + "DocumentChange": { + "fields": { + "document": { + "type": "Document", + "id": 1 + }, + "targetIds": { + "rule": "repeated", + "type": "int32", + "id": 5 + }, + "removedTargetIds": { + "rule": "repeated", + "type": "int32", + "id": 6 + } + } + }, + "DocumentDelete": { + "fields": { + "document": { + "type": "string", + "id": 1 + }, + "removedTargetIds": { + "rule": "repeated", + "type": "int32", + "id": 6 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + } + } + }, + "DocumentRemove": { + "fields": { + "document": { + "type": "string", + "id": 1 + }, + "removedTargetIds": { + "rule": "repeated", + "type": "int32", + "id": 2 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + } + } + }, + "ExistenceFilter": { + "fields": { + "targetId": { + "type": "int32", + "id": 1 + }, + "count": { + "type": "int32", + "id": 2 + }, + "unchangedNames": { + "type": "BloomFilter", + "id": 3 + } + } + } + } + } + } + }, + "api": { + "options": { + "go_package": "google.golang.org/genproto/googleapis/api/annotations;annotations", + "java_multiple_files": true, + "java_outer_classname": "ResourceProto", + "java_package": "com.google.api", + "objc_class_prefix": "GAPI" + }, + "nested": { + "fieldBehavior": { + "rule": "repeated", + "type": "google.api.FieldBehavior", + "id": 1052, + "extend": "google.protobuf.FieldOptions", + "options": { + "packed": false + } + }, + "FieldBehavior": { + "values": { + "FIELD_BEHAVIOR_UNSPECIFIED": 0, + "OPTIONAL": 1, + "REQUIRED": 2, + "OUTPUT_ONLY": 3, + "INPUT_ONLY": 4, + "IMMUTABLE": 5, + "UNORDERED_LIST": 6, + "NON_EMPTY_DEFAULT": 7, + "IDENTIFIER": 8 + } + }, + "http": { + "type": "HttpRule", + "id": 72295728, + "extend": "google.protobuf.MethodOptions" + }, + "Http": { + "fields": { + "rules": { + "rule": "repeated", + "type": "HttpRule", + "id": 1 + }, + "fullyDecodeReservedExpansion": { + "type": "bool", + "id": 2 + } + } + }, + "HttpRule": { + "oneofs": { + "pattern": { + "oneof": [ + "get", + "put", + "post", + "delete", + "patch", + "custom" + ] + } + }, + "fields": { + "selector": { + "type": "string", + "id": 1 + }, + "get": { + "type": "string", + "id": 2 + }, + "put": { + "type": "string", + "id": 3 + }, + "post": { + "type": "string", + "id": 4 + }, + "delete": { + "type": "string", + "id": 5 + }, + "patch": { + "type": "string", + "id": 6 + }, + "custom": { + "type": "CustomHttpPattern", + "id": 8 + }, + "body": { + "type": "string", + "id": 7 + }, + "responseBody": { + "type": "string", + "id": 12 + }, + "additionalBindings": { + "rule": "repeated", + "type": "HttpRule", + "id": 11 + } + } + }, + "CustomHttpPattern": { + "fields": { + "kind": { + "type": "string", + "id": 1 + }, + "path": { + "type": "string", + "id": 2 + } + } + }, + "methodSignature": { + "rule": "repeated", + "type": "string", + "id": 1051, + "extend": "google.protobuf.MethodOptions" + }, + "defaultHost": { + "type": "string", + "id": 1049, + "extend": "google.protobuf.ServiceOptions" + }, + "oauthScopes": { + "type": "string", + "id": 1050, + "extend": "google.protobuf.ServiceOptions" + }, + "apiVersion": { + "type": "string", + "id": 525000001, + "extend": "google.protobuf.ServiceOptions" + }, + "CommonLanguageSettings": { + "fields": { + "referenceDocsUri": { + "type": "string", + "id": 1, + "options": { + "deprecated": true + } + }, + "destinations": { + "rule": "repeated", + "type": "ClientLibraryDestination", + "id": 2 + }, + "selectiveGapicGeneration": { + "type": "SelectiveGapicGeneration", + "id": 3 + } + } + }, + "ClientLibrarySettings": { + "fields": { + "version": { + "type": "string", + "id": 1 + }, + "launchStage": { + "type": "LaunchStage", + "id": 2 + }, + "restNumericEnums": { + "type": "bool", + "id": 3 + }, + "javaSettings": { + "type": "JavaSettings", + "id": 21 + }, + "cppSettings": { + "type": "CppSettings", + "id": 22 + }, + "phpSettings": { + "type": "PhpSettings", + "id": 23 + }, + "pythonSettings": { + "type": "PythonSettings", + "id": 24 + }, + "nodeSettings": { + "type": "NodeSettings", + "id": 25 + }, + "dotnetSettings": { + "type": "DotnetSettings", + "id": 26 + }, + "rubySettings": { + "type": "RubySettings", + "id": 27 + }, + "goSettings": { + "type": "GoSettings", + "id": 28 + } + } + }, + "Publishing": { + "fields": { + "methodSettings": { + "rule": "repeated", + "type": "MethodSettings", + "id": 2 + }, + "newIssueUri": { + "type": "string", + "id": 101 + }, + "documentationUri": { + "type": "string", + "id": 102 + }, + "apiShortName": { + "type": "string", + "id": 103 + }, + "githubLabel": { + "type": "string", + "id": 104 + }, + "codeownerGithubTeams": { + "rule": "repeated", + "type": "string", + "id": 105 + }, + "docTagPrefix": { + "type": "string", + "id": 106 + }, + "organization": { + "type": "ClientLibraryOrganization", + "id": 107 + }, + "librarySettings": { + "rule": "repeated", + "type": "ClientLibrarySettings", + "id": 109 + }, + "protoReferenceDocumentationUri": { + "type": "string", + "id": 110 + }, + "restReferenceDocumentationUri": { + "type": "string", + "id": 111 + } + } + }, + "JavaSettings": { + "fields": { + "libraryPackage": { + "type": "string", + "id": 1 + }, + "serviceClassNames": { + "keyType": "string", + "type": "string", + "id": 2 + }, + "common": { + "type": "CommonLanguageSettings", + "id": 3 + } + } + }, + "CppSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "PhpSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "PythonSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + }, + "experimentalFeatures": { + "type": "ExperimentalFeatures", + "id": 2 + } + }, + "nested": { + "ExperimentalFeatures": { + "fields": { + "restAsyncIoEnabled": { + "type": "bool", + "id": 1 + }, + "protobufPythonicTypesEnabled": { + "type": "bool", + "id": 2 + }, + "unversionedPackageDisabled": { + "type": "bool", + "id": 3 + } + } + } + } + }, + "NodeSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "DotnetSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + }, + "renamedServices": { + "keyType": "string", + "type": "string", + "id": 2 + }, + "renamedResources": { + "keyType": "string", + "type": "string", + "id": 3 + }, + "ignoredResources": { + "rule": "repeated", + "type": "string", + "id": 4 + }, + "forcedNamespaceAliases": { + "rule": "repeated", + "type": "string", + "id": 5 + }, + "handwrittenSignatures": { + "rule": "repeated", + "type": "string", + "id": 6 + } + } + }, + "RubySettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "GoSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + }, + "renamedServices": { + "keyType": "string", + "type": "string", + "id": 2 + } + } + }, + "MethodSettings": { + "fields": { + "selector": { + "type": "string", + "id": 1 + }, + "longRunning": { + "type": "LongRunning", + "id": 2 + }, + "autoPopulatedFields": { + "rule": "repeated", + "type": "string", + "id": 3 + } + }, + "nested": { + "LongRunning": { + "fields": { + "initialPollDelay": { + "type": "google.protobuf.Duration", + "id": 1 + }, + "pollDelayMultiplier": { + "type": "float", + "id": 2 + }, + "maxPollDelay": { + "type": "google.protobuf.Duration", + "id": 3 + }, + "totalPollTimeout": { + "type": "google.protobuf.Duration", + "id": 4 + } + } + } + } + }, + "ClientLibraryOrganization": { + "values": { + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED": 0, + "CLOUD": 1, + "ADS": 2, + "PHOTOS": 3, + "STREET_VIEW": 4, + "SHOPPING": 5, + "GEO": 6, + "GENERATIVE_AI": 7 + } + }, + "ClientLibraryDestination": { + "values": { + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED": 0, + "GITHUB": 10, + "PACKAGE_MANAGER": 20 + } + }, + "SelectiveGapicGeneration": { + "fields": { + "methods": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "generateOmittedAsInternal": { + "type": "bool", + "id": 2 + } + } + }, + "LaunchStage": { + "values": { + "LAUNCH_STAGE_UNSPECIFIED": 0, + "UNIMPLEMENTED": 6, + "PRELAUNCH": 7, + "EARLY_ACCESS": 1, + "ALPHA": 2, + "BETA": 3, + "GA": 4, + "DEPRECATED": 5 + } + }, + "routing": { + "type": "google.api.RoutingRule", + "id": 72295729, + "extend": "google.protobuf.MethodOptions" + }, + "RoutingRule": { + "fields": { + "routingParameters": { + "rule": "repeated", + "type": "RoutingParameter", + "id": 2 + } + } + }, + "RoutingParameter": { + "fields": { + "field": { + "type": "string", + "id": 1 + }, + "pathTemplate": { + "type": "string", + "id": 2 + } + } + }, + "resourceReference": { + "type": "google.api.ResourceReference", + "id": 1055, + "extend": "google.protobuf.FieldOptions" + }, + "resourceDefinition": { + "rule": "repeated", + "type": "google.api.ResourceDescriptor", + "id": 1053, + "extend": "google.protobuf.FileOptions" + }, + "resource": { + "type": "google.api.ResourceDescriptor", + "id": 1053, + "extend": "google.protobuf.MessageOptions" + }, + "ResourceDescriptor": { + "fields": { + "type": { + "type": "string", + "id": 1 + }, + "pattern": { + "rule": "repeated", + "type": "string", + "id": 2 + }, + "nameField": { + "type": "string", + "id": 3 + }, + "history": { + "type": "History", + "id": 4 + }, + "plural": { + "type": "string", + "id": 5 + }, + "singular": { + "type": "string", + "id": 6 + }, + "style": { + "rule": "repeated", + "type": "Style", + "id": 10 + } + }, + "nested": { + "History": { + "values": { + "HISTORY_UNSPECIFIED": 0, + "ORIGINALLY_SINGLE_PATTERN": 1, + "FUTURE_MULTI_PATTERN": 2 + } + }, + "Style": { + "values": { + "STYLE_UNSPECIFIED": 0, + "DECLARATIVE_FRIENDLY": 1 + } + } + } + }, + "ResourceReference": { + "fields": { + "type": { + "type": "string", + "id": 1 + }, + "childType": { + "type": "string", + "id": 2 + } + } + } + } + }, + "protobuf": { + "options": { + "go_package": "google.golang.org/protobuf/types/descriptorpb", + "java_package": "com.google.protobuf", + "java_outer_classname": "DescriptorProtos", + "csharp_namespace": "Google.Protobuf.Reflection", + "objc_class_prefix": "GPB", + "cc_enable_arenas": true, + "optimize_for": "SPEED" + }, + "nested": { + "FileDescriptorSet": { + "edition": "proto2", + "fields": { + "file": { + "rule": "repeated", + "type": "FileDescriptorProto", + "id": 1 + } + } + }, + "Edition": { + "edition": "proto2", + "values": { + "EDITION_UNKNOWN": 0, + "EDITION_PROTO2": 998, + "EDITION_PROTO3": 999, + "EDITION_2023": 1000, + "EDITION_2024": 1001, + "EDITION_1_TEST_ONLY": 1, + "EDITION_2_TEST_ONLY": 2, + "EDITION_99997_TEST_ONLY": 99997, + "EDITION_99998_TEST_ONLY": 99998, + "EDITION_99999_TEST_ONLY": 99999, + "EDITION_MAX": 2147483647 + } + }, + "FileDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "package": { + "type": "string", + "id": 2 + }, + "dependency": { + "rule": "repeated", + "type": "string", + "id": 3 + }, + "publicDependency": { + "rule": "repeated", + "type": "int32", + "id": 10 + }, + "weakDependency": { + "rule": "repeated", + "type": "int32", + "id": 11 + }, + "messageType": { + "rule": "repeated", + "type": "DescriptorProto", + "id": 4 + }, + "enumType": { + "rule": "repeated", + "type": "EnumDescriptorProto", + "id": 5 + }, + "service": { + "rule": "repeated", + "type": "ServiceDescriptorProto", + "id": 6 + }, + "extension": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 7 + }, + "options": { + "type": "FileOptions", + "id": 8 + }, + "sourceCodeInfo": { + "type": "SourceCodeInfo", + "id": 9 + }, + "syntax": { + "type": "string", + "id": 12 + }, + "edition": { + "type": "Edition", + "id": 14 + } + } + }, + "DescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "field": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 2 + }, + "extension": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 6 + }, + "nestedType": { + "rule": "repeated", + "type": "DescriptorProto", + "id": 3 + }, + "enumType": { + "rule": "repeated", + "type": "EnumDescriptorProto", + "id": 4 + }, + "extensionRange": { + "rule": "repeated", + "type": "ExtensionRange", + "id": 5 + }, + "oneofDecl": { + "rule": "repeated", + "type": "OneofDescriptorProto", + "id": 8 + }, + "options": { + "type": "MessageOptions", + "id": 7 + }, + "reservedRange": { + "rule": "repeated", + "type": "ReservedRange", + "id": 9 + }, + "reservedName": { + "rule": "repeated", + "type": "string", + "id": 10 + } + }, + "nested": { + "ExtensionRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + }, + "options": { + "type": "ExtensionRangeOptions", + "id": 3 + } + } + }, + "ReservedRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + } + } + } + } + }, + "ExtensionRangeOptions": { + "edition": "proto2", + "fields": { + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + }, + "declaration": { + "rule": "repeated", + "type": "Declaration", + "id": 2, + "options": { + "retention": "RETENTION_SOURCE" + } + }, + "features": { + "type": "FeatureSet", + "id": 50 + }, + "verification": { + "type": "VerificationState", + "id": 3, + "options": { + "default": "UNVERIFIED", + "retention": "RETENTION_SOURCE" + } + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "nested": { + "Declaration": { + "fields": { + "number": { + "type": "int32", + "id": 1 + }, + "fullName": { + "type": "string", + "id": 2 + }, + "type": { + "type": "string", + "id": 3 + }, + "reserved": { + "type": "bool", + "id": 5 + }, + "repeated": { + "type": "bool", + "id": 6 + } + }, + "reserved": [ + [ + 4, + 4 + ] + ] + }, + "VerificationState": { + "values": { + "DECLARATION": 0, + "UNVERIFIED": 1 + } + } + } + }, + "FieldDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "number": { + "type": "int32", + "id": 3 + }, + "label": { + "type": "Label", + "id": 4 + }, + "type": { + "type": "Type", + "id": 5 + }, + "typeName": { + "type": "string", + "id": 6 + }, + "extendee": { + "type": "string", + "id": 2 + }, + "defaultValue": { + "type": "string", + "id": 7 + }, + "oneofIndex": { + "type": "int32", + "id": 9 + }, + "jsonName": { + "type": "string", + "id": 10 + }, + "options": { + "type": "FieldOptions", + "id": 8 + }, + "proto3Optional": { + "type": "bool", + "id": 17 + } + }, + "nested": { + "Type": { + "values": { + "TYPE_DOUBLE": 1, + "TYPE_FLOAT": 2, + "TYPE_INT64": 3, + "TYPE_UINT64": 4, + "TYPE_INT32": 5, + "TYPE_FIXED64": 6, + "TYPE_FIXED32": 7, + "TYPE_BOOL": 8, + "TYPE_STRING": 9, + "TYPE_GROUP": 10, + "TYPE_MESSAGE": 11, + "TYPE_BYTES": 12, + "TYPE_UINT32": 13, + "TYPE_ENUM": 14, + "TYPE_SFIXED32": 15, + "TYPE_SFIXED64": 16, + "TYPE_SINT32": 17, + "TYPE_SINT64": 18 + } + }, + "Label": { + "values": { + "LABEL_OPTIONAL": 1, + "LABEL_REPEATED": 3, + "LABEL_REQUIRED": 2 + } + } + } + }, + "OneofDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "options": { + "type": "OneofOptions", + "id": 2 + } + } + }, + "EnumDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "value": { + "rule": "repeated", + "type": "EnumValueDescriptorProto", + "id": 2 + }, + "options": { + "type": "EnumOptions", + "id": 3 + }, + "reservedRange": { + "rule": "repeated", + "type": "EnumReservedRange", + "id": 4 + }, + "reservedName": { + "rule": "repeated", + "type": "string", + "id": 5 + } + }, + "nested": { + "EnumReservedRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + } + } + } + } + }, + "EnumValueDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "number": { + "type": "int32", + "id": 2 + }, + "options": { + "type": "EnumValueOptions", + "id": 3 + } + } + }, + "ServiceDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "method": { + "rule": "repeated", + "type": "MethodDescriptorProto", + "id": 2 + }, + "options": { + "type": "ServiceOptions", + "id": 3 + } + } + }, + "MethodDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "inputType": { + "type": "string", + "id": 2 + }, + "outputType": { + "type": "string", + "id": 3 + }, + "options": { + "type": "MethodOptions", + "id": 4 + }, + "clientStreaming": { + "type": "bool", + "id": 5, + "options": { + "default": false + } + }, + "serverStreaming": { + "type": "bool", + "id": 6, + "options": { + "default": false + } + } + } + }, + "FileOptions": { + "edition": "proto2", + "fields": { + "javaPackage": { + "type": "string", + "id": 1 + }, + "javaOuterClassname": { + "type": "string", + "id": 8 + }, + "javaMultipleFiles": { + "type": "bool", + "id": 10, + "options": { + "default": false + } + }, + "javaGenerateEqualsAndHash": { + "type": "bool", + "id": 20, + "options": { + "deprecated": true + } + }, + "javaStringCheckUtf8": { + "type": "bool", + "id": 27, + "options": { + "default": false + } + }, + "optimizeFor": { + "type": "OptimizeMode", + "id": 9, + "options": { + "default": "SPEED" + } + }, + "goPackage": { + "type": "string", + "id": 11 + }, + "ccGenericServices": { + "type": "bool", + "id": 16, + "options": { + "default": false + } + }, + "javaGenericServices": { + "type": "bool", + "id": 17, + "options": { + "default": false + } + }, + "pyGenericServices": { + "type": "bool", + "id": 18, + "options": { + "default": false + } + }, + "deprecated": { + "type": "bool", + "id": 23, + "options": { + "default": false + } + }, + "ccEnableArenas": { + "type": "bool", + "id": 31, + "options": { + "default": true + } + }, + "objcClassPrefix": { + "type": "string", + "id": 36 + }, + "csharpNamespace": { + "type": "string", + "id": 37 + }, + "swiftPrefix": { + "type": "string", + "id": 39 + }, + "phpClassPrefix": { + "type": "string", + "id": 40 + }, + "phpNamespace": { + "type": "string", + "id": 41 + }, + "phpMetadataNamespace": { + "type": "string", + "id": 44 + }, + "rubyPackage": { + "type": "string", + "id": 45 + }, + "features": { + "type": "FeatureSet", + "id": 50 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 42, + 42 + ], + [ + 38, + 38 + ] + ], + "nested": { + "OptimizeMode": { + "values": { + "SPEED": 1, + "CODE_SIZE": 2, + "LITE_RUNTIME": 3 + } + } + } + }, + "MessageOptions": { + "edition": "proto2", + "fields": { + "messageSetWireFormat": { + "type": "bool", + "id": 1, + "options": { + "default": false + } + }, + "noStandardDescriptorAccessor": { + "type": "bool", + "id": 2, + "options": { + "default": false + } + }, + "deprecated": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "mapEntry": { + "type": "bool", + "id": 7 + }, + "deprecatedLegacyJsonFieldConflicts": { + "type": "bool", + "id": 11, + "options": { + "deprecated": true + } + }, + "features": { + "type": "FeatureSet", + "id": 12 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 4, + 4 + ], + [ + 5, + 5 + ], + [ + 6, + 6 + ], + [ + 8, + 8 + ], + [ + 9, + 9 + ] + ] + }, + "FieldOptions": { + "edition": "proto2", + "fields": { + "ctype": { + "type": "CType", + "id": 1, + "options": { + "default": "STRING" + } + }, + "packed": { + "type": "bool", + "id": 2 + }, + "jstype": { + "type": "JSType", + "id": 6, + "options": { + "default": "JS_NORMAL" + } + }, + "lazy": { + "type": "bool", + "id": 5, + "options": { + "default": false + } + }, + "unverifiedLazy": { + "type": "bool", + "id": 15, + "options": { + "default": false + } + }, + "deprecated": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "weak": { + "type": "bool", + "id": 10, + "options": { + "default": false + } + }, + "debugRedact": { + "type": "bool", + "id": 16, + "options": { + "default": false + } + }, + "retention": { + "type": "OptionRetention", + "id": 17 + }, + "targets": { + "rule": "repeated", + "type": "OptionTargetType", + "id": 19 + }, + "editionDefaults": { + "rule": "repeated", + "type": "EditionDefault", + "id": 20 + }, + "features": { + "type": "FeatureSet", + "id": 21 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 4, + 4 + ], + [ + 18, + 18 + ] + ], + "nested": { + "CType": { + "values": { + "STRING": 0, + "CORD": 1, + "STRING_PIECE": 2 + } + }, + "JSType": { + "values": { + "JS_NORMAL": 0, + "JS_STRING": 1, + "JS_NUMBER": 2 + } + }, + "OptionRetention": { + "values": { + "RETENTION_UNKNOWN": 0, + "RETENTION_RUNTIME": 1, + "RETENTION_SOURCE": 2 + } + }, + "OptionTargetType": { + "values": { + "TARGET_TYPE_UNKNOWN": 0, + "TARGET_TYPE_FILE": 1, + "TARGET_TYPE_EXTENSION_RANGE": 2, + "TARGET_TYPE_MESSAGE": 3, + "TARGET_TYPE_FIELD": 4, + "TARGET_TYPE_ONEOF": 5, + "TARGET_TYPE_ENUM": 6, + "TARGET_TYPE_ENUM_ENTRY": 7, + "TARGET_TYPE_SERVICE": 8, + "TARGET_TYPE_METHOD": 9 + } + }, + "EditionDefault": { + "fields": { + "edition": { + "type": "Edition", + "id": 3 + }, + "value": { + "type": "string", + "id": 2 + } + } + } + } + }, + "OneofOptions": { + "edition": "proto2", + "fields": { + "features": { + "type": "FeatureSet", + "id": 1 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "EnumOptions": { + "edition": "proto2", + "fields": { + "allowAlias": { + "type": "bool", + "id": 2 + }, + "deprecated": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "deprecatedLegacyJsonFieldConflicts": { + "type": "bool", + "id": 6, + "options": { + "deprecated": true + } + }, + "features": { + "type": "FeatureSet", + "id": 7 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 5, + 5 + ] + ] + }, + "EnumValueOptions": { + "edition": "proto2", + "fields": { + "deprecated": { + "type": "bool", + "id": 1, + "options": { + "default": false + } + }, + "features": { + "type": "FeatureSet", + "id": 2 + }, + "debugRedact": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "ServiceOptions": { + "edition": "proto2", + "fields": { + "features": { + "type": "FeatureSet", + "id": 34 + }, + "deprecated": { + "type": "bool", + "id": 33, + "options": { + "default": false + } + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "MethodOptions": { + "edition": "proto2", + "fields": { + "deprecated": { + "type": "bool", + "id": 33, + "options": { + "default": false + } + }, + "idempotencyLevel": { + "type": "IdempotencyLevel", + "id": 34, + "options": { + "default": "IDEMPOTENCY_UNKNOWN" + } + }, + "features": { + "type": "FeatureSet", + "id": 35 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "nested": { + "IdempotencyLevel": { + "values": { + "IDEMPOTENCY_UNKNOWN": 0, + "NO_SIDE_EFFECTS": 1, + "IDEMPOTENT": 2 + } + } + } + }, + "UninterpretedOption": { + "edition": "proto2", + "fields": { + "name": { + "rule": "repeated", + "type": "NamePart", + "id": 2 + }, + "identifierValue": { + "type": "string", + "id": 3 + }, + "positiveIntValue": { + "type": "uint64", + "id": 4 + }, + "negativeIntValue": { + "type": "int64", + "id": 5 + }, + "doubleValue": { + "type": "double", + "id": 6 + }, + "stringValue": { + "type": "bytes", + "id": 7 + }, + "aggregateValue": { + "type": "string", + "id": 8 + } + }, + "nested": { + "NamePart": { + "fields": { + "namePart": { + "rule": "required", + "type": "string", + "id": 1 + }, + "isExtension": { + "rule": "required", + "type": "bool", + "id": 2 + } + } + } + } + }, + "FeatureSet": { + "edition": "proto2", + "fields": { + "fieldPresence": { + "type": "FieldPresence", + "id": 1, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_2023", + "edition_defaults.value": "EXPLICIT" + } + }, + "enumType": { + "type": "EnumType", + "id": 2, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "OPEN" + } + }, + "repeatedFieldEncoding": { + "type": "RepeatedFieldEncoding", + "id": 3, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "PACKED" + } + }, + "utf8Validation": { + "type": "Utf8Validation", + "id": 4, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "VERIFY" + } + }, + "messageEncoding": { + "type": "MessageEncoding", + "id": 5, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO2", + "edition_defaults.value": "LENGTH_PREFIXED" + } + }, + "jsonFormat": { + "type": "JsonFormat", + "id": 6, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "ALLOW" + } + } + }, + "extensions": [ + [ + 1000, + 1000 + ], + [ + 1001, + 1001 + ], + [ + 1002, + 1002 + ], + [ + 9995, + 9999 + ], + [ + 10000, + 10000 + ] + ], + "reserved": [ + [ + 999, + 999 + ] + ], + "nested": { + "FieldPresence": { + "values": { + "FIELD_PRESENCE_UNKNOWN": 0, + "EXPLICIT": 1, + "IMPLICIT": 2, + "LEGACY_REQUIRED": 3 + } + }, + "EnumType": { + "values": { + "ENUM_TYPE_UNKNOWN": 0, + "OPEN": 1, + "CLOSED": 2 + } + }, + "RepeatedFieldEncoding": { + "values": { + "REPEATED_FIELD_ENCODING_UNKNOWN": 0, + "PACKED": 1, + "EXPANDED": 2 + } + }, + "Utf8Validation": { + "values": { + "UTF8_VALIDATION_UNKNOWN": 0, + "VERIFY": 2, + "NONE": 3 + } + }, + "MessageEncoding": { + "values": { + "MESSAGE_ENCODING_UNKNOWN": 0, + "LENGTH_PREFIXED": 1, + "DELIMITED": 2 + } + }, + "JsonFormat": { + "values": { + "JSON_FORMAT_UNKNOWN": 0, + "ALLOW": 1, + "LEGACY_BEST_EFFORT": 2 + } + } + } + }, + "FeatureSetDefaults": { + "edition": "proto2", + "fields": { + "defaults": { + "rule": "repeated", + "type": "FeatureSetEditionDefault", + "id": 1 + }, + "minimumEdition": { + "type": "Edition", + "id": 4 + }, + "maximumEdition": { + "type": "Edition", + "id": 5 + } + }, + "nested": { + "FeatureSetEditionDefault": { + "fields": { + "edition": { + "type": "Edition", + "id": 3 + }, + "features": { + "type": "FeatureSet", + "id": 2 + } + } + } + } + }, + "SourceCodeInfo": { + "edition": "proto2", + "fields": { + "location": { + "rule": "repeated", + "type": "Location", + "id": 1 + } + }, + "nested": { + "Location": { + "fields": { + "path": { + "rule": "repeated", + "type": "int32", + "id": 1, + "options": { + "packed": true + } + }, + "span": { + "rule": "repeated", + "type": "int32", + "id": 2, + "options": { + "packed": true + } + }, + "leadingComments": { + "type": "string", + "id": 3 + }, + "trailingComments": { + "type": "string", + "id": 4 + }, + "leadingDetachedComments": { + "rule": "repeated", + "type": "string", + "id": 6 + } + } + } + } + }, + "GeneratedCodeInfo": { + "edition": "proto2", + "fields": { + "annotation": { + "rule": "repeated", + "type": "Annotation", + "id": 1 + } + }, + "nested": { + "Annotation": { + "fields": { + "path": { + "rule": "repeated", + "type": "int32", + "id": 1, + "options": { + "packed": true + } + }, + "sourceFile": { + "type": "string", + "id": 2 + }, + "begin": { + "type": "int32", + "id": 3 + }, + "end": { + "type": "int32", + "id": 4 + }, + "semantic": { + "type": "Semantic", + "id": 5 + } + }, + "nested": { + "Semantic": { + "values": { + "NONE": 0, + "SET": 1, + "ALIAS": 2 + } + } + } + } + } + }, + "Struct": { + "fields": { + "fields": { + "keyType": "string", + "type": "Value", + "id": 1 + } + } + }, + "Value": { + "oneofs": { + "kind": { + "oneof": [ + "nullValue", + "numberValue", + "stringValue", + "boolValue", + "structValue", + "listValue" + ] + } + }, + "fields": { + "nullValue": { + "type": "NullValue", + "id": 1 + }, + "numberValue": { + "type": "double", + "id": 2 + }, + "stringValue": { + "type": "string", + "id": 3 + }, + "boolValue": { + "type": "bool", + "id": 4 + }, + "structValue": { + "type": "Struct", + "id": 5 + }, + "listValue": { + "type": "ListValue", + "id": 6 + } + } + }, + "NullValue": { + "values": { + "NULL_VALUE": 0 + } + }, + "ListValue": { + "fields": { + "values": { + "rule": "repeated", + "type": "Value", + "id": 1 + } + } + }, + "Timestamp": { + "fields": { + "seconds": { + "type": "int64", + "id": 1 + }, + "nanos": { + "type": "int32", + "id": 2 + } + } + }, + "Any": { + "fields": { + "type_url": { + "type": "string", + "id": 1 + }, + "value": { + "type": "bytes", + "id": 2 + } + } + }, + "Duration": { + "fields": { + "seconds": { + "type": "int64", + "id": 1 + }, + "nanos": { + "type": "int32", + "id": 2 + } + } + }, + "DoubleValue": { + "fields": { + "value": { + "type": "double", + "id": 1 + } + } + }, + "FloatValue": { + "fields": { + "value": { + "type": "float", + "id": 1 + } + } + }, + "Int64Value": { + "fields": { + "value": { + "type": "int64", + "id": 1 + } + } + }, + "UInt64Value": { + "fields": { + "value": { + "type": "uint64", + "id": 1 + } + } + }, + "Int32Value": { + "fields": { + "value": { + "type": "int32", + "id": 1 + } + } + }, + "UInt32Value": { + "fields": { + "value": { + "type": "uint32", + "id": 1 + } + } + }, + "BoolValue": { + "fields": { + "value": { + "type": "bool", + "id": 1 + } + } + }, + "StringValue": { + "fields": { + "value": { + "type": "string", + "id": 1 + } + } + }, + "BytesValue": { + "fields": { + "value": { + "type": "bytes", + "id": 1 + } + } + }, + "Empty": { + "fields": {} + }, + "FieldMask": { + "fields": { + "paths": { + "rule": "repeated", + "type": "string", + "id": 1 + } + } + } + } + }, + "type": { + "options": { + "cc_enable_arenas": true, + "go_package": "google.golang.org/genproto/googleapis/type/dayofweek;dayofweek", + "java_multiple_files": true, + "java_outer_classname": "DayOfWeekProto", + "java_package": "com.google.type", + "objc_class_prefix": "GTP" + }, + "nested": { + "LatLng": { + "fields": { + "latitude": { + "type": "double", + "id": 1 + }, + "longitude": { + "type": "double", + "id": 2 + } + } + }, + "DayOfWeek": { + "values": { + "DAY_OF_WEEK_UNSPECIFIED": 0, + "MONDAY": 1, + "TUESDAY": 2, + "WEDNESDAY": 3, + "THURSDAY": 4, + "FRIDAY": 5, + "SATURDAY": 6, + "SUNDAY": 7 + } + } + } + }, + "rpc": { + "options": { + "cc_enable_arenas": true, + "go_package": "google.golang.org/genproto/googleapis/rpc/status;status", + "java_multiple_files": true, + "java_outer_classname": "StatusProto", + "java_package": "com.google.rpc", + "objc_class_prefix": "RPC" + }, + "nested": { + "Status": { + "fields": { + "code": { + "type": "int32", + "id": 1 + }, + "message": { + "type": "string", + "id": 2 + }, + "details": { + "rule": "repeated", + "type": "google.protobuf.Any", + "id": 3 + } + } + } + } + } + } + } + } +} diff --git a/handwritten/firestore/dev/protos/v1beta1.json b/handwritten/firestore/dev/protos/v1beta1.json new file mode 100644 index 00000000000..7c121967526 --- /dev/null +++ b/handwritten/firestore/dev/protos/v1beta1.json @@ -0,0 +1,3771 @@ +{ + "nested": { + "google": { + "nested": { + "protobuf": { + "options": { + "go_package": "google.golang.org/protobuf/types/descriptorpb", + "java_package": "com.google.protobuf", + "java_outer_classname": "DescriptorProtos", + "csharp_namespace": "Google.Protobuf.Reflection", + "objc_class_prefix": "GPB", + "cc_enable_arenas": true, + "optimize_for": "SPEED" + }, + "nested": { + "Timestamp": { + "fields": { + "seconds": { + "type": "int64", + "id": 1 + }, + "nanos": { + "type": "int32", + "id": 2 + } + } + }, + "Struct": { + "fields": { + "fields": { + "keyType": "string", + "type": "Value", + "id": 1 + } + } + }, + "Value": { + "oneofs": { + "kind": { + "oneof": [ + "nullValue", + "numberValue", + "stringValue", + "boolValue", + "structValue", + "listValue" + ] + } + }, + "fields": { + "nullValue": { + "type": "NullValue", + "id": 1 + }, + "numberValue": { + "type": "double", + "id": 2 + }, + "stringValue": { + "type": "string", + "id": 3 + }, + "boolValue": { + "type": "bool", + "id": 4 + }, + "structValue": { + "type": "Struct", + "id": 5 + }, + "listValue": { + "type": "ListValue", + "id": 6 + } + } + }, + "NullValue": { + "values": { + "NULL_VALUE": 0 + } + }, + "ListValue": { + "fields": { + "values": { + "rule": "repeated", + "type": "Value", + "id": 1 + } + } + }, + "FileDescriptorSet": { + "edition": "proto2", + "fields": { + "file": { + "rule": "repeated", + "type": "FileDescriptorProto", + "id": 1 + } + } + }, + "Edition": { + "edition": "proto2", + "values": { + "EDITION_UNKNOWN": 0, + "EDITION_PROTO2": 998, + "EDITION_PROTO3": 999, + "EDITION_2023": 1000, + "EDITION_2024": 1001, + "EDITION_1_TEST_ONLY": 1, + "EDITION_2_TEST_ONLY": 2, + "EDITION_99997_TEST_ONLY": 99997, + "EDITION_99998_TEST_ONLY": 99998, + "EDITION_99999_TEST_ONLY": 99999, + "EDITION_MAX": 2147483647 + } + }, + "FileDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "package": { + "type": "string", + "id": 2 + }, + "dependency": { + "rule": "repeated", + "type": "string", + "id": 3 + }, + "publicDependency": { + "rule": "repeated", + "type": "int32", + "id": 10 + }, + "weakDependency": { + "rule": "repeated", + "type": "int32", + "id": 11 + }, + "messageType": { + "rule": "repeated", + "type": "DescriptorProto", + "id": 4 + }, + "enumType": { + "rule": "repeated", + "type": "EnumDescriptorProto", + "id": 5 + }, + "service": { + "rule": "repeated", + "type": "ServiceDescriptorProto", + "id": 6 + }, + "extension": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 7 + }, + "options": { + "type": "FileOptions", + "id": 8 + }, + "sourceCodeInfo": { + "type": "SourceCodeInfo", + "id": 9 + }, + "syntax": { + "type": "string", + "id": 12 + }, + "edition": { + "type": "Edition", + "id": 14 + } + } + }, + "DescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "field": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 2 + }, + "extension": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 6 + }, + "nestedType": { + "rule": "repeated", + "type": "DescriptorProto", + "id": 3 + }, + "enumType": { + "rule": "repeated", + "type": "EnumDescriptorProto", + "id": 4 + }, + "extensionRange": { + "rule": "repeated", + "type": "ExtensionRange", + "id": 5 + }, + "oneofDecl": { + "rule": "repeated", + "type": "OneofDescriptorProto", + "id": 8 + }, + "options": { + "type": "MessageOptions", + "id": 7 + }, + "reservedRange": { + "rule": "repeated", + "type": "ReservedRange", + "id": 9 + }, + "reservedName": { + "rule": "repeated", + "type": "string", + "id": 10 + } + }, + "nested": { + "ExtensionRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + }, + "options": { + "type": "ExtensionRangeOptions", + "id": 3 + } + } + }, + "ReservedRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + } + } + } + } + }, + "ExtensionRangeOptions": { + "edition": "proto2", + "fields": { + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + }, + "declaration": { + "rule": "repeated", + "type": "Declaration", + "id": 2, + "options": { + "retention": "RETENTION_SOURCE" + } + }, + "features": { + "type": "FeatureSet", + "id": 50 + }, + "verification": { + "type": "VerificationState", + "id": 3, + "options": { + "default": "UNVERIFIED", + "retention": "RETENTION_SOURCE" + } + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "nested": { + "Declaration": { + "fields": { + "number": { + "type": "int32", + "id": 1 + }, + "fullName": { + "type": "string", + "id": 2 + }, + "type": { + "type": "string", + "id": 3 + }, + "reserved": { + "type": "bool", + "id": 5 + }, + "repeated": { + "type": "bool", + "id": 6 + } + }, + "reserved": [ + [ + 4, + 4 + ] + ] + }, + "VerificationState": { + "values": { + "DECLARATION": 0, + "UNVERIFIED": 1 + } + } + } + }, + "FieldDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "number": { + "type": "int32", + "id": 3 + }, + "label": { + "type": "Label", + "id": 4 + }, + "type": { + "type": "Type", + "id": 5 + }, + "typeName": { + "type": "string", + "id": 6 + }, + "extendee": { + "type": "string", + "id": 2 + }, + "defaultValue": { + "type": "string", + "id": 7 + }, + "oneofIndex": { + "type": "int32", + "id": 9 + }, + "jsonName": { + "type": "string", + "id": 10 + }, + "options": { + "type": "FieldOptions", + "id": 8 + }, + "proto3Optional": { + "type": "bool", + "id": 17 + } + }, + "nested": { + "Type": { + "values": { + "TYPE_DOUBLE": 1, + "TYPE_FLOAT": 2, + "TYPE_INT64": 3, + "TYPE_UINT64": 4, + "TYPE_INT32": 5, + "TYPE_FIXED64": 6, + "TYPE_FIXED32": 7, + "TYPE_BOOL": 8, + "TYPE_STRING": 9, + "TYPE_GROUP": 10, + "TYPE_MESSAGE": 11, + "TYPE_BYTES": 12, + "TYPE_UINT32": 13, + "TYPE_ENUM": 14, + "TYPE_SFIXED32": 15, + "TYPE_SFIXED64": 16, + "TYPE_SINT32": 17, + "TYPE_SINT64": 18 + } + }, + "Label": { + "values": { + "LABEL_OPTIONAL": 1, + "LABEL_REPEATED": 3, + "LABEL_REQUIRED": 2 + } + } + } + }, + "OneofDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "options": { + "type": "OneofOptions", + "id": 2 + } + } + }, + "EnumDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "value": { + "rule": "repeated", + "type": "EnumValueDescriptorProto", + "id": 2 + }, + "options": { + "type": "EnumOptions", + "id": 3 + }, + "reservedRange": { + "rule": "repeated", + "type": "EnumReservedRange", + "id": 4 + }, + "reservedName": { + "rule": "repeated", + "type": "string", + "id": 5 + } + }, + "nested": { + "EnumReservedRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + } + } + } + } + }, + "EnumValueDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "number": { + "type": "int32", + "id": 2 + }, + "options": { + "type": "EnumValueOptions", + "id": 3 + } + } + }, + "ServiceDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "method": { + "rule": "repeated", + "type": "MethodDescriptorProto", + "id": 2 + }, + "options": { + "type": "ServiceOptions", + "id": 3 + } + } + }, + "MethodDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "inputType": { + "type": "string", + "id": 2 + }, + "outputType": { + "type": "string", + "id": 3 + }, + "options": { + "type": "MethodOptions", + "id": 4 + }, + "clientStreaming": { + "type": "bool", + "id": 5, + "options": { + "default": false + } + }, + "serverStreaming": { + "type": "bool", + "id": 6, + "options": { + "default": false + } + } + } + }, + "FileOptions": { + "edition": "proto2", + "fields": { + "javaPackage": { + "type": "string", + "id": 1 + }, + "javaOuterClassname": { + "type": "string", + "id": 8 + }, + "javaMultipleFiles": { + "type": "bool", + "id": 10, + "options": { + "default": false + } + }, + "javaGenerateEqualsAndHash": { + "type": "bool", + "id": 20, + "options": { + "deprecated": true + } + }, + "javaStringCheckUtf8": { + "type": "bool", + "id": 27, + "options": { + "default": false + } + }, + "optimizeFor": { + "type": "OptimizeMode", + "id": 9, + "options": { + "default": "SPEED" + } + }, + "goPackage": { + "type": "string", + "id": 11 + }, + "ccGenericServices": { + "type": "bool", + "id": 16, + "options": { + "default": false + } + }, + "javaGenericServices": { + "type": "bool", + "id": 17, + "options": { + "default": false + } + }, + "pyGenericServices": { + "type": "bool", + "id": 18, + "options": { + "default": false + } + }, + "deprecated": { + "type": "bool", + "id": 23, + "options": { + "default": false + } + }, + "ccEnableArenas": { + "type": "bool", + "id": 31, + "options": { + "default": true + } + }, + "objcClassPrefix": { + "type": "string", + "id": 36 + }, + "csharpNamespace": { + "type": "string", + "id": 37 + }, + "swiftPrefix": { + "type": "string", + "id": 39 + }, + "phpClassPrefix": { + "type": "string", + "id": 40 + }, + "phpNamespace": { + "type": "string", + "id": 41 + }, + "phpMetadataNamespace": { + "type": "string", + "id": 44 + }, + "rubyPackage": { + "type": "string", + "id": 45 + }, + "features": { + "type": "FeatureSet", + "id": 50 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 42, + 42 + ], + [ + 38, + 38 + ] + ], + "nested": { + "OptimizeMode": { + "values": { + "SPEED": 1, + "CODE_SIZE": 2, + "LITE_RUNTIME": 3 + } + } + } + }, + "MessageOptions": { + "edition": "proto2", + "fields": { + "messageSetWireFormat": { + "type": "bool", + "id": 1, + "options": { + "default": false + } + }, + "noStandardDescriptorAccessor": { + "type": "bool", + "id": 2, + "options": { + "default": false + } + }, + "deprecated": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "mapEntry": { + "type": "bool", + "id": 7 + }, + "deprecatedLegacyJsonFieldConflicts": { + "type": "bool", + "id": 11, + "options": { + "deprecated": true + } + }, + "features": { + "type": "FeatureSet", + "id": 12 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 4, + 4 + ], + [ + 5, + 5 + ], + [ + 6, + 6 + ], + [ + 8, + 8 + ], + [ + 9, + 9 + ] + ] + }, + "FieldOptions": { + "edition": "proto2", + "fields": { + "ctype": { + "type": "CType", + "id": 1, + "options": { + "default": "STRING" + } + }, + "packed": { + "type": "bool", + "id": 2 + }, + "jstype": { + "type": "JSType", + "id": 6, + "options": { + "default": "JS_NORMAL" + } + }, + "lazy": { + "type": "bool", + "id": 5, + "options": { + "default": false + } + }, + "unverifiedLazy": { + "type": "bool", + "id": 15, + "options": { + "default": false + } + }, + "deprecated": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "weak": { + "type": "bool", + "id": 10, + "options": { + "default": false + } + }, + "debugRedact": { + "type": "bool", + "id": 16, + "options": { + "default": false + } + }, + "retention": { + "type": "OptionRetention", + "id": 17 + }, + "targets": { + "rule": "repeated", + "type": "OptionTargetType", + "id": 19 + }, + "editionDefaults": { + "rule": "repeated", + "type": "EditionDefault", + "id": 20 + }, + "features": { + "type": "FeatureSet", + "id": 21 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 4, + 4 + ], + [ + 18, + 18 + ] + ], + "nested": { + "CType": { + "values": { + "STRING": 0, + "CORD": 1, + "STRING_PIECE": 2 + } + }, + "JSType": { + "values": { + "JS_NORMAL": 0, + "JS_STRING": 1, + "JS_NUMBER": 2 + } + }, + "OptionRetention": { + "values": { + "RETENTION_UNKNOWN": 0, + "RETENTION_RUNTIME": 1, + "RETENTION_SOURCE": 2 + } + }, + "OptionTargetType": { + "values": { + "TARGET_TYPE_UNKNOWN": 0, + "TARGET_TYPE_FILE": 1, + "TARGET_TYPE_EXTENSION_RANGE": 2, + "TARGET_TYPE_MESSAGE": 3, + "TARGET_TYPE_FIELD": 4, + "TARGET_TYPE_ONEOF": 5, + "TARGET_TYPE_ENUM": 6, + "TARGET_TYPE_ENUM_ENTRY": 7, + "TARGET_TYPE_SERVICE": 8, + "TARGET_TYPE_METHOD": 9 + } + }, + "EditionDefault": { + "fields": { + "edition": { + "type": "Edition", + "id": 3 + }, + "value": { + "type": "string", + "id": 2 + } + } + } + } + }, + "OneofOptions": { + "edition": "proto2", + "fields": { + "features": { + "type": "FeatureSet", + "id": 1 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "EnumOptions": { + "edition": "proto2", + "fields": { + "allowAlias": { + "type": "bool", + "id": 2 + }, + "deprecated": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "deprecatedLegacyJsonFieldConflicts": { + "type": "bool", + "id": 6, + "options": { + "deprecated": true + } + }, + "features": { + "type": "FeatureSet", + "id": 7 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 5, + 5 + ] + ] + }, + "EnumValueOptions": { + "edition": "proto2", + "fields": { + "deprecated": { + "type": "bool", + "id": 1, + "options": { + "default": false + } + }, + "features": { + "type": "FeatureSet", + "id": 2 + }, + "debugRedact": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "ServiceOptions": { + "edition": "proto2", + "fields": { + "features": { + "type": "FeatureSet", + "id": 34 + }, + "deprecated": { + "type": "bool", + "id": 33, + "options": { + "default": false + } + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "MethodOptions": { + "edition": "proto2", + "fields": { + "deprecated": { + "type": "bool", + "id": 33, + "options": { + "default": false + } + }, + "idempotencyLevel": { + "type": "IdempotencyLevel", + "id": 34, + "options": { + "default": "IDEMPOTENCY_UNKNOWN" + } + }, + "features": { + "type": "FeatureSet", + "id": 35 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "nested": { + "IdempotencyLevel": { + "values": { + "IDEMPOTENCY_UNKNOWN": 0, + "NO_SIDE_EFFECTS": 1, + "IDEMPOTENT": 2 + } + } + } + }, + "UninterpretedOption": { + "edition": "proto2", + "fields": { + "name": { + "rule": "repeated", + "type": "NamePart", + "id": 2 + }, + "identifierValue": { + "type": "string", + "id": 3 + }, + "positiveIntValue": { + "type": "uint64", + "id": 4 + }, + "negativeIntValue": { + "type": "int64", + "id": 5 + }, + "doubleValue": { + "type": "double", + "id": 6 + }, + "stringValue": { + "type": "bytes", + "id": 7 + }, + "aggregateValue": { + "type": "string", + "id": 8 + } + }, + "nested": { + "NamePart": { + "fields": { + "namePart": { + "rule": "required", + "type": "string", + "id": 1 + }, + "isExtension": { + "rule": "required", + "type": "bool", + "id": 2 + } + } + } + } + }, + "FeatureSet": { + "edition": "proto2", + "fields": { + "fieldPresence": { + "type": "FieldPresence", + "id": 1, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_2023", + "edition_defaults.value": "EXPLICIT" + } + }, + "enumType": { + "type": "EnumType", + "id": 2, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "OPEN" + } + }, + "repeatedFieldEncoding": { + "type": "RepeatedFieldEncoding", + "id": 3, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "PACKED" + } + }, + "utf8Validation": { + "type": "Utf8Validation", + "id": 4, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "VERIFY" + } + }, + "messageEncoding": { + "type": "MessageEncoding", + "id": 5, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO2", + "edition_defaults.value": "LENGTH_PREFIXED" + } + }, + "jsonFormat": { + "type": "JsonFormat", + "id": 6, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "ALLOW" + } + } + }, + "extensions": [ + [ + 1000, + 1000 + ], + [ + 1001, + 1001 + ], + [ + 1002, + 1002 + ], + [ + 9995, + 9999 + ], + [ + 10000, + 10000 + ] + ], + "reserved": [ + [ + 999, + 999 + ] + ], + "nested": { + "FieldPresence": { + "values": { + "FIELD_PRESENCE_UNKNOWN": 0, + "EXPLICIT": 1, + "IMPLICIT": 2, + "LEGACY_REQUIRED": 3 + } + }, + "EnumType": { + "values": { + "ENUM_TYPE_UNKNOWN": 0, + "OPEN": 1, + "CLOSED": 2 + } + }, + "RepeatedFieldEncoding": { + "values": { + "REPEATED_FIELD_ENCODING_UNKNOWN": 0, + "PACKED": 1, + "EXPANDED": 2 + } + }, + "Utf8Validation": { + "values": { + "UTF8_VALIDATION_UNKNOWN": 0, + "VERIFY": 2, + "NONE": 3 + } + }, + "MessageEncoding": { + "values": { + "MESSAGE_ENCODING_UNKNOWN": 0, + "LENGTH_PREFIXED": 1, + "DELIMITED": 2 + } + }, + "JsonFormat": { + "values": { + "JSON_FORMAT_UNKNOWN": 0, + "ALLOW": 1, + "LEGACY_BEST_EFFORT": 2 + } + } + } + }, + "FeatureSetDefaults": { + "edition": "proto2", + "fields": { + "defaults": { + "rule": "repeated", + "type": "FeatureSetEditionDefault", + "id": 1 + }, + "minimumEdition": { + "type": "Edition", + "id": 4 + }, + "maximumEdition": { + "type": "Edition", + "id": 5 + } + }, + "nested": { + "FeatureSetEditionDefault": { + "fields": { + "edition": { + "type": "Edition", + "id": 3 + }, + "features": { + "type": "FeatureSet", + "id": 2 + } + } + } + } + }, + "SourceCodeInfo": { + "edition": "proto2", + "fields": { + "location": { + "rule": "repeated", + "type": "Location", + "id": 1 + } + }, + "nested": { + "Location": { + "fields": { + "path": { + "rule": "repeated", + "type": "int32", + "id": 1, + "options": { + "packed": true + } + }, + "span": { + "rule": "repeated", + "type": "int32", + "id": 2, + "options": { + "packed": true + } + }, + "leadingComments": { + "type": "string", + "id": 3 + }, + "trailingComments": { + "type": "string", + "id": 4 + }, + "leadingDetachedComments": { + "rule": "repeated", + "type": "string", + "id": 6 + } + } + } + } + }, + "GeneratedCodeInfo": { + "edition": "proto2", + "fields": { + "annotation": { + "rule": "repeated", + "type": "Annotation", + "id": 1 + } + }, + "nested": { + "Annotation": { + "fields": { + "path": { + "rule": "repeated", + "type": "int32", + "id": 1, + "options": { + "packed": true + } + }, + "sourceFile": { + "type": "string", + "id": 2 + }, + "begin": { + "type": "int32", + "id": 3 + }, + "end": { + "type": "int32", + "id": 4 + }, + "semantic": { + "type": "Semantic", + "id": 5 + } + }, + "nested": { + "Semantic": { + "values": { + "NONE": 0, + "SET": 1, + "ALIAS": 2 + } + } + } + } + } + }, + "Duration": { + "fields": { + "seconds": { + "type": "int64", + "id": 1 + }, + "nanos": { + "type": "int32", + "id": 2 + } + } + }, + "DoubleValue": { + "fields": { + "value": { + "type": "double", + "id": 1 + } + } + }, + "FloatValue": { + "fields": { + "value": { + "type": "float", + "id": 1 + } + } + }, + "Int64Value": { + "fields": { + "value": { + "type": "int64", + "id": 1 + } + } + }, + "UInt64Value": { + "fields": { + "value": { + "type": "uint64", + "id": 1 + } + } + }, + "Int32Value": { + "fields": { + "value": { + "type": "int32", + "id": 1 + } + } + }, + "UInt32Value": { + "fields": { + "value": { + "type": "uint32", + "id": 1 + } + } + }, + "BoolValue": { + "fields": { + "value": { + "type": "bool", + "id": 1 + } + } + }, + "StringValue": { + "fields": { + "value": { + "type": "string", + "id": 1 + } + } + }, + "BytesValue": { + "fields": { + "value": { + "type": "bytes", + "id": 1 + } + } + }, + "Empty": { + "fields": {} + }, + "Any": { + "fields": { + "type_url": { + "type": "string", + "id": 1 + }, + "value": { + "type": "bytes", + "id": 2 + } + } + }, + "FieldMask": { + "fields": { + "paths": { + "rule": "repeated", + "type": "string", + "id": 1 + } + } + } + } + }, + "firestore": { + "nested": { + "v1beta1": { + "options": { + "csharp_namespace": "Google.Cloud.Firestore.V1Beta1", + "go_package": "cloud.google.com/go/firestore/apiv1beta1/firestorepb;firestorepb", + "java_multiple_files": true, + "java_outer_classname": "UndeliverableFirstGenEventProto", + "java_package": "com.google.firestore.v1beta1", + "objc_class_prefix": "GCFS", + "php_namespace": "Google\\Cloud\\Firestore\\V1beta1", + "ruby_package": "Google::Cloud::Firestore::V1beta1" + }, + "nested": { + "DocumentMask": { + "fields": { + "fieldPaths": { + "rule": "repeated", + "type": "string", + "id": 1 + } + } + }, + "Precondition": { + "oneofs": { + "conditionType": { + "oneof": [ + "exists", + "updateTime" + ] + } + }, + "fields": { + "exists": { + "type": "bool", + "id": 1 + }, + "updateTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + } + } + }, + "TransactionOptions": { + "oneofs": { + "mode": { + "oneof": [ + "readOnly", + "readWrite" + ] + } + }, + "fields": { + "readOnly": { + "type": "ReadOnly", + "id": 2 + }, + "readWrite": { + "type": "ReadWrite", + "id": 3 + } + }, + "nested": { + "ReadWrite": { + "fields": { + "retryTransaction": { + "type": "bytes", + "id": 1 + } + } + }, + "ReadOnly": { + "oneofs": { + "consistencySelector": { + "oneof": [ + "readTime" + ] + } + }, + "fields": { + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + } + } + } + } + }, + "Document": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "fields": { + "keyType": "string", + "type": "Value", + "id": 2 + }, + "createTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + }, + "updateTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + } + } + }, + "Value": { + "oneofs": { + "valueType": { + "oneof": [ + "nullValue", + "booleanValue", + "integerValue", + "doubleValue", + "timestampValue", + "stringValue", + "bytesValue", + "referenceValue", + "geoPointValue", + "arrayValue", + "mapValue" + ] + } + }, + "fields": { + "nullValue": { + "type": "google.protobuf.NullValue", + "id": 11 + }, + "booleanValue": { + "type": "bool", + "id": 1 + }, + "integerValue": { + "type": "int64", + "id": 2 + }, + "doubleValue": { + "type": "double", + "id": 3 + }, + "timestampValue": { + "type": "google.protobuf.Timestamp", + "id": 10 + }, + "stringValue": { + "type": "string", + "id": 17 + }, + "bytesValue": { + "type": "bytes", + "id": 18 + }, + "referenceValue": { + "type": "string", + "id": 5 + }, + "geoPointValue": { + "type": "google.type.LatLng", + "id": 8 + }, + "arrayValue": { + "type": "ArrayValue", + "id": 9 + }, + "mapValue": { + "type": "MapValue", + "id": 6 + } + } + }, + "ArrayValue": { + "fields": { + "values": { + "rule": "repeated", + "type": "Value", + "id": 1 + } + } + }, + "MapValue": { + "fields": { + "fields": { + "keyType": "string", + "type": "Value", + "id": 1 + } + } + }, + "Firestore": { + "options": { + "(google.api.default_host)": "firestore.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/datastore" + }, + "methods": { + "GetDocument": { + "requestType": "GetDocumentRequest", + "responseType": "Document", + "options": { + "(google.api.http).get": "/v1beta1/{name=projects/*/databases/*/documents/*/**}" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1beta1/{name=projects/*/databases/*/documents/*/**}" + } + } + ] + }, + "ListDocuments": { + "requestType": "ListDocumentsRequest", + "responseType": "ListDocumentsResponse", + "options": { + "(google.api.http).get": "/v1beta1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1beta1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}" + } + } + ] + }, + "UpdateDocument": { + "requestType": "UpdateDocumentRequest", + "responseType": "Document", + "options": { + "(google.api.http).patch": "/v1beta1/{document.name=projects/*/databases/*/documents/*/**}", + "(google.api.http).body": "document", + "(google.api.method_signature)": "document,update_mask" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "patch": "/v1beta1/{document.name=projects/*/databases/*/documents/*/**}", + "body": "document" + } + }, + { + "(google.api.method_signature)": "document,update_mask" + } + ] + }, + "DeleteDocument": { + "requestType": "DeleteDocumentRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1beta1/{name=projects/*/databases/*/documents/*/**}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1beta1/{name=projects/*/databases/*/documents/*/**}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "BatchGetDocuments": { + "requestType": "BatchGetDocumentsRequest", + "responseType": "BatchGetDocumentsResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1beta1/{database=projects/*/databases/*}/documents:batchGet", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1beta1/{database=projects/*/databases/*}/documents:batchGet", + "body": "*" + } + } + ] + }, + "BeginTransaction": { + "requestType": "BeginTransactionRequest", + "responseType": "BeginTransactionResponse", + "options": { + "(google.api.http).post": "/v1beta1/{database=projects/*/databases/*}/documents:beginTransaction", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1beta1/{database=projects/*/databases/*}/documents:beginTransaction", + "body": "*" + } + }, + { + "(google.api.method_signature)": "database" + } + ] + }, + "Commit": { + "requestType": "CommitRequest", + "responseType": "CommitResponse", + "options": { + "(google.api.http).post": "/v1beta1/{database=projects/*/databases/*}/documents:commit", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database,writes" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1beta1/{database=projects/*/databases/*}/documents:commit", + "body": "*" + } + }, + { + "(google.api.method_signature)": "database,writes" + } + ] + }, + "Rollback": { + "requestType": "RollbackRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).post": "/v1beta1/{database=projects/*/databases/*}/documents:rollback", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database,transaction" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1beta1/{database=projects/*/databases/*}/documents:rollback", + "body": "*" + } + }, + { + "(google.api.method_signature)": "database,transaction" + } + ] + }, + "RunQuery": { + "requestType": "RunQueryRequest", + "responseType": "RunQueryResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1beta1/{parent=projects/*/databases/*/documents}:runQuery", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1beta1/{parent=projects/*/databases/*/documents/*/**}:runQuery", + "(google.api.http).additional_bindings.body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1beta1/{parent=projects/*/databases/*/documents}:runQuery", + "body": "*", + "additional_bindings": { + "post": "/v1beta1/{parent=projects/*/databases/*/documents/*/**}:runQuery", + "body": "*" + } + } + } + ] + }, + "PartitionQuery": { + "requestType": "PartitionQueryRequest", + "responseType": "PartitionQueryResponse", + "options": { + "(google.api.http).post": "/v1beta1/{parent=projects/*/databases/*/documents}:partitionQuery", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1beta1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery", + "(google.api.http).additional_bindings.body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1beta1/{parent=projects/*/databases/*/documents}:partitionQuery", + "body": "*", + "additional_bindings": { + "post": "/v1beta1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery", + "body": "*" + } + } + } + ] + }, + "Write": { + "requestType": "WriteRequest", + "requestStream": true, + "responseType": "WriteResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1beta1/{database=projects/*/databases/*}/documents:write", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1beta1/{database=projects/*/databases/*}/documents:write", + "body": "*" + } + } + ] + }, + "Listen": { + "requestType": "ListenRequest", + "requestStream": true, + "responseType": "ListenResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1beta1/{database=projects/*/databases/*}/documents:listen", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1beta1/{database=projects/*/databases/*}/documents:listen", + "body": "*" + } + } + ] + }, + "ListCollectionIds": { + "requestType": "ListCollectionIdsRequest", + "responseType": "ListCollectionIdsResponse", + "options": { + "(google.api.http).post": "/v1beta1/{parent=projects/*/databases/*/documents}:listCollectionIds", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1beta1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds", + "(google.api.http).additional_bindings.body": "*", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1beta1/{parent=projects/*/databases/*/documents}:listCollectionIds", + "body": "*", + "additional_bindings": { + "post": "/v1beta1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds", + "body": "*" + } + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "BatchWrite": { + "requestType": "BatchWriteRequest", + "responseType": "BatchWriteResponse", + "options": { + "(google.api.http).post": "/v1beta1/{database=projects/*/databases/*}/documents:batchWrite", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1beta1/{database=projects/*/databases/*}/documents:batchWrite", + "body": "*" + } + } + ] + }, + "CreateDocument": { + "requestType": "CreateDocumentRequest", + "responseType": "Document", + "options": { + "(google.api.http).post": "/v1beta1/{parent=projects/*/databases/*/documents/**}/{collection_id}", + "(google.api.http).body": "document" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1beta1/{parent=projects/*/databases/*/documents/**}/{collection_id}", + "body": "document" + } + } + ] + } + } + }, + "GetDocumentRequest": { + "oneofs": { + "consistencySelector": { + "oneof": [ + "transaction", + "readTime" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "mask": { + "type": "DocumentMask", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 3 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 5 + } + } + }, + "ListDocumentsRequest": { + "oneofs": { + "consistencySelector": { + "oneof": [ + "transaction", + "readTime" + ] + } + }, + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "collectionId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "pageSize": { + "type": "int32", + "id": 3 + }, + "pageToken": { + "type": "string", + "id": 4 + }, + "orderBy": { + "type": "string", + "id": 6 + }, + "mask": { + "type": "DocumentMask", + "id": 7 + }, + "transaction": { + "type": "bytes", + "id": 8 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 10 + }, + "showMissing": { + "type": "bool", + "id": 12 + } + } + }, + "ListDocumentsResponse": { + "fields": { + "documents": { + "rule": "repeated", + "type": "Document", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "CreateDocumentRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "collectionId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "documentId": { + "type": "string", + "id": 3 + }, + "document": { + "type": "Document", + "id": 4, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "mask": { + "type": "DocumentMask", + "id": 5 + } + } + }, + "UpdateDocumentRequest": { + "fields": { + "document": { + "type": "Document", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "updateMask": { + "type": "DocumentMask", + "id": 2 + }, + "mask": { + "type": "DocumentMask", + "id": 3 + }, + "currentDocument": { + "type": "Precondition", + "id": 4 + } + } + }, + "DeleteDocumentRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "currentDocument": { + "type": "Precondition", + "id": 2 + } + } + }, + "BatchGetDocumentsRequest": { + "oneofs": { + "consistencySelector": { + "oneof": [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "documents": { + "rule": "repeated", + "type": "string", + "id": 2 + }, + "mask": { + "type": "DocumentMask", + "id": 3 + }, + "transaction": { + "type": "bytes", + "id": 4 + }, + "newTransaction": { + "type": "TransactionOptions", + "id": 5 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 7 + } + } + }, + "BatchGetDocumentsResponse": { + "oneofs": { + "result": { + "oneof": [ + "found", + "missing" + ] + } + }, + "fields": { + "found": { + "type": "Document", + "id": 1 + }, + "missing": { + "type": "string", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 3 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + } + } + }, + "BeginTransactionRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "options": { + "type": "TransactionOptions", + "id": 2 + } + } + }, + "BeginTransactionResponse": { + "fields": { + "transaction": { + "type": "bytes", + "id": 1 + } + } + }, + "CommitRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "writes": { + "rule": "repeated", + "type": "Write", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 3 + } + } + }, + "CommitResponse": { + "fields": { + "writeResults": { + "rule": "repeated", + "type": "WriteResult", + "id": 1 + }, + "commitTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + } + } + }, + "RollbackRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "transaction": { + "type": "bytes", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "RunQueryRequest": { + "oneofs": { + "queryType": { + "oneof": [ + "structuredQuery" + ] + }, + "consistencySelector": { + "oneof": [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "structuredQuery": { + "type": "StructuredQuery", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 5 + }, + "newTransaction": { + "type": "TransactionOptions", + "id": 6 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 7 + } + } + }, + "RunQueryResponse": { + "fields": { + "transaction": { + "type": "bytes", + "id": 2 + }, + "document": { + "type": "Document", + "id": 1 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + }, + "skippedResults": { + "type": "int32", + "id": 4 + } + } + }, + "PartitionQueryRequest": { + "oneofs": { + "queryType": { + "oneof": [ + "structuredQuery" + ] + } + }, + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "structuredQuery": { + "type": "StructuredQuery", + "id": 2 + }, + "partitionCount": { + "type": "int64", + "id": 3 + }, + "pageToken": { + "type": "string", + "id": 4 + }, + "pageSize": { + "type": "int32", + "id": 5 + } + } + }, + "PartitionQueryResponse": { + "fields": { + "partitions": { + "rule": "repeated", + "type": "Cursor", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "WriteRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "streamId": { + "type": "string", + "id": 2 + }, + "writes": { + "rule": "repeated", + "type": "Write", + "id": 3 + }, + "streamToken": { + "type": "bytes", + "id": 4 + }, + "labels": { + "keyType": "string", + "type": "string", + "id": 5 + } + } + }, + "WriteResponse": { + "fields": { + "streamId": { + "type": "string", + "id": 1 + }, + "streamToken": { + "type": "bytes", + "id": 2 + }, + "writeResults": { + "rule": "repeated", + "type": "WriteResult", + "id": 3 + }, + "commitTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + } + } + }, + "ListenRequest": { + "oneofs": { + "targetChange": { + "oneof": [ + "addTarget", + "removeTarget" + ] + } + }, + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "addTarget": { + "type": "Target", + "id": 2 + }, + "removeTarget": { + "type": "int32", + "id": 3 + }, + "labels": { + "keyType": "string", + "type": "string", + "id": 4 + } + } + }, + "ListenResponse": { + "oneofs": { + "responseType": { + "oneof": [ + "targetChange", + "documentChange", + "documentDelete", + "documentRemove", + "filter" + ] + } + }, + "fields": { + "targetChange": { + "type": "TargetChange", + "id": 2 + }, + "documentChange": { + "type": "DocumentChange", + "id": 3 + }, + "documentDelete": { + "type": "DocumentDelete", + "id": 4 + }, + "documentRemove": { + "type": "DocumentRemove", + "id": 6 + }, + "filter": { + "type": "ExistenceFilter", + "id": 5 + } + } + }, + "Target": { + "oneofs": { + "targetType": { + "oneof": [ + "query", + "documents" + ] + }, + "resumeType": { + "oneof": [ + "resumeToken", + "readTime" + ] + } + }, + "fields": { + "query": { + "type": "QueryTarget", + "id": 2 + }, + "documents": { + "type": "DocumentsTarget", + "id": 3 + }, + "resumeToken": { + "type": "bytes", + "id": 4 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 11 + }, + "targetId": { + "type": "int32", + "id": 5 + }, + "once": { + "type": "bool", + "id": 6 + } + }, + "nested": { + "DocumentsTarget": { + "fields": { + "documents": { + "rule": "repeated", + "type": "string", + "id": 2 + } + } + }, + "QueryTarget": { + "oneofs": { + "queryType": { + "oneof": [ + "structuredQuery" + ] + } + }, + "fields": { + "parent": { + "type": "string", + "id": 1 + }, + "structuredQuery": { + "type": "StructuredQuery", + "id": 2 + } + } + } + } + }, + "TargetChange": { + "fields": { + "targetChangeType": { + "type": "TargetChangeType", + "id": 1 + }, + "targetIds": { + "rule": "repeated", + "type": "int32", + "id": 2 + }, + "cause": { + "type": "google.rpc.Status", + "id": 3 + }, + "resumeToken": { + "type": "bytes", + "id": 4 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 6 + } + }, + "nested": { + "TargetChangeType": { + "values": { + "NO_CHANGE": 0, + "ADD": 1, + "REMOVE": 2, + "CURRENT": 3, + "RESET": 4 + } + } + } + }, + "ListCollectionIdsRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "pageSize": { + "type": "int32", + "id": 2 + }, + "pageToken": { + "type": "string", + "id": 3 + } + } + }, + "ListCollectionIdsResponse": { + "fields": { + "collectionIds": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "BatchWriteRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "writes": { + "rule": "repeated", + "type": "Write", + "id": 2 + }, + "labels": { + "keyType": "string", + "type": "string", + "id": 3 + } + } + }, + "BatchWriteResponse": { + "fields": { + "writeResults": { + "rule": "repeated", + "type": "WriteResult", + "id": 1 + }, + "status": { + "rule": "repeated", + "type": "google.rpc.Status", + "id": 2 + } + } + }, + "StructuredQuery": { + "fields": { + "select": { + "type": "Projection", + "id": 1 + }, + "from": { + "rule": "repeated", + "type": "CollectionSelector", + "id": 2 + }, + "where": { + "type": "Filter", + "id": 3 + }, + "orderBy": { + "rule": "repeated", + "type": "Order", + "id": 4 + }, + "startAt": { + "type": "Cursor", + "id": 7 + }, + "endAt": { + "type": "Cursor", + "id": 8 + }, + "offset": { + "type": "int32", + "id": 6 + }, + "limit": { + "type": "google.protobuf.Int32Value", + "id": 5 + } + }, + "nested": { + "CollectionSelector": { + "fields": { + "collectionId": { + "type": "string", + "id": 2 + }, + "allDescendants": { + "type": "bool", + "id": 3 + } + } + }, + "Filter": { + "oneofs": { + "filterType": { + "oneof": [ + "compositeFilter", + "fieldFilter", + "unaryFilter" + ] + } + }, + "fields": { + "compositeFilter": { + "type": "CompositeFilter", + "id": 1 + }, + "fieldFilter": { + "type": "FieldFilter", + "id": 2 + }, + "unaryFilter": { + "type": "UnaryFilter", + "id": 3 + } + } + }, + "CompositeFilter": { + "fields": { + "op": { + "type": "Operator", + "id": 1 + }, + "filters": { + "rule": "repeated", + "type": "Filter", + "id": 2 + } + }, + "nested": { + "Operator": { + "values": { + "OPERATOR_UNSPECIFIED": 0, + "AND": 1 + } + } + } + }, + "FieldFilter": { + "fields": { + "field": { + "type": "FieldReference", + "id": 1 + }, + "op": { + "type": "Operator", + "id": 2 + }, + "value": { + "type": "Value", + "id": 3 + } + }, + "nested": { + "Operator": { + "values": { + "OPERATOR_UNSPECIFIED": 0, + "LESS_THAN": 1, + "LESS_THAN_OR_EQUAL": 2, + "GREATER_THAN": 3, + "GREATER_THAN_OR_EQUAL": 4, + "EQUAL": 5, + "NOT_EQUAL": 6, + "ARRAY_CONTAINS": 7, + "IN": 8, + "ARRAY_CONTAINS_ANY": 9, + "NOT_IN": 10 + } + } + } + }, + "UnaryFilter": { + "oneofs": { + "operandType": { + "oneof": [ + "field" + ] + } + }, + "fields": { + "op": { + "type": "Operator", + "id": 1 + }, + "field": { + "type": "FieldReference", + "id": 2 + } + }, + "nested": { + "Operator": { + "values": { + "OPERATOR_UNSPECIFIED": 0, + "IS_NAN": 2, + "IS_NULL": 3, + "IS_NOT_NAN": 4, + "IS_NOT_NULL": 5 + } + } + } + }, + "FieldReference": { + "fields": { + "fieldPath": { + "type": "string", + "id": 2 + } + } + }, + "Order": { + "fields": { + "field": { + "type": "FieldReference", + "id": 1 + }, + "direction": { + "type": "Direction", + "id": 2 + } + } + }, + "Projection": { + "fields": { + "fields": { + "rule": "repeated", + "type": "FieldReference", + "id": 2 + } + } + }, + "Direction": { + "values": { + "DIRECTION_UNSPECIFIED": 0, + "ASCENDING": 1, + "DESCENDING": 2 + } + } + } + }, + "Cursor": { + "fields": { + "values": { + "rule": "repeated", + "type": "Value", + "id": 1 + }, + "before": { + "type": "bool", + "id": 2 + } + } + }, + "Write": { + "oneofs": { + "operation": { + "oneof": [ + "update", + "delete", + "transform" + ] + } + }, + "fields": { + "update": { + "type": "Document", + "id": 1 + }, + "delete": { + "type": "string", + "id": 2 + }, + "transform": { + "type": "DocumentTransform", + "id": 6 + }, + "updateMask": { + "type": "DocumentMask", + "id": 3 + }, + "updateTransforms": { + "rule": "repeated", + "type": "DocumentTransform.FieldTransform", + "id": 7 + }, + "currentDocument": { + "type": "Precondition", + "id": 4 + } + } + }, + "DocumentTransform": { + "fields": { + "document": { + "type": "string", + "id": 1 + }, + "fieldTransforms": { + "rule": "repeated", + "type": "FieldTransform", + "id": 2 + } + }, + "nested": { + "FieldTransform": { + "oneofs": { + "transformType": { + "oneof": [ + "setToServerValue", + "increment", + "maximum", + "minimum", + "appendMissingElements", + "removeAllFromArray" + ] + } + }, + "fields": { + "fieldPath": { + "type": "string", + "id": 1 + }, + "setToServerValue": { + "type": "ServerValue", + "id": 2 + }, + "increment": { + "type": "Value", + "id": 3 + }, + "maximum": { + "type": "Value", + "id": 4 + }, + "minimum": { + "type": "Value", + "id": 5 + }, + "appendMissingElements": { + "type": "ArrayValue", + "id": 6 + }, + "removeAllFromArray": { + "type": "ArrayValue", + "id": 7 + } + }, + "nested": { + "ServerValue": { + "values": { + "SERVER_VALUE_UNSPECIFIED": 0, + "REQUEST_TIME": 1 + } + } + } + } + } + }, + "WriteResult": { + "fields": { + "updateTime": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "transformResults": { + "rule": "repeated", + "type": "Value", + "id": 2 + } + } + }, + "DocumentChange": { + "fields": { + "document": { + "type": "Document", + "id": 1 + }, + "targetIds": { + "rule": "repeated", + "type": "int32", + "id": 5 + }, + "removedTargetIds": { + "rule": "repeated", + "type": "int32", + "id": 6 + } + } + }, + "DocumentDelete": { + "fields": { + "document": { + "type": "string", + "id": 1 + }, + "removedTargetIds": { + "rule": "repeated", + "type": "int32", + "id": 6 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + } + } + }, + "DocumentRemove": { + "fields": { + "document": { + "type": "string", + "id": 1 + }, + "removedTargetIds": { + "rule": "repeated", + "type": "int32", + "id": 2 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + } + } + }, + "ExistenceFilter": { + "fields": { + "targetId": { + "type": "int32", + "id": 1 + }, + "count": { + "type": "int32", + "id": 2 + } + } + }, + "UndeliverableFirstGenEvent": { + "fields": { + "message": { + "type": "string", + "id": 1 + }, + "reason": { + "type": "Reason", + "id": 2 + }, + "documentName": { + "type": "string", + "id": 3 + }, + "documentChangeType": { + "type": "DocumentChangeType", + "id": 4 + }, + "functionName": { + "rule": "repeated", + "type": "string", + "id": 5 + }, + "triggeredTime": { + "type": "google.protobuf.Timestamp", + "id": 6 + } + }, + "nested": { + "Reason": { + "values": { + "REASON_UNSPECIFIED": 0, + "EXCEEDING_SIZE_LIMIT": 1 + } + }, + "DocumentChangeType": { + "values": { + "DOCUMENT_CHANGE_TYPE_UNSPECIFIED": 0, + "CREATE": 1, + "DELETE": 2, + "UPDATE": 3 + } + } + } + } + } + } + } + }, + "type": { + "options": { + "cc_enable_arenas": true, + "go_package": "google.golang.org/genproto/googleapis/type/dayofweek;dayofweek", + "java_multiple_files": true, + "java_outer_classname": "DayOfWeekProto", + "java_package": "com.google.type", + "objc_class_prefix": "GTP" + }, + "nested": { + "LatLng": { + "fields": { + "latitude": { + "type": "double", + "id": 1 + }, + "longitude": { + "type": "double", + "id": 2 + } + } + }, + "DayOfWeek": { + "values": { + "DAY_OF_WEEK_UNSPECIFIED": 0, + "MONDAY": 1, + "TUESDAY": 2, + "WEDNESDAY": 3, + "THURSDAY": 4, + "FRIDAY": 5, + "SATURDAY": 6, + "SUNDAY": 7 + } + } + } + }, + "api": { + "options": { + "go_package": "google.golang.org/genproto/googleapis/api/annotations;annotations", + "java_multiple_files": true, + "java_outer_classname": "RoutingProto", + "java_package": "com.google.api", + "objc_class_prefix": "GAPI" + }, + "nested": { + "http": { + "type": "HttpRule", + "id": 72295728, + "extend": "google.protobuf.MethodOptions" + }, + "Http": { + "fields": { + "rules": { + "rule": "repeated", + "type": "HttpRule", + "id": 1 + }, + "fullyDecodeReservedExpansion": { + "type": "bool", + "id": 2 + } + } + }, + "HttpRule": { + "oneofs": { + "pattern": { + "oneof": [ + "get", + "put", + "post", + "delete", + "patch", + "custom" + ] + } + }, + "fields": { + "selector": { + "type": "string", + "id": 1 + }, + "get": { + "type": "string", + "id": 2 + }, + "put": { + "type": "string", + "id": 3 + }, + "post": { + "type": "string", + "id": 4 + }, + "delete": { + "type": "string", + "id": 5 + }, + "patch": { + "type": "string", + "id": 6 + }, + "custom": { + "type": "CustomHttpPattern", + "id": 8 + }, + "body": { + "type": "string", + "id": 7 + }, + "responseBody": { + "type": "string", + "id": 12 + }, + "additionalBindings": { + "rule": "repeated", + "type": "HttpRule", + "id": 11 + } + } + }, + "CustomHttpPattern": { + "fields": { + "kind": { + "type": "string", + "id": 1 + }, + "path": { + "type": "string", + "id": 2 + } + } + }, + "methodSignature": { + "rule": "repeated", + "type": "string", + "id": 1051, + "extend": "google.protobuf.MethodOptions" + }, + "defaultHost": { + "type": "string", + "id": 1049, + "extend": "google.protobuf.ServiceOptions" + }, + "oauthScopes": { + "type": "string", + "id": 1050, + "extend": "google.protobuf.ServiceOptions" + }, + "apiVersion": { + "type": "string", + "id": 525000001, + "extend": "google.protobuf.ServiceOptions" + }, + "CommonLanguageSettings": { + "fields": { + "referenceDocsUri": { + "type": "string", + "id": 1, + "options": { + "deprecated": true + } + }, + "destinations": { + "rule": "repeated", + "type": "ClientLibraryDestination", + "id": 2 + }, + "selectiveGapicGeneration": { + "type": "SelectiveGapicGeneration", + "id": 3 + } + } + }, + "ClientLibrarySettings": { + "fields": { + "version": { + "type": "string", + "id": 1 + }, + "launchStage": { + "type": "LaunchStage", + "id": 2 + }, + "restNumericEnums": { + "type": "bool", + "id": 3 + }, + "javaSettings": { + "type": "JavaSettings", + "id": 21 + }, + "cppSettings": { + "type": "CppSettings", + "id": 22 + }, + "phpSettings": { + "type": "PhpSettings", + "id": 23 + }, + "pythonSettings": { + "type": "PythonSettings", + "id": 24 + }, + "nodeSettings": { + "type": "NodeSettings", + "id": 25 + }, + "dotnetSettings": { + "type": "DotnetSettings", + "id": 26 + }, + "rubySettings": { + "type": "RubySettings", + "id": 27 + }, + "goSettings": { + "type": "GoSettings", + "id": 28 + } + } + }, + "Publishing": { + "fields": { + "methodSettings": { + "rule": "repeated", + "type": "MethodSettings", + "id": 2 + }, + "newIssueUri": { + "type": "string", + "id": 101 + }, + "documentationUri": { + "type": "string", + "id": 102 + }, + "apiShortName": { + "type": "string", + "id": 103 + }, + "githubLabel": { + "type": "string", + "id": 104 + }, + "codeownerGithubTeams": { + "rule": "repeated", + "type": "string", + "id": 105 + }, + "docTagPrefix": { + "type": "string", + "id": 106 + }, + "organization": { + "type": "ClientLibraryOrganization", + "id": 107 + }, + "librarySettings": { + "rule": "repeated", + "type": "ClientLibrarySettings", + "id": 109 + }, + "protoReferenceDocumentationUri": { + "type": "string", + "id": 110 + }, + "restReferenceDocumentationUri": { + "type": "string", + "id": 111 + } + } + }, + "JavaSettings": { + "fields": { + "libraryPackage": { + "type": "string", + "id": 1 + }, + "serviceClassNames": { + "keyType": "string", + "type": "string", + "id": 2 + }, + "common": { + "type": "CommonLanguageSettings", + "id": 3 + } + } + }, + "CppSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "PhpSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "PythonSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + }, + "experimentalFeatures": { + "type": "ExperimentalFeatures", + "id": 2 + } + }, + "nested": { + "ExperimentalFeatures": { + "fields": { + "restAsyncIoEnabled": { + "type": "bool", + "id": 1 + }, + "protobufPythonicTypesEnabled": { + "type": "bool", + "id": 2 + }, + "unversionedPackageDisabled": { + "type": "bool", + "id": 3 + } + } + } + } + }, + "NodeSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "DotnetSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + }, + "renamedServices": { + "keyType": "string", + "type": "string", + "id": 2 + }, + "renamedResources": { + "keyType": "string", + "type": "string", + "id": 3 + }, + "ignoredResources": { + "rule": "repeated", + "type": "string", + "id": 4 + }, + "forcedNamespaceAliases": { + "rule": "repeated", + "type": "string", + "id": 5 + }, + "handwrittenSignatures": { + "rule": "repeated", + "type": "string", + "id": 6 + } + } + }, + "RubySettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "GoSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + }, + "renamedServices": { + "keyType": "string", + "type": "string", + "id": 2 + } + } + }, + "MethodSettings": { + "fields": { + "selector": { + "type": "string", + "id": 1 + }, + "longRunning": { + "type": "LongRunning", + "id": 2 + }, + "autoPopulatedFields": { + "rule": "repeated", + "type": "string", + "id": 3 + } + }, + "nested": { + "LongRunning": { + "fields": { + "initialPollDelay": { + "type": "google.protobuf.Duration", + "id": 1 + }, + "pollDelayMultiplier": { + "type": "float", + "id": 2 + }, + "maxPollDelay": { + "type": "google.protobuf.Duration", + "id": 3 + }, + "totalPollTimeout": { + "type": "google.protobuf.Duration", + "id": 4 + } + } + } + } + }, + "ClientLibraryOrganization": { + "values": { + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED": 0, + "CLOUD": 1, + "ADS": 2, + "PHOTOS": 3, + "STREET_VIEW": 4, + "SHOPPING": 5, + "GEO": 6, + "GENERATIVE_AI": 7 + } + }, + "ClientLibraryDestination": { + "values": { + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED": 0, + "GITHUB": 10, + "PACKAGE_MANAGER": 20 + } + }, + "SelectiveGapicGeneration": { + "fields": { + "methods": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "generateOmittedAsInternal": { + "type": "bool", + "id": 2 + } + } + }, + "LaunchStage": { + "values": { + "LAUNCH_STAGE_UNSPECIFIED": 0, + "UNIMPLEMENTED": 6, + "PRELAUNCH": 7, + "EARLY_ACCESS": 1, + "ALPHA": 2, + "BETA": 3, + "GA": 4, + "DEPRECATED": 5 + } + }, + "fieldBehavior": { + "rule": "repeated", + "type": "google.api.FieldBehavior", + "id": 1052, + "extend": "google.protobuf.FieldOptions", + "options": { + "packed": false + } + }, + "FieldBehavior": { + "values": { + "FIELD_BEHAVIOR_UNSPECIFIED": 0, + "OPTIONAL": 1, + "REQUIRED": 2, + "OUTPUT_ONLY": 3, + "INPUT_ONLY": 4, + "IMMUTABLE": 5, + "UNORDERED_LIST": 6, + "NON_EMPTY_DEFAULT": 7, + "IDENTIFIER": 8 + } + }, + "resourceReference": { + "type": "google.api.ResourceReference", + "id": 1055, + "extend": "google.protobuf.FieldOptions" + }, + "resourceDefinition": { + "rule": "repeated", + "type": "google.api.ResourceDescriptor", + "id": 1053, + "extend": "google.protobuf.FileOptions" + }, + "resource": { + "type": "google.api.ResourceDescriptor", + "id": 1053, + "extend": "google.protobuf.MessageOptions" + }, + "ResourceDescriptor": { + "fields": { + "type": { + "type": "string", + "id": 1 + }, + "pattern": { + "rule": "repeated", + "type": "string", + "id": 2 + }, + "nameField": { + "type": "string", + "id": 3 + }, + "history": { + "type": "History", + "id": 4 + }, + "plural": { + "type": "string", + "id": 5 + }, + "singular": { + "type": "string", + "id": 6 + }, + "style": { + "rule": "repeated", + "type": "Style", + "id": 10 + } + }, + "nested": { + "History": { + "values": { + "HISTORY_UNSPECIFIED": 0, + "ORIGINALLY_SINGLE_PATTERN": 1, + "FUTURE_MULTI_PATTERN": 2 + } + }, + "Style": { + "values": { + "STYLE_UNSPECIFIED": 0, + "DECLARATIVE_FRIENDLY": 1 + } + } + } + }, + "ResourceReference": { + "fields": { + "type": { + "type": "string", + "id": 1 + }, + "childType": { + "type": "string", + "id": 2 + } + } + }, + "routing": { + "type": "google.api.RoutingRule", + "id": 72295729, + "extend": "google.protobuf.MethodOptions" + }, + "RoutingRule": { + "fields": { + "routingParameters": { + "rule": "repeated", + "type": "RoutingParameter", + "id": 2 + } + } + }, + "RoutingParameter": { + "fields": { + "field": { + "type": "string", + "id": 1 + }, + "pathTemplate": { + "type": "string", + "id": 2 + } + } + } + } + }, + "rpc": { + "options": { + "cc_enable_arenas": true, + "go_package": "google.golang.org/genproto/googleapis/rpc/status;status", + "java_multiple_files": true, + "java_outer_classname": "StatusProto", + "java_package": "com.google.rpc", + "objc_class_prefix": "RPC" + }, + "nested": { + "Status": { + "fields": { + "code": { + "type": "int32", + "id": 1 + }, + "message": { + "type": "string", + "id": 2 + }, + "details": { + "rule": "repeated", + "type": "google.protobuf.Any", + "id": 3 + } + } + } + } + } + } + } + } +} diff --git a/handwritten/firestore/dev/src/aggregate.ts b/handwritten/firestore/dev/src/aggregate.ts new file mode 100644 index 00000000000..c0fe62dca6d --- /dev/null +++ b/handwritten/firestore/dev/src/aggregate.ts @@ -0,0 +1,165 @@ +/** + * Copyright 2023 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; + +import {FieldPath} from './path'; +import {google} from '../protos/firestore_v1_proto_api'; + +import IAggregation = google.firestore.v1.StructuredAggregationQuery.IAggregation; +import * as assert from 'assert'; + +/** + * Concrete implementation of the Aggregate type. + */ +export class Aggregate { + constructor( + readonly alias: string, + readonly aggregateType: AggregateType, + readonly fieldPath?: string | FieldPath, + ) {} + + /** + * Converts this object to the proto representation of an Aggregate. + * @internal + */ + toProto(): IAggregation { + const proto: IAggregation = {}; + if (this.aggregateType === 'count') { + proto.count = {}; + } else if (this.aggregateType === 'sum') { + assert( + this.fieldPath !== undefined, + 'Missing field path for sum aggregation.', + ); + proto.sum = { + field: { + fieldPath: FieldPath.fromArgument(this.fieldPath!).formattedName, + }, + }; + } else if (this.aggregateType === 'avg') { + assert( + this.fieldPath !== undefined, + 'Missing field path for average aggregation.', + ); + proto.avg = { + field: { + fieldPath: FieldPath.fromArgument(this.fieldPath!).formattedName, + }, + }; + } else { + throw new Error(`Aggregate type ${this.aggregateType} unimplemented.`); + } + proto.alias = this.alias; + return proto; + } +} + +/** + * Represents an aggregation that can be performed by Firestore. + */ +export class AggregateField implements firestore.AggregateField { + /** A type string to uniquely identify instances of this class. */ + readonly type = 'AggregateField'; + + /** + * The field on which the aggregation is performed. + * @internal + **/ + public readonly _field?: string | FieldPath; + + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param field Optionally specifies the field that is aggregated. + * @internal + */ + private constructor( + public readonly aggregateType: AggregateType, + field?: string | FieldPath, + ) { + this._field = field; + } + + /** + * Compares this object with the given object for equality. + * + * This object is considered "equal" to the other object if and only if + * `other` performs the same kind of aggregation on the same field (if any). + * + * @param other The object to compare to this object for equality. + * @returns `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual(other: AggregateField): boolean { + return ( + other instanceof AggregateField && + this.aggregateType === other.aggregateType && + ((this._field === undefined && other._field === undefined) || + (this._field !== undefined && + other._field !== undefined && + FieldPath.fromArgument(this._field).isEqual( + FieldPath.fromArgument(other._field), + ))) + ); + } + + /** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ + static count(): AggregateField { + return new AggregateField('count'); + } + + /** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ + static average(field: string | FieldPath): AggregateField { + return new AggregateField('avg', field); + } + + /** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ + static sum(field: string | FieldPath): AggregateField { + return new AggregateField('sum', field); + } +} + +/** + * A type whose property values are all `AggregateField` objects. + */ +export interface AggregateSpec { + [field: string]: AggregateFieldType; +} + +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export type AggregateFieldType = + | ReturnType + | ReturnType + | ReturnType; + +/** + * Union type representing the aggregate type to be performed. + */ +export type AggregateType = 'count' | 'avg' | 'sum'; diff --git a/handwritten/firestore/dev/src/backoff.ts b/handwritten/firestore/dev/src/backoff.ts new file mode 100644 index 00000000000..e672d75d655 --- /dev/null +++ b/handwritten/firestore/dev/src/backoff.ts @@ -0,0 +1,312 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {logger} from './logger'; + +/* + * @module firestore/backoff + * @private + * @internal + * + * Contains backoff logic to facilitate RPC error handling. This class derives + * its implementation from the Firestore Mobile Web Client. + * + * @see https://github.com/firebase/firebase-js-sdk/blob/master/packages/firestore/src/remote/backoff.ts + */ + +/*! + * The default initial backoff time in milliseconds after an error. + * Set to 1s according to https://cloud.google.com/apis/design/errors. + */ +export const DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000; + +/*! + * The default maximum backoff time in milliseconds. + */ +export const DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000; + +/*! + * The default factor to increase the backup by after each failed attempt. + */ +export const DEFAULT_BACKOFF_FACTOR = 1.5; + +/*! + * The default jitter to distribute the backoff attempts by (0 means no + * randomization, 1.0 means +/-50% randomization). + */ +const DEFAULT_JITTER_FACTOR = 1.0; + +/*! + * The maximum number of retries that will be attempted by backoff + * before stopping all retry attempts. + */ +export const MAX_RETRY_ATTEMPTS = 10; + +/*! + * The timeout handler used by `ExponentialBackoff` and `BulkWriter`. + */ +export let delayExecution: (f: () => void, ms: number) => NodeJS.Timeout = + setTimeout; + +/** + * Allows overriding of the timeout handler used by the exponential backoff + * implementation. If not invoked, we default to `setTimeout()`. + * + * Used only in testing. + * + * @private + * @internal + * @param {function} handler A handler than matches the API of `setTimeout()`. + */ +export function setTimeoutHandler( + handler: (f: () => void, ms: number) => void, +): void { + delayExecution = (f: () => void, ms: number) => { + handler(f, ms); + const timeout: NodeJS.Timeout = { + hasRef: () => { + throw new Error('For tests only. Not Implemented'); + }, + ref: () => { + throw new Error('For tests only. Not Implemented'); + }, + refresh: () => { + throw new Error('For tests only. Not Implemented'); + }, + unref: () => { + throw new Error('For tests only. Not Implemented'); + }, + [Symbol.toPrimitive]: () => { + throw new Error('For tests only. Not Implemented'); + }, + } as unknown as NodeJS.Timeout; + // `NodeJS.Timeout` type signature change: + // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/66176/files#diff-e838d0ace9cd5f6516bacfbd3ad00d02cd37bd60f9993ce6223f52d889a1fdbaR122-R126 + // + // Adding `[Symbol.dispose](): void;` cannot be done on older versions of + // NodeJS. So we simply cast to `NodeJS.Timeout`. + return timeout; + }; +} + +/** + * Configuration object to adjust the delays of the exponential backoff + * algorithm. + * + * @private + * @internal + */ +export interface ExponentialBackoffSetting { + /** Optional override for the initial retry delay. */ + initialDelayMs?: number; + /** Optional override for the exponential backoff factor. */ + backoffFactor?: number; + /** Optional override for the maximum retry delay. */ + maxDelayMs?: number; + /** + * Optional override to control the itter factor by which to randomize + * attempts (0 means no randomization, 1.0 means +/-50% randomization). It is + * suggested not to exceed this range. + */ + jitterFactor?: number; +} + +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a "jitter" (+/- 50% by default) that is calculated and + * added to the base delay. This prevents clients from accidentally + * synchronizing their delays causing spikes of load to the backend. + * + * @private + * @internal + */ +export class ExponentialBackoff { + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs (based on a jitter factor of 1.0). + * + * @private + * @internal + */ + private readonly initialDelayMs: number; + + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + * + * @private + * @internal + */ + private readonly backoffFactor: number; + + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs (based on a jitter factor of 1.0). + * + * @private + * @internal + */ + private readonly maxDelayMs: number; + + /** + * The jitter factor that controls the random distribution of the backoff + * points. + * + * @private + * @internal + */ + private readonly jitterFactor: number; + + /** + * The number of retries that has been attempted. + * + * @private + * @internal + */ + private _retryCount = 0; + + /** + * The backoff delay of the current attempt. + * + * @private + * @internal + */ + private currentBaseMs = 0; + + /** + * Whether we are currently waiting for backoff to complete. + * + * @private + * @internal + */ + private awaitingBackoffCompletion = false; + + constructor(options: ExponentialBackoffSetting = {}) { + this.initialDelayMs = + options.initialDelayMs !== undefined + ? options.initialDelayMs + : DEFAULT_BACKOFF_INITIAL_DELAY_MS; + this.backoffFactor = + options.backoffFactor !== undefined + ? options.backoffFactor + : DEFAULT_BACKOFF_FACTOR; + this.maxDelayMs = + options.maxDelayMs !== undefined + ? options.maxDelayMs + : DEFAULT_BACKOFF_MAX_DELAY_MS; + this.jitterFactor = + options.jitterFactor !== undefined + ? options.jitterFactor + : DEFAULT_JITTER_FACTOR; + } + + /** + * Resets the backoff delay and retry count. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + * + * @private + * @internal + */ + reset(): void { + this._retryCount = 0; + this.currentBaseMs = 0; + } + + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + * + * @private + * @internal + */ + resetToMax(): void { + this.currentBaseMs = this.maxDelayMs; + } + + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. + * + * @returns A Promise that resolves when the current delay elapsed. + * @private + * @internal + */ + backoffAndWait(): Promise { + if (this.awaitingBackoffCompletion) { + return Promise.reject( + new Error('A backoff operation is already in progress.'), + ); + } + + if (this.retryCount > MAX_RETRY_ATTEMPTS) { + return Promise.reject( + new Error('Exceeded maximum number of retries allowed.'), + ); + } + // First schedule using the current base (which may be 0 and should be + // honored as such). + const delayWithJitterMs = this.currentBaseMs + this.jitterDelayMs(); + if (this.currentBaseMs > 0) { + logger( + 'ExponentialBackoff.backoffAndWait', + null, + `Backing off for ${delayWithJitterMs} ms ` + + `(base delay: ${this.currentBaseMs} ms)`, + ); + } + + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.currentBaseMs *= this.backoffFactor; + this.currentBaseMs = Math.max(this.currentBaseMs, this.initialDelayMs); + this.currentBaseMs = Math.min(this.currentBaseMs, this.maxDelayMs); + this._retryCount += 1; + + return new Promise(resolve => { + this.awaitingBackoffCompletion = true; + + delayExecution(() => { + this.awaitingBackoffCompletion = false; + resolve(); + }, delayWithJitterMs); + }); + } + + // Visible for testing. + get retryCount(): number { + return this._retryCount; + } + + /** + * Returns a randomized "jitter" delay based on the current base and jitter + * factor. + * + * @returns {number} The jitter to apply based on the current delay. + * @private + * @internal + */ + private jitterDelayMs(): number { + return (Math.random() - 0.5) * this.jitterFactor * this.currentBaseMs; + } +} diff --git a/handwritten/firestore/dev/src/bulk-writer.ts b/handwritten/firestore/dev/src/bulk-writer.ts new file mode 100644 index 00000000000..251baefb49b --- /dev/null +++ b/handwritten/firestore/dev/src/bulk-writer.ts @@ -0,0 +1,1206 @@ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as firestore from '@google-cloud/firestore'; + +import * as assert from 'assert'; +import type {GoogleError} from 'google-gax'; + +import {google} from '../protos/firestore_v1_proto_api'; +import {FieldPath, Firestore} from '.'; +import { + DEFAULT_BACKOFF_FACTOR, + DEFAULT_BACKOFF_INITIAL_DELAY_MS, + DEFAULT_BACKOFF_MAX_DELAY_MS, + delayExecution, + MAX_RETRY_ATTEMPTS, +} from './backoff'; +import {RateLimiter} from './rate-limiter'; +import {Timestamp} from './timestamp'; +import { + Deferred, + getRetryCodes, + isObject, + requestTag, + silencePromise, + wrapError, +} from './util'; +import {WriteBatch, WriteResult} from './write-batch'; +import { + invalidArgumentMessage, + validateInteger, + validateOptional, +} from './validate'; +import {logger} from './logger'; +import {StatusCode} from './status-code'; + +// eslint-disable-next-line no-undef +import GrpcStatus = FirebaseFirestore.GrpcStatus; +import api = google.firestore.v1; +import { + ATTRIBUTE_KEY_DOC_COUNT, + SPAN_NAME_BULK_WRITER_COMMIT, +} from './telemetry/trace-util'; + +/*! + * The maximum number of writes that can be in a single batch. + */ +const MAX_BATCH_SIZE = 20; + +/*! + * The maximum number of writes can be can in a single batch that is being retried. + */ +export const RETRY_MAX_BATCH_SIZE = 10; + +/*! + * The starting maximum number of operations per second as allowed by the + * 500/50/5 rule. + * + * https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic. + */ +export const DEFAULT_INITIAL_OPS_PER_SECOND_LIMIT = 500; + +/*! + * The maximum number of operations per second as allowed by the 500/50/5 rule. + * By default the rate limiter will not exceed this value. + * + * https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic. + */ +export const DEFAULT_MAXIMUM_OPS_PER_SECOND_LIMIT = 10000; + +/*! + * The default jitter to apply to the exponential backoff used in retries. For + * example, a factor of 0.3 means a 30% jitter is applied. + */ +export const DEFAULT_JITTER_FACTOR = 0.3; + +/*! + * The rate by which to increase the capacity as specified by the 500/50/5 rule. + */ +const RATE_LIMITER_MULTIPLIER = 1.5; + +/*! + * How often the operations per second capacity should increase in milliseconds + * as specified by the 500/50/5 rule. + */ +const RATE_LIMITER_MULTIPLIER_MILLIS = 5 * 60 * 1000; + +/*! + * The default maximum number of pending operations that can be enqueued onto a + * BulkWriter instance. An operation is considered pending if BulkWriter has + * sent it via RPC and is awaiting the result. BulkWriter buffers additional + * writes after this many pending operations in order to avoiding going OOM. + */ +const DEFAULT_MAXIMUM_PENDING_OPERATIONS_COUNT = 500; + +/** + * Represents a single write for BulkWriter, encapsulating operation dispatch + * and error handling. + * @private + * @internal + */ +class BulkWriterOperation { + private deferred = new Deferred(); + private failedAttempts = 0; + private lastStatus?: StatusCode; + private _backoffDuration = 0; + + /** Whether flush() was called when this was the last enqueued operation. */ + private _flushed = false; + + /** + * @param ref The document reference being written to. + * @param type The type of operation that created this write. + * @param sendFn A callback to invoke when the operation should be sent. + * @param errorFn The user provided global error callback. + * @param successFn The user provided global success callback. + */ + constructor( + readonly ref: firestore.DocumentReference, + private readonly type: 'create' | 'set' | 'update' | 'delete', + private readonly sendFn: (op: BulkWriterOperation) => void, + private readonly errorFn: (error: BulkWriterError) => boolean, + private readonly successFn: ( + ref: firestore.DocumentReference, + result: WriteResult, + ) => void, + ) {} + + get promise(): Promise { + return this.deferred.promise; + } + + get backoffDuration(): number { + return this._backoffDuration; + } + + markFlushed(): void { + this._flushed = true; + } + + get flushed(): boolean { + return this._flushed; + } + + onError(error: GoogleError): void { + ++this.failedAttempts; + + try { + const bulkWriterError = new BulkWriterError( + error.code as number as GrpcStatus, + error.message, + this.ref, + this.type, + this.failedAttempts, + ); + const shouldRetry = this.errorFn(bulkWriterError); + logger( + 'BulkWriter.errorFn', + null, + 'Ran error callback on error code:', + error.code, + ', shouldRetry:', + shouldRetry, + ' for document:', + this.ref.path, + ); + + if (shouldRetry) { + this.lastStatus = error.code as number; + this.updateBackoffDuration(); + this.sendFn(this); + } else { + this.deferred.reject(bulkWriterError); + } + } catch (userCallbackError) { + this.deferred.reject(userCallbackError); + } + } + + private updateBackoffDuration(): void { + if (this.lastStatus === StatusCode.RESOURCE_EXHAUSTED) { + this._backoffDuration = DEFAULT_BACKOFF_MAX_DELAY_MS; + } else if (this._backoffDuration === 0) { + this._backoffDuration = DEFAULT_BACKOFF_INITIAL_DELAY_MS; + } else { + this._backoffDuration *= DEFAULT_BACKOFF_FACTOR; + } + } + + onSuccess(result: WriteResult): void { + try { + this.successFn(this.ref, result); + this.deferred.resolve(result); + } catch (userCallbackError) { + this.deferred.reject(userCallbackError); + } + } +} + +/** + * Used to represent a batch on the BatchQueue. + * + * @private + * @internal + */ +class BulkCommitBatch extends WriteBatch { + // The set of document reference paths present in the WriteBatch. + readonly docPaths = new Set(); + + // An array of pending write operations. Only contains writes that have not + // been resolved. + readonly pendingOps: Array = []; + + private _maxBatchSize: number; + + constructor(firestore: Firestore, maxBatchSize: number) { + super(firestore); + this._maxBatchSize = maxBatchSize; + } + + get maxBatchSize(): number { + return this._maxBatchSize; + } + + setMaxBatchSize(size: number): void { + assert( + this.pendingOps.length <= size, + 'New batch size cannot be less than the number of enqueued writes', + ); + this._maxBatchSize = size; + } + + has(documentRef: firestore.DocumentReference): boolean { + return this.docPaths.has(documentRef.path); + } + + async bulkCommit(options: {requestTag?: string} = {}): Promise { + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_BULK_WRITER_COMMIT, + async () => { + const tag = options?.requestTag ?? requestTag(); + + // Capture the error stack to preserve stack tracing across async calls. + const stack = Error().stack!; + + let response: api.IBatchWriteResponse; + try { + logger( + 'BulkCommitBatch.bulkCommit', + tag, + `Sending next batch with ${this._opCount} writes`, + ); + const retryCodes = getRetryCodes('batchWrite'); + response = await this._commit< + api.BatchWriteRequest, + api.BatchWriteResponse + >({retryCodes, methodName: 'batchWrite', requestTag: tag}); + } catch (err) { + // Map the failure to each individual write's result. + const ops = Array.from({length: this.pendingOps.length}); + response = { + writeResults: ops.map(() => { + return {}; + }), + status: ops.map(() => err), + }; + } + + for (let i = 0; i < (response.writeResults || []).length; ++i) { + // Since delete operations currently do not have write times, use a + // sentinel Timestamp value. + // TODO(b/158502664): Use actual delete timestamp. + const DELETE_TIMESTAMP_SENTINEL = Timestamp.fromMillis(0); + + const status = (response.status || [])[i]; + if (status.code === StatusCode.OK) { + const updateTime = Timestamp.fromProto( + response.writeResults![i].updateTime || DELETE_TIMESTAMP_SENTINEL, + ); + this.pendingOps[i].onSuccess(new WriteResult(updateTime)); + } else { + const error = new (require('google-gax/fallback').GoogleError)( + status.message || undefined, + ); + error.code = status.code as number; + this.pendingOps[i].onError(wrapError(error, stack)); + } + } + }, + { + [ATTRIBUTE_KEY_DOC_COUNT]: this._opCount, + }, + ); + } + + /** + * Helper to update data structures associated with the operation and returns + * the result. + */ + processLastOperation(op: BulkWriterOperation): void { + assert( + !this.docPaths.has(op.ref.path), + 'Batch should not contain writes to the same document', + ); + this.docPaths.add(op.ref.path); + this.pendingOps.push(op); + } +} + +/** + * Used to represent a buffered BulkWriterOperation. + * + * @private + * @internal + */ +class BufferedOperation { + constructor( + readonly operation: BulkWriterOperation, + readonly sendFn: () => void, + ) {} +} + +/** + * The error thrown when a BulkWriter operation fails. + * + * @class BulkWriterError + */ +export class BulkWriterError extends Error { + /** + * @private + * @internal + */ + constructor( + /** The status code of the error. */ + readonly code: GrpcStatus, + + /** The error message of the error. */ + readonly message: string, + + /** The document reference the operation was performed on. */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + readonly documentRef: firestore.DocumentReference, + + /** The type of operation performed. */ + readonly operationType: 'create' | 'set' | 'update' | 'delete', + + /** How many times this operation has been attempted unsuccessfully. */ + readonly failedAttempts: number, + ) { + super(message); + } +} + +/** + * A Firestore BulkWriter that can be used to perform a large number of writes + * in parallel. + * + * @class BulkWriter + */ +export class BulkWriter { + /** + * The maximum number of writes that can be in a single batch. + * Visible for testing. + * @private + * @internal + */ + private _maxBatchSize = MAX_BATCH_SIZE; + + /** + * The batch that is currently used to schedule operations. Once this batch + * reaches maximum capacity, a new batch is created. + * @private + * @internal + */ + private _bulkCommitBatch: BulkCommitBatch; + + /** + * A pointer to the tail of all active BulkWriter operations. This pointer + * is advanced every time a new write is enqueued. + * @private + * @internal + */ + private _lastOp: Promise = Promise.resolve(); + + /** + * When this BulkWriter instance has started to close, a flush promise is + * saved. Afterwards, no new operations can be enqueued, except for retry + * operations scheduled by the error handler. + * @private + * @internal + */ + private _closePromise: Promise | undefined; + + /** + * Rate limiter used to throttle requests as per the 500/50/5 rule. + * Visible for testing. + * @private + * @internal + */ + readonly _rateLimiter: RateLimiter; + + /** + * The number of pending operations enqueued on this BulkWriter instance. + * An operation is considered pending if BulkWriter has sent it via RPC and + * is awaiting the result. + * @private + * @internal + */ + private _pendingOpsCount = 0; + + /** + * An array containing buffered BulkWriter operations after the maximum number + * of pending operations has been enqueued. + * @private + * @internal + */ + private _bufferedOperations: Array = []; + + /** + * Whether a custom error handler has been set. BulkWriter only swallows + * errors if an error handler is set. Otherwise, an UnhandledPromiseRejection + * is thrown by Node if an operation promise is rejected without being + * handled. + * @private + * @internal + */ + private _errorHandlerSet = false; + + // Visible for testing. + /** + * @private + * @internal + */ + _getBufferedOperationsCount(): number { + return this._bufferedOperations.length; + } + + // Visible for testing. + /** + * @private + * @internal + */ + _setMaxBatchSize(size: number): void { + assert( + this._bulkCommitBatch.pendingOps.length === 0, + 'BulkCommitBatch should be empty', + ); + this._maxBatchSize = size; + this._bulkCommitBatch = new BulkCommitBatch(this.firestore, size); + } + + /** + * The maximum number of pending operations that can be enqueued onto this + * BulkWriter instance. Once the this number of writes have been enqueued, + * subsequent writes are buffered. + * @private + * @internal + */ + private _maxPendingOpCount = DEFAULT_MAXIMUM_PENDING_OPERATIONS_COUNT; + + // Visible for testing. + /** + * @private + * @internal + */ + _setMaxPendingOpCount(newMax: number): void { + this._maxPendingOpCount = newMax; + } + + /** + * The user-provided callback to be run every time a BulkWriter operation + * successfully completes. + * @private + * @internal + */ + private _successFn: ( + document: firestore.DocumentReference, + result: WriteResult, + ) => void = () => {}; + + /** + * The user-provided callback to be run every time a BulkWriter operation + * fails. + * @private + * @internal + */ + private _errorFn: (error: BulkWriterError) => boolean = error => { + const isRetryableDeleteError = + error.operationType === 'delete' && + (error.code as number) === StatusCode.INTERNAL; + const retryCodes = getRetryCodes('batchWrite'); + return ( + (retryCodes.includes(error.code) || isRetryableDeleteError) && + error.failedAttempts < MAX_RETRY_ATTEMPTS + ); + }; + + /** @private */ + constructor( + private readonly firestore: Firestore, + options?: firestore.BulkWriterOptions, + ) { + this._bulkCommitBatch = new BulkCommitBatch( + this.firestore, + this._maxBatchSize, + ); + + this.firestore._incrementBulkWritersCount(); + validateBulkWriterOptions(options); + + if (options?.throttling === false) { + this._rateLimiter = new RateLimiter( + Number.POSITIVE_INFINITY, + Number.POSITIVE_INFINITY, + Number.POSITIVE_INFINITY, + Number.POSITIVE_INFINITY, + ); + } else { + let startingRate = DEFAULT_INITIAL_OPS_PER_SECOND_LIMIT; + let maxRate = DEFAULT_MAXIMUM_OPS_PER_SECOND_LIMIT; + + if (typeof options?.throttling !== 'boolean') { + if (options?.throttling?.maxOpsPerSecond !== undefined) { + maxRate = options.throttling.maxOpsPerSecond; + } + + if (options?.throttling?.initialOpsPerSecond !== undefined) { + startingRate = options.throttling.initialOpsPerSecond; + } + + // The initial validation step ensures that the maxOpsPerSecond is + // greater than initialOpsPerSecond. If this inequality is true, that + // means initialOpsPerSecond was not set and maxOpsPerSecond is less + // than the default starting rate. + if (maxRate < startingRate) { + startingRate = maxRate; + } + + // Ensure that the batch size is not larger than the number of allowed + // operations per second. + if (startingRate < this._maxBatchSize) { + this._maxBatchSize = startingRate; + } + } + + this._rateLimiter = new RateLimiter( + startingRate, + RATE_LIMITER_MULTIPLIER, + RATE_LIMITER_MULTIPLIER_MILLIS, + maxRate, + ); + } + } + + /** + * Create a document with the provided data. This single operation will fail + * if a document exists at its location. + * + * @param {DocumentReference} documentRef A reference to the document to be + * created. + * @param {T} data The object to serialize as the document. + * @throws {Error} If the provided input is not a valid Firestore document. + * @returns {Promise} A promise that resolves with the result of + * the write. If the write fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * let documentRef = firestore.collection('col').doc(); + * + * bulkWriter + * .create(documentRef, {foo: 'bar'}) + * .then(result => { + * console.log('Successfully executed write at: ', result); + * }) + * .catch(err => { + * console.log('Write failed with: ', err); + * }); + * }); + * ``` + */ + create( + documentRef: firestore.DocumentReference, + data: firestore.WithFieldValue, + ): Promise { + this._verifyNotClosed(); + return this._enqueue(documentRef, 'create', bulkCommitBatch => + bulkCommitBatch.create(documentRef, data), + ); + } + + /** + * Delete a document from the database. + * + * @param {DocumentReference} documentRef A reference to the document to be + * deleted. + * @param {Precondition=} precondition A precondition to enforce for this + * delete. + * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the + * document was last updated at lastUpdateTime. Fails the batch if the + * document doesn't exist or was last updated at a different time. + * @returns {Promise} A promise that resolves with the result of + * the delete. If the delete fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * let documentRef = firestore.doc('col/doc'); + * + * bulkWriter + * .delete(documentRef) + * .then(result => { + * console.log('Successfully deleted document'); + * }) + * .catch(err => { + * console.log('Delete failed with: ', err); + * }); + * }); + * ``` + */ + delete( + documentRef: firestore.DocumentReference, + precondition?: firestore.Precondition, + ): Promise { + this._verifyNotClosed(); + return this._enqueue(documentRef, 'delete', bulkCommitBatch => + bulkCommitBatch.delete(documentRef, precondition), + ); + } + + set( + documentRef: firestore.DocumentReference, + data: Partial, + options: firestore.SetOptions, + ): Promise; + set( + documentRef: firestore.DocumentReference, + data: AppModelType, + ): Promise; + /** + * Write to the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document does not + * exist yet, it will be created. If you pass [SetOptions]{@link SetOptions}., + * the provided data can be merged into the existing document. + * + * @param {DocumentReference} documentRef A reference to the document to be + * set. + * @param {T} data The object to serialize as the document. + * @param {SetOptions=} options An object to configure the set behavior. + * @throws {Error} If the provided input is not a valid Firestore document. + * @param {boolean=} options.merge - If true, set() merges the values + * specified in its data argument. Fields omitted from this set() call remain + * untouched. If your input sets any field to an empty map, all nested fields + * are overwritten. + * @param {Array.=} options.mergeFields - If provided, set() + * only replaces the specified field paths. Any field path that is not + * specified is ignored and remains untouched. If your input sets any field to + * an empty map, all nested fields are overwritten. + * @returns {Promise} A promise that resolves with the result of + * the write. If the write fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + * + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * let documentRef = firestore.collection('col').doc(); + * + * bulkWriter + * .set(documentRef, {foo: 'bar'}) + * .then(result => { + * console.log('Successfully executed write at: ', result); + * }) + * .catch(err => { + * console.log('Write failed with: ', err); + * }); + * }); + * ``` + */ + set( + documentRef: firestore.DocumentReference, + data: firestore.PartialWithFieldValue, + options?: firestore.SetOptions, + ): Promise { + this._verifyNotClosed(); + return this._enqueue(documentRef, 'set', bulkCommitBatch => { + if (options) { + return bulkCommitBatch.set(documentRef, data, options); + } else { + return bulkCommitBatch.set( + documentRef, + data as firestore.WithFieldValue, + ); + } + }); + } + + /** + * Update fields of the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document doesn't yet + * exist, the update fails and the entire batch will be rejected. + * + * The update() method accepts either an object with field paths encoded as + * keys and field values encoded as values, or a variable number of arguments + * that alternate between field paths and field values. Nested fields can be + * updated by providing dot-separated field path strings or by providing + * FieldPath objects. + * + * + * A Precondition restricting this update can be specified as the last + * argument. + * + * @param {DocumentReference} documentRef A reference to the document to be + * updated. + * @param {UpdateData|string|FieldPath} dataOrField An object containing the + * fields and values with which to update the document or the path of the + * first field to update. + * @param {...(Precondition|*|string|FieldPath)} preconditionOrValues - An + * alternating list of field paths and values to update or a Precondition to + * restrict this update + * @throws {Error} If the provided input is not valid Firestore data. + * @returns {Promise} A promise that resolves with the result of + * the write. If the write fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * let documentRef = firestore.doc('col/doc'); + * + * bulkWriter + * .update(documentRef, {foo: 'bar'}) + * .then(result => { + * console.log('Successfully executed write at: ', result); + * }) + * .catch(err => { + * console.log('Write failed with: ', err); + * }); + * }); + * ``` + */ + update( + documentRef: firestore.DocumentReference, + dataOrField: firestore.UpdateData | string | FieldPath, + ...preconditionOrValues: Array< + {lastUpdateTime?: Timestamp} | unknown | string | FieldPath + > + ): Promise { + this._verifyNotClosed(); + return this._enqueue(documentRef, 'update', bulkCommitBatch => + bulkCommitBatch.update(documentRef, dataOrField, ...preconditionOrValues), + ); + } + + /** + * Callback function set by {@link BulkWriter#onWriteResult} that is run + * every time a {@link BulkWriter} operation successfully completes. + * + * @callback BulkWriter~successCallback + * @param {DocumentReference} documentRef The document reference the + * operation was performed on + * @param {WriteResult} result The server write time of the operation. + */ + + /** + * Attaches a listener that is run every time a BulkWriter operation + * successfully completes. + * + * @param {BulkWriter~successCallback} successCallback A callback to be + * called every time a BulkWriter operation successfully completes. + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * + * bulkWriter + * .onWriteResult((documentRef, result) => { + * console.log( + * 'Successfully executed write on document: ', + * documentRef, + * ' at: ', + * result + * ); + * }); + * ``` + */ + onWriteResult( + successCallback: ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + documentRef: firestore.DocumentReference, + result: WriteResult, + ) => void, + ): void { + this._successFn = successCallback; + } + + /** + * Callback function set by {@link BulkWriter#onWriteError} that is run when + * a write fails in order to determine whether {@link BulkWriter} should + * retry the operation. + * + * @callback BulkWriter~shouldRetryCallback + * @param {BulkWriterError} error The error object with information about the + * operation and error. + * @returns {boolean} Whether or not to retry the failed operation. Returning + * `true` retries the operation. Returning `false` will stop the retry loop. + */ + + /** + * Attaches an error handler listener that is run every time a BulkWriter + * operation fails. + * + * BulkWriter has a default error handler that retries UNAVAILABLE and + * ABORTED errors up to a maximum of 10 failed attempts. When an error + * handler is specified, the default error handler will be overwritten. + * + * @param shouldRetryCallback {BulkWriter~shouldRetryCallback} A callback to + * be called every time a BulkWriter operation fails. Returning `true` will + * retry the operation. Returning `false` will stop the retry loop. + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * + * bulkWriter + * .onWriteError((error) => { + * if ( + * error.code === GrpcStatus.UNAVAILABLE && + * error.failedAttempts < MAX_RETRY_ATTEMPTS + * ) { + * return true; + * } else { + * console.log('Failed write at document: ', error.documentRef); + * return false; + * } + * }); + * ``` + */ + onWriteError(shouldRetryCallback: (error: BulkWriterError) => boolean): void { + this._errorHandlerSet = true; + this._errorFn = shouldRetryCallback; + } + + /** + * Commits all writes that have been enqueued up to this point in parallel. + * + * Returns a Promise that resolves when all currently queued operations have + * been committed. The Promise will never be rejected since the results for + * each individual operation are conveyed via their individual Promises. + * + * The Promise resolves immediately if there are no pending writes. Otherwise, + * the Promise waits for all previously issued writes, but it does not wait + * for writes that were added after the method is called. If you want to wait + * for additional writes, call `flush()` again. + * + * @returns {Promise} A promise that resolves when all enqueued writes + * up to this point have been committed. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * + * bulkWriter.create(documentRef, {foo: 'bar'}); + * bulkWriter.update(documentRef2, {foo: 'bar'}); + * bulkWriter.delete(documentRef3); + * await flush().then(() => { + * console.log('Executed all writes'); + * }); + * ``` + */ + flush(): Promise { + this._verifyNotClosed(); + this._scheduleCurrentBatch(/* flush= */ true); + + // Mark the most recent operation as flushed to ensure that the batch + // containing it will be sent once it's popped from the buffer. + if (this._bufferedOperations.length > 0) { + this._bufferedOperations[ + this._bufferedOperations.length - 1 + ].operation.markFlushed(); + } + + return this._lastOp; + } + + /** + * Commits all enqueued writes and marks the BulkWriter instance as closed. + * + * After calling `close()`, calling any method will throw an error. Any + * retries scheduled as part of an `onWriteError()` handler will be run + * before the `close()` promise resolves. + * + * Returns a Promise that resolves when there are no more pending writes. The + * Promise will never be rejected. Calling this method will send all requests. + * The promise resolves immediately if there are no pending writes. + * + * @returns {Promise} A promise that resolves when all enqueued writes + * up to this point have been committed. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * + * bulkWriter.create(documentRef, {foo: 'bar'}); + * bulkWriter.update(documentRef2, {foo: 'bar'}); + * bulkWriter.delete(documentRef3); + * await close().then(() => { + * console.log('Executed all writes'); + * }); + * ``` + */ + close(): Promise { + if (!this._closePromise) { + this._closePromise = this.flush(); + this.firestore._decrementBulkWritersCount(); + } + return this._closePromise; + } + + /** + * Throws an error if the BulkWriter instance has been closed. + * @private + * @internal + */ + _verifyNotClosed(): void { + if (this._closePromise) { + throw new Error('BulkWriter has already been closed.'); + } + } + + /** + * Sends the current batch and resets `this._bulkCommitBatch`. + * + * @param flush If provided, keeps re-sending operations until no more + * operations are enqueued. This allows retries to resolve as part of a + * `flush()` or `close()` call. + * @private + * @internal + */ + private _scheduleCurrentBatch(flush = false): void { + if (this._bulkCommitBatch._opCount === 0) return; + + const pendingBatch = this._bulkCommitBatch; + this._bulkCommitBatch = new BulkCommitBatch( + this.firestore, + this._maxBatchSize, + ); + + // Use the write with the longest backoff duration when determining backoff. + const highestBackoffDuration = pendingBatch.pendingOps.reduce( + (prev, cur) => (prev.backoffDuration > cur.backoffDuration ? prev : cur), + ).backoffDuration; + const backoffMsWithJitter = BulkWriter._applyJitter(highestBackoffDuration); + const delayedExecution = new Deferred(); + + if (backoffMsWithJitter > 0) { + delayExecution(() => delayedExecution.resolve(), backoffMsWithJitter); + } else { + delayedExecution.resolve(); + } + + void delayedExecution.promise.then(() => + this._sendBatch(pendingBatch, flush), + ); + } + + /** + * Sends the provided batch once the rate limiter does not require any delay. + * @private + * @internal + */ + private async _sendBatch( + batch: BulkCommitBatch, + flush = false, + ): Promise { + const tag = requestTag(); + + // Send the batch if it is does not require any delay, or schedule another + // attempt after the appropriate timeout. + const underRateLimit = this._rateLimiter.tryMakeRequest(batch._opCount); + if (underRateLimit) { + await batch.bulkCommit({requestTag: tag}); + if (flush) this._scheduleCurrentBatch(flush); + } else { + const delayMs = this._rateLimiter.getNextRequestDelayMs(batch._opCount); + logger( + 'BulkWriter._sendBatch', + tag, + `Backing off for ${delayMs} seconds`, + ); + delayExecution(() => this._sendBatch(batch, flush), delayMs); + } + } + + /** + * Adds a 30% jitter to the provided backoff. + * + * @private + * @internal + */ + private static _applyJitter(backoffMs: number): number { + if (backoffMs === 0) return 0; + // Random value in [-0.3, 0.3]. + const jitter = DEFAULT_JITTER_FACTOR * (Math.random() * 2 - 1); + return Math.min( + DEFAULT_BACKOFF_MAX_DELAY_MS, + backoffMs + jitter * backoffMs, + ); + } + + /** + * Schedules and runs the provided operation on the next available batch. + * @private + * @internal + */ + private _enqueue( + ref: firestore.DocumentReference, + type: 'create' | 'set' | 'update' | 'delete', + enqueueOnBatchCallback: (bulkCommitBatch: BulkCommitBatch) => void, + ): Promise { + const bulkWriterOp = new BulkWriterOperation( + ref, + type, + this._sendFn.bind(this, enqueueOnBatchCallback), + this._errorFn.bind(this), + this._successFn.bind(this), + ); + + // Swallow the error if the developer has set an error listener. This + // prevents UnhandledPromiseRejections from being thrown if a floating + // BulkWriter operation promise fails when an error handler is specified. + // + // This is done here in order to chain the caught promise onto `lastOp`, + // which ensures that flush() resolves after the operation promise. + const userPromise = bulkWriterOp.promise.catch(err => { + if (!this._errorHandlerSet) { + throw err; + } else { + return bulkWriterOp.promise; + } + }); + + // Advance the `_lastOp` pointer. This ensures that `_lastOp` only resolves + // when both the previous and the current write resolve. + this._lastOp = this._lastOp.then(() => silencePromise(userPromise)); + + // Schedule the operation if the BulkWriter has fewer than the maximum + // number of allowed pending operations, or add the operation to the + // buffer. + if (this._pendingOpsCount < this._maxPendingOpCount) { + this._pendingOpsCount++; + this._sendFn(enqueueOnBatchCallback, bulkWriterOp); + } else { + this._bufferedOperations.push( + new BufferedOperation(bulkWriterOp, () => { + this._pendingOpsCount++; + this._sendFn(enqueueOnBatchCallback, bulkWriterOp); + }), + ); + } + + // Chain the BulkWriter operation promise with the buffer processing logic + // in order to ensure that it runs and that subsequent operations are + // enqueued before the next batch is scheduled in `_sendBatch()`. + return userPromise + .then(res => { + this._pendingOpsCount--; + this._processBufferedOps(); + return res; + }) + .catch(err => { + this._pendingOpsCount--; + this._processBufferedOps(); + throw err; + }); + } + + /** + * Manages the pending operation counter and schedules the next BulkWriter + * operation if we're under the maximum limit. + * @private + * @internal + */ + private _processBufferedOps(): void { + if ( + this._pendingOpsCount < this._maxPendingOpCount && + this._bufferedOperations.length > 0 + ) { + const nextOp = this._bufferedOperations.shift()!; + nextOp.sendFn(); + } + } + + /** + * Schedules the provided operations on current BulkCommitBatch. + * Sends the BulkCommitBatch if it reaches maximum capacity. + * + * @private + * @internal + */ + _sendFn( + enqueueOnBatchCallback: (bulkCommitBatch: BulkCommitBatch) => void, + op: BulkWriterOperation, + ): void { + // A backoff duration greater than 0 implies that this batch is a retry. + // Retried writes are sent with a batch size of 10 in order to guarantee + // that the batch is under the 10MiB limit. + if (op.backoffDuration > 0) { + if (this._bulkCommitBatch.pendingOps.length >= RETRY_MAX_BATCH_SIZE) { + this._scheduleCurrentBatch(/* flush= */ false); + } + this._bulkCommitBatch.setMaxBatchSize(RETRY_MAX_BATCH_SIZE); + } + + if (this._bulkCommitBatch.has(op.ref)) { + // Create a new batch since the backend doesn't support batches with two + // writes to the same document. + this._scheduleCurrentBatch(); + } + + enqueueOnBatchCallback(this._bulkCommitBatch); + this._bulkCommitBatch.processLastOperation(op); + + if (this._bulkCommitBatch._opCount === this._bulkCommitBatch.maxBatchSize) { + this._scheduleCurrentBatch(); + } else if (op.flushed) { + // If flush() was called before this operation was enqueued into a batch, + // we still need to schedule it. + this._scheduleCurrentBatch(/* flush= */ true); + } + } +} + +/** + * Validates the use of 'value' as BulkWriterOptions. + * + * @private + * @internal + * @param value The BulkWriterOptions object to validate. + * @throws if the input is not a valid BulkWriterOptions object. + */ +function validateBulkWriterOptions(value: unknown): void { + if (validateOptional(value, {optional: true})) { + return; + } + const argName = 'options'; + + if (!isObject(value)) { + throw new Error( + `${invalidArgumentMessage( + argName, + 'bulkWriter() options argument', + )} Input is not an object.`, + ); + } + + const options = value as firestore.BulkWriterOptions; + + if ( + options.throttling === undefined || + typeof options.throttling === 'boolean' + ) { + return; + } + + if (options.throttling.initialOpsPerSecond !== undefined) { + validateInteger( + 'initialOpsPerSecond', + options.throttling.initialOpsPerSecond, + { + minValue: 1, + }, + ); + } + + if (options.throttling.maxOpsPerSecond !== undefined) { + validateInteger('maxOpsPerSecond', options.throttling.maxOpsPerSecond, { + minValue: 1, + }); + + if ( + options.throttling.initialOpsPerSecond !== undefined && + options.throttling.initialOpsPerSecond > + options.throttling.maxOpsPerSecond + ) { + throw new Error( + `${invalidArgumentMessage( + argName, + 'bulkWriter() options argument', + )} "maxOpsPerSecond" cannot be less than "initialOpsPerSecond".`, + ); + } + } +} diff --git a/handwritten/firestore/dev/src/bundle.ts b/handwritten/firestore/dev/src/bundle.ts new file mode 100644 index 00000000000..dc11d7a851d --- /dev/null +++ b/handwritten/firestore/dev/src/bundle.ts @@ -0,0 +1,242 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {firestore, google} from '../protos/firestore_v1_proto_api'; + +import {DocumentSnapshot} from './document'; +import {QuerySnapshot} from './reference/query-snapshot'; +import {Timestamp} from './timestamp'; +import { + invalidArgumentMessage, + validateMaxNumberOfArguments, + validateMinNumberOfArguments, + validateString, +} from './validate'; + +import api = google.firestore.v1; + +const BUNDLE_VERSION = 1; + +/** + * Builds a Firestore data bundle with results from the given document and query snapshots. + */ +export class BundleBuilder { + // Resulting documents for the bundle, keyed by full document path. + private documents: Map = new Map(); + // Named queries saved in the bundle, keyed by query name. + private namedQueries: Map = new Map(); + + // The latest read time among all bundled documents and queries. + private latestReadTime = new Timestamp(0, 0); + + constructor(readonly bundleId: string) {} + + add(documentSnapshot: DocumentSnapshot): BundleBuilder; + add(queryName: string, querySnapshot: QuerySnapshot): BundleBuilder; + /** + * Adds a Firestore document snapshot or query snapshot to the bundle. + * Both the documents data and the query read time will be included in the bundle. + * + * @param {DocumentSnapshot | string} documentOrName A document snapshot to add or a name of a query. + * @param {Query=} querySnapshot A query snapshot to add to the bundle, if provided. + * @returns {BundleBuilder} This instance. + * + * @example + * ``` + * const bundle = firestore.bundle('data-bundle'); + * const docSnapshot = await firestore.doc('abc/123').get(); + * const querySnapshot = await firestore.collection('coll').get(); + * + * const bundleBuffer = bundle.add(docSnapshot) // Add a document + * .add('coll-query', querySnapshot) // Add a named query. + * .build() + * // Save `bundleBuffer` to CDN or stream it to clients. + * ``` + */ + add( + documentOrName: DocumentSnapshot | string, + querySnapshot?: QuerySnapshot, + ): BundleBuilder { + // eslint-disable-next-line prefer-rest-params + validateMinNumberOfArguments('BundleBuilder.add', arguments, 1); + // eslint-disable-next-line prefer-rest-params + validateMaxNumberOfArguments('BundleBuilder.add', arguments, 2); + if (arguments.length === 1) { + validateDocumentSnapshot('documentOrName', documentOrName); + this.addBundledDocument(documentOrName as DocumentSnapshot); + } else { + validateString('documentOrName', documentOrName); + validateQuerySnapshot('querySnapshot', querySnapshot); + this.addNamedQuery(documentOrName as string, querySnapshot!); + } + + return this; + } + + private addBundledDocument(snap: DocumentSnapshot, queryName?: string): void { + const originalDocument = this.documents.get(snap.ref.path); + const originalQueries = originalDocument?.metadata.queries; + + // Update with document built from `snap` because it is newer. + if ( + !originalDocument || + Timestamp.fromProto(originalDocument.metadata.readTime!) < snap.readTime + ) { + const docProto = snap.toDocumentProto(); + this.documents.set(snap.ref.path, { + document: snap.exists ? docProto : undefined, + metadata: { + name: docProto.name, + readTime: snap.readTime.toProto().timestampValue, + exists: snap.exists, + }, + }); + } + + // Update `queries` to include both original and `queryName`. + const newDocument = this.documents.get(snap.ref.path)!; + newDocument.metadata.queries = originalQueries || []; + if (queryName) { + newDocument.metadata.queries!.push(queryName); + } + + if (snap.readTime > this.latestReadTime) { + this.latestReadTime = snap.readTime; + } + } + + private addNamedQuery(name: string, querySnap: QuerySnapshot): void { + if (this.namedQueries.has(name)) { + throw new Error(`Query name conflict: ${name} has already been added.`); + } + + this.namedQueries.set(name, { + name, + bundledQuery: querySnap.query._toBundledQuery(), + readTime: querySnap.readTime.toProto().timestampValue, + }); + + for (const snap of querySnap.docs) { + this.addBundledDocument(snap, name); + } + + if (querySnap.readTime > this.latestReadTime) { + this.latestReadTime = querySnap.readTime; + } + } + + /** + * Converts a IBundleElement to a Buffer whose content is the length prefixed JSON representation + * of the element. + * @private + * @internal + */ + private elementToLengthPrefixedBuffer( + bundleElement: firestore.IBundleElement, + ): Buffer { + // Convert to a valid proto message object then take its JSON representation. + // This take cares of stuff like converting internal byte array fields + // to Base64 encodings. + // We lazy-load the Proto file to reduce cold-start times. + const message = require('../protos/firestore_v1_proto_api') + .firestore.BundleElement.fromObject(bundleElement) + .toJSON(); + const buffer = Buffer.from(JSON.stringify(message), 'utf-8'); + const lengthBuffer = Buffer.from(buffer.length.toString()); + return Buffer.concat([lengthBuffer, buffer]); + } + + build(): Buffer { + let bundleBuffer = Buffer.alloc(0); + + for (const namedQuery of this.namedQueries.values()) { + bundleBuffer = Buffer.concat([ + bundleBuffer, + this.elementToLengthPrefixedBuffer({namedQuery}), + ]); + } + + for (const bundledDocument of this.documents.values()) { + const documentMetadata: firestore.IBundledDocumentMetadata = + bundledDocument.metadata; + + bundleBuffer = Buffer.concat([ + bundleBuffer, + this.elementToLengthPrefixedBuffer({documentMetadata}), + ]); + // Write to the bundle if document exists. + const document = bundledDocument.document; + if (document) { + bundleBuffer = Buffer.concat([ + bundleBuffer, + this.elementToLengthPrefixedBuffer({document}), + ]); + } + } + + const metadata: firestore.IBundleMetadata = { + id: this.bundleId, + createTime: this.latestReadTime.toProto().timestampValue, + version: BUNDLE_VERSION, + totalDocuments: this.documents.size, + totalBytes: bundleBuffer.length, + }; + // Prepends the metadata element to the bundleBuffer: `bundleBuffer` is the second argument to `Buffer.concat`. + bundleBuffer = Buffer.concat([ + this.elementToLengthPrefixedBuffer({metadata}), + bundleBuffer, + ]); + return bundleBuffer; + } +} + +/** + * Convenient class to hold both the metadata and the actual content of a document to be bundled. + * @private + * @internal + */ +class BundledDocument { + constructor( + readonly metadata: firestore.IBundledDocumentMetadata, + readonly document?: api.IDocument, + ) {} +} + +/** + * Validates that 'value' is DocumentSnapshot. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + */ +function validateDocumentSnapshot(arg: string | number, value: unknown): void { + if (!(value instanceof DocumentSnapshot)) { + throw new Error(invalidArgumentMessage(arg, 'DocumentSnapshot')); + } +} + +/** + * Validates that 'value' is QuerySnapshot. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + */ +function validateQuerySnapshot(arg: string | number, value: unknown): void { + if (!(value instanceof QuerySnapshot)) { + throw new Error(invalidArgumentMessage(arg, 'QuerySnapshot')); + } +} diff --git a/handwritten/firestore/dev/src/collection-group.ts b/handwritten/firestore/dev/src/collection-group.ts new file mode 100644 index 00000000000..cd58e063473 --- /dev/null +++ b/handwritten/firestore/dev/src/collection-group.ts @@ -0,0 +1,228 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; +import * as protos from '../protos/firestore_v1_proto_api'; + +import {QueryPartition} from './query-partition'; +import {requestTag} from './util'; +import {logger} from './logger'; +import {Query} from './reference/query'; +import {QueryOptions} from './reference/query-options'; +import {FieldPath} from './path'; +import {Firestore} from './index'; +import {validateInteger} from './validate'; + +import api = protos.google.firestore.v1; +import {defaultConverter} from './types'; +import {compareArrays} from './order'; +import {SPAN_NAME_PARTITION_QUERY} from './telemetry/trace-util'; + +/** + * A `CollectionGroup` refers to all documents that are contained in a + * collection or subcollection with a specific collection ID. + * + * @class CollectionGroup + */ +export class CollectionGroup< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, + > + extends Query + implements firestore.CollectionGroup +{ + /** @private */ + constructor( + firestore: Firestore, + collectionId: string, + converter: + | firestore.FirestoreDataConverter + | undefined, + ) { + super( + firestore, + QueryOptions.forCollectionGroupQuery(collectionId, converter), + ); + } + + /** + * Partitions a query by returning partition cursors that can be used to run + * the query in parallel. The returned cursors are split points that can be + * used as starting and end points for individual query invocations. + * + * @example + * ``` + * const query = firestore.collectionGroup('collectionId'); + * for await (const partition of query.getPartitions(42)) { + * const partitionedQuery = partition.toQuery(); + * const querySnapshot = await partitionedQuery.get(); + * console.log(`Partition contained ${querySnapshot.length} documents`); + * } + * + * ``` + * @param {number} desiredPartitionCount The desired maximum number of + * partition points. The number must be strictly positive. The actual number + * of partitions returned may be fewer. + * @returns {AsyncIterable} An AsyncIterable of + * `QueryPartition`s. + */ + async *getPartitions( + desiredPartitionCount: number, + ): AsyncIterable> { + const partitions: Array[] = []; + + await this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_PARTITION_QUERY, + async () => { + validateInteger('desiredPartitionCount', desiredPartitionCount, { + minValue: 1, + }); + + const tag = requestTag(); + await this.firestore.initializeIfNeeded(tag); + + if (desiredPartitionCount > 1) { + // Partition queries require explicit ordering by __name__. + const queryWithDefaultOrder = this.orderBy(FieldPath.documentId()); + const request: api.IPartitionQueryRequest = + queryWithDefaultOrder.toProto(); + + // Since we are always returning an extra partition (with an empty endBefore + // cursor), we reduce the desired partition count by one. + request.partitionCount = desiredPartitionCount - 1; + + const stream = await this.firestore.requestStream( + 'partitionQueryStream', + /* bidirectional= */ false, + request, + tag, + ); + stream.resume(); + + for await (const currentCursor of stream) { + partitions.push(currentCursor.values ?? []); + } + } + + logger( + 'Firestore.getPartitions', + tag, + 'Received %d partitions', + partitions.length, + ); + + // Sort the partitions as they may not be ordered if responses are paged. + partitions.sort((l, r) => compareArrays(l, r)); + }, + ); + + for (let i = 0; i < partitions.length; ++i) { + yield new QueryPartition( + this._firestore, + this._queryOptions.collectionId, + this._queryOptions.converter, + i > 0 ? partitions[i - 1] : undefined, + partitions[i], + ); + } + + // Return the extra partition with the empty cursor. + yield new QueryPartition( + this._firestore, + this._queryOptions.collectionId, + this._queryOptions.converter, + partitions.pop(), + undefined, + ); + } + + /** + * Applies a custom data converter to this `CollectionGroup`, allowing you + * to use your own custom model objects with Firestore. When you call get() + * on the returned `CollectionGroup`, the provided converter will convert + * between Firestore data of type `NewDbModelType` and your custom type + * `NewAppModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * Passing in `null` as the converter parameter removes the current + * converter. + * + * @example + * ``` + * class Post { + * constructor(readonly title: string, readonly author: string) {} + * + * toString(): string { + * return this.title + ', by ' + this.author; + * } + * } + * + * const postConverter = { + * toFirestore(post: Post): FirebaseFirestore.DocumentData { + * return {title: post.title, author: post.author}; + * }, + * fromFirestore( + * snapshot: FirebaseFirestore.QueryDocumentSnapshot + * ): Post { + * const data = snapshot.data(); + * return new Post(data.title, data.author); + * } + * }; + * + * const querySnapshot = await Firestore() + * .collectionGroup('posts') + * .withConverter(postConverter) + * .get(); + * for (const doc of querySnapshot.docs) { + * const post = doc.data(); + * post.title; // string + * post.toString(); // Should be defined + * post.someNonExistentProperty; // TS error + * } + * + * ``` + * @param {FirestoreDataConverter | null} converter Converts objects to and + * from Firestore. Passing in `null` removes the current converter. + * @returns {CollectionGroup} A `CollectionGroup` that uses the provided + * converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends firestore.DocumentData = firestore.DocumentData, + >( + converter: firestore.FirestoreDataConverter< + NewAppModelType, + NewDbModelType + > | null, + ): CollectionGroup; + withConverter< + NewAppModelType, + NewDbModelType extends firestore.DocumentData = firestore.DocumentData, + >( + converter: firestore.FirestoreDataConverter< + NewAppModelType, + NewDbModelType + > | null, + ): CollectionGroup { + return new CollectionGroup( + this.firestore, + this._queryOptions.collectionId, + converter ?? defaultConverter(), + ); + } +} diff --git a/handwritten/firestore/dev/src/convert.ts b/handwritten/firestore/dev/src/convert.ts new file mode 100644 index 00000000000..c44e0840119 --- /dev/null +++ b/handwritten/firestore/dev/src/convert.ts @@ -0,0 +1,300 @@ +/*! + * Copyright 2019 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {google} from '../protos/firestore_v1_proto_api'; + +import {ApiMapValue, ProtobufJsValue} from './types'; +import {validateObject} from './validate'; + +import api = google.firestore.v1; +import {RESERVED_MAP_KEY, RESERVED_MAP_KEY_VECTOR_VALUE} from './map-type'; + +/*! + * @module firestore/convert + * @private + * @internal + * + * This module contains utility functions to convert + * `firestore.v1.Documents` from Proto3 JSON to their equivalent + * representation in Protobuf JS. Protobuf JS is the only encoding supported by + * this client, and dependencies that use Proto3 JSON (such as the Google Cloud + * Functions SDK) are supported through this conversion and its usage in + * {@see Firestore#snapshot_}. + */ + +/** + * Converts an ISO 8601 or google.protobuf.Timestamp proto into Protobuf JS. + * + * @private + * @internal + * @param timestampValue The value to convert. + * @param argumentName The argument name to use in the error message if the + * conversion fails. If omitted, 'timestampValue' is used. + * @returns The value as expected by Protobuf JS or undefined if no input was + * provided. + */ +export function timestampFromJson( + timestampValue?: string | google.protobuf.ITimestamp, + argumentName?: string, +): google.protobuf.ITimestamp | undefined { + let timestampProto: google.protobuf.ITimestamp = {}; + + if (typeof timestampValue === 'string') { + const date = new Date(timestampValue); + const seconds = Math.floor(date.getTime() / 1000); + let nanos = 0; + + if (timestampValue.length > 20) { + const nanoString = timestampValue.substring( + 20, + timestampValue.length - 1, + ); + const trailingZeroes = 9 - nanoString.length; + nanos = Number(nanoString) * Math.pow(10, trailingZeroes); + } + + if (isNaN(seconds) || isNaN(nanos)) { + argumentName = argumentName || 'timestampValue'; + throw new Error( + `Specify a valid ISO 8601 timestamp for "${argumentName}".`, + ); + } + + timestampProto = { + seconds: seconds || undefined, + nanos: nanos || undefined, + }; + } else if (timestampValue !== undefined) { + validateObject('timestampValue', timestampValue); + timestampProto = { + seconds: timestampValue.seconds || undefined, + nanos: timestampValue.nanos || undefined, + }; + } + + return timestampProto; +} + +/** + * Converts a Proto3 JSON 'bytesValue' field into Protobuf JS. + * + * @private + * @internal + * @param bytesValue The value to convert. + * @returns The value as expected by Protobuf JS. + */ +function bytesFromJson(bytesValue: string | Uint8Array): Uint8Array { + if (typeof bytesValue === 'string') { + return Buffer.from(bytesValue, 'base64'); + } else { + return bytesValue; + } +} + +/** + * Detects 'valueType' from a Proto3 JSON `firestore.v1.Value` proto. + * + * @private + * @internal + * @param proto The `firestore.v1.Value` proto. + * @returns The string value for 'valueType'. + */ +export function detectValueType(proto: ProtobufJsValue): string { + let valueType: string | undefined; + + if (proto.valueType) { + valueType = proto.valueType; + } else { + const detectedValues: string[] = []; + + if (proto.stringValue !== undefined) { + detectedValues.push('stringValue'); + } + if (proto.booleanValue !== undefined) { + detectedValues.push('booleanValue'); + } + if (proto.integerValue !== undefined) { + detectedValues.push('integerValue'); + } + if (proto.doubleValue !== undefined) { + detectedValues.push('doubleValue'); + } + if (proto.timestampValue !== undefined) { + detectedValues.push('timestampValue'); + } + if (proto.referenceValue !== undefined) { + detectedValues.push('referenceValue'); + } + if (proto.arrayValue !== undefined) { + detectedValues.push('arrayValue'); + } + if (proto.nullValue !== undefined) { + detectedValues.push('nullValue'); + } + if (proto.mapValue !== undefined) { + detectedValues.push('mapValue'); + } + if (proto.geoPointValue !== undefined) { + detectedValues.push('geoPointValue'); + } + if (proto.bytesValue !== undefined) { + detectedValues.push('bytesValue'); + } + + if (detectedValues.length !== 1) { + throw new Error( + `Unable to infer type value from '${JSON.stringify(proto)}'.`, + ); + } + + valueType = detectedValues[0]; + } + + // Special handling of mapValues used to represent other data types + if (valueType === 'mapValue') { + const fields = proto.mapValue?.fields; + if (fields) { + const props = Object.keys(fields); + if ( + props.indexOf(RESERVED_MAP_KEY) !== -1 && + detectValueType(fields[RESERVED_MAP_KEY]) === 'stringValue' && + fields[RESERVED_MAP_KEY].stringValue === RESERVED_MAP_KEY_VECTOR_VALUE + ) { + valueType = 'vectorValue'; + } + } + } + + return valueType; +} + +/** + * Detects the value kind from a Proto3 JSON `google.protobuf.Value` proto. + * + * @private + * @internal + * @param proto The `firestore.v1.Value` proto. + * @returns The string value for 'valueType'. + */ +export function detectGoogleProtobufValueType( + proto: google.protobuf.IValue, +): string { + const detectedValues: string[] = []; + + if (proto.nullValue !== undefined) { + detectedValues.push('nullValue'); + } + if (proto.numberValue !== undefined) { + detectedValues.push('numberValue'); + } + if (proto.stringValue !== undefined) { + detectedValues.push('stringValue'); + } + if (proto.boolValue !== undefined) { + detectedValues.push('boolValue'); + } + if (proto.structValue !== undefined) { + detectedValues.push('structValue'); + } + if (proto.listValue !== undefined) { + detectedValues.push('listValue'); + } + + if (detectedValues.length !== 1) { + throw new Error( + `Unable to infer type value from '${JSON.stringify(proto)}'.`, + ); + } + + return detectedValues[0]; +} + +/** + * Converts a `firestore.v1.Value` in Proto3 JSON encoding into the + * Protobuf JS format expected by this client. + * + * @private + * @internal + * @param fieldValue The `firestore.v1.Value` in Proto3 JSON format. + * @returns The `firestore.v1.Value` in Protobuf JS format. + */ +export function valueFromJson(fieldValue: api.IValue): api.IValue { + const valueType = detectValueType(fieldValue); + + switch (valueType) { + case 'timestampValue': + return { + timestampValue: timestampFromJson(fieldValue.timestampValue!), + }; + case 'bytesValue': + return { + bytesValue: bytesFromJson(fieldValue.bytesValue!), + }; + case 'doubleValue': + return { + doubleValue: Number(fieldValue.doubleValue), + }; + case 'arrayValue': { + const arrayValue: Array = []; + if (Array.isArray(fieldValue.arrayValue!.values)) { + for (const value of fieldValue.arrayValue!.values!) { + arrayValue.push(valueFromJson(value)); + } + } + return { + arrayValue: { + values: arrayValue, + }, + }; + } + case 'mapValue': + case 'vectorValue': { + const mapValue: ApiMapValue = {}; + const fields = fieldValue.mapValue!.fields; + if (fields) { + for (const prop of Object.keys(fields)) { + mapValue[prop] = valueFromJson(fieldValue.mapValue!.fields![prop]); + } + } + return { + mapValue: { + fields: mapValue, + }, + }; + } + default: + return fieldValue; + } +} + +/** + * Converts a map of IValues in Proto3 JSON encoding into the Protobuf JS format + * expected by this client. This conversion creates a copy of the underlying + * fields. + * + * @private + * @internal + * @param document An object with IValues in Proto3 JSON format. + * @returns The object in Protobuf JS format. + */ +export function fieldsFromJson(document: ApiMapValue): ApiMapValue { + const result: ApiMapValue = {}; + + for (const prop of Object.keys(document)) { + result[prop] = valueFromJson(document[prop]); + } + return result; +} diff --git a/handwritten/firestore/dev/src/document-change.ts b/handwritten/firestore/dev/src/document-change.ts new file mode 100644 index 00000000000..ea1e3cc69a6 --- /dev/null +++ b/handwritten/firestore/dev/src/document-change.ts @@ -0,0 +1,199 @@ +/*! + * Copyright 2018 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; + +import {QueryDocumentSnapshot} from './document'; + +export type DocumentChangeType = 'added' | 'removed' | 'modified'; + +/** + * A DocumentChange represents a change to the documents matching a query. + * It contains the document affected and the type of change that occurred. + * + * @class DocumentChange + */ +export class DocumentChange< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> implements firestore.DocumentChange +{ + private readonly _type: DocumentChangeType; + private readonly _document: QueryDocumentSnapshot; + private readonly _oldIndex: number; + private readonly _newIndex: number; + + /** + * @private + * + * @param {string} type 'added' | 'removed' | 'modified'. + * @param {QueryDocumentSnapshot} document The document. + * @param {number} oldIndex The index in the documents array prior to this + * change. + * @param {number} newIndex The index in the documents array after this + * change. + */ + constructor( + type: DocumentChangeType, + document: QueryDocumentSnapshot, + oldIndex: number, + newIndex: number, + ) { + this._type = type; + this._document = document; + this._oldIndex = oldIndex; + this._newIndex = newIndex; + } + + /** + * The type of change ('added', 'modified', or 'removed'). + * + * @type {string} + * @name DocumentChange#type + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * let docsArray = []; + * + * let unsubscribe = query.onSnapshot(querySnapshot => { + * for (let change of querySnapshot.docChanges) { + * console.log(`Type of change is ${change.type}`); + * } + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + get type(): DocumentChangeType { + return this._type; + } + + /** + * The document affected by this change. + * + * @type {QueryDocumentSnapshot} + * @name DocumentChange#doc + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * let unsubscribe = query.onSnapshot(querySnapshot => { + * for (let change of querySnapshot.docChanges) { + * console.log(change.doc.data()); + * } + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + get doc(): QueryDocumentSnapshot { + return this._document; + } + + /** + * The index of the changed document in the result set immediately prior to + * this DocumentChange (i.e. supposing that all prior DocumentChange objects + * have been applied). Is -1 for 'added' events. + * + * @type {number} + * @name DocumentChange#oldIndex + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * let docsArray = []; + * + * let unsubscribe = query.onSnapshot(querySnapshot => { + * for (let change of querySnapshot.docChanges) { + * if (change.oldIndex !== -1) { + * docsArray.splice(change.oldIndex, 1); + * } + * if (change.newIndex !== -1) { + * docsArray.splice(change.newIndex, 0, change.doc); + * } + * } + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + get oldIndex(): number { + return this._oldIndex; + } + + /** + * The index of the changed document in the result set immediately after + * this DocumentChange (i.e. supposing that all prior DocumentChange + * objects and the current DocumentChange object have been applied). + * Is -1 for 'removed' events. + * + * @type {number} + * @name DocumentChange#newIndex + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * let docsArray = []; + * + * let unsubscribe = query.onSnapshot(querySnapshot => { + * for (let change of querySnapshot.docChanges) { + * if (change.oldIndex !== -1) { + * docsArray.splice(change.oldIndex, 1); + * } + * if (change.newIndex !== -1) { + * docsArray.splice(change.newIndex, 0, change.doc); + * } + * } + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + get newIndex(): number { + return this._newIndex; + } + + /** + * Returns true if the data in this `DocumentChange` is equal to the provided + * value. + * + * @param {*} other The value to compare against. + * @returns true if this `DocumentChange` is equal to the provided value. + */ + isEqual(other: firestore.DocumentChange): boolean { + if (this === other) { + return true; + } + + return ( + other instanceof DocumentChange && + this._type === other._type && + this._oldIndex === other._oldIndex && + this._newIndex === other._newIndex && + this._document.isEqual(other._document) + ); + } +} diff --git a/handwritten/firestore/dev/src/document-reader.ts b/handwritten/firestore/dev/src/document-reader.ts new file mode 100644 index 00000000000..d6d0d318bbe --- /dev/null +++ b/handwritten/firestore/dev/src/document-reader.ts @@ -0,0 +1,233 @@ +/*! + * Copyright 2021 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {DocumentSnapshot, DocumentSnapshotBuilder} from './document'; +import {DocumentReference} from './reference/document-reference'; +import {FieldPath} from './path'; +import {isPermanentRpcError} from './util'; +import {google} from '../protos/firestore_v1_proto_api'; +import {logger} from './logger'; +import {Firestore} from './index'; +import {Timestamp} from './timestamp'; +import {DocumentData} from '@google-cloud/firestore'; +import api = google.firestore.v1; + +interface BatchGetResponse { + result: Array>; + /** + * The transaction that was started as part of this request. Will only be if + * `DocumentReader.transactionIdOrNewTransaction` was `api.ITransactionOptions`. + */ + transaction?: Uint8Array; +} + +/** + * A wrapper around BatchGetDocumentsRequest that retries request upon stream + * failure and returns ordered results. + * + * @private + * @internal + */ +export class DocumentReader { + private readonly outstandingDocuments = new Set(); + private readonly retrievedDocuments = new Map(); + private retrievedTransactionId?: Uint8Array; + + /** + * Creates a new DocumentReader that fetches the provided documents (via + * `get()`). + * + * @param firestore The Firestore instance to use. + * @param allDocuments The documents to get. + * @param fieldMask An optional field mask to apply to this read + * @param transactionOrReadTime An optional transaction ID to use for this + * read or options for beginning a new transaction with this read + */ + constructor( + private readonly firestore: Firestore, + private readonly allDocuments: ReadonlyArray< + DocumentReference + >, + private readonly fieldMask?: FieldPath[], + private readonly transactionOrReadTime?: + | Uint8Array + | api.ITransactionOptions + | Timestamp, + ) { + for (const docRef of this.allDocuments) { + this.outstandingDocuments.add(docRef.formattedName); + } + } + + /** + * Invokes the BatchGetDocuments RPC and returns the results as an array of + * documents. + * + * @param requestTag A unique client-assigned identifier for this request. + */ + async get( + requestTag: string, + ): Promise>> { + const {result} = await this._get(requestTag); + return result; + } + + /** + * Invokes the BatchGetDocuments RPC and returns the results with transaction + * metadata. + * + * @param requestTag A unique client-assigned identifier for this request. + */ + async _get( + requestTag: string, + ): Promise> { + await this.fetchDocuments(requestTag); + + // BatchGetDocuments doesn't preserve document order. We use the request + // order to sort the resulting documents. + const orderedDocuments: Array> = + []; + + for (const docRef of this.allDocuments) { + const document = this.retrievedDocuments.get(docRef.formattedName); + if (document !== undefined) { + // Recreate the DocumentSnapshot with the DocumentReference + // containing the original converter. + const finalDoc = new DocumentSnapshotBuilder( + docRef as DocumentReference, + ); + finalDoc.fieldsProto = document._fieldsProto; + finalDoc.readTime = document.readTime; + finalDoc.createTime = document.createTime; + finalDoc.updateTime = document.updateTime; + orderedDocuments.push(finalDoc.build()); + } else { + throw new Error(`Did not receive document for "${docRef.path}".`); + } + } + + return { + result: orderedDocuments, + transaction: this.retrievedTransactionId, + }; + } + + private async fetchDocuments(requestTag: string): Promise { + if (!this.outstandingDocuments.size) { + return; + } + + const request: api.IBatchGetDocumentsRequest = { + database: this.firestore.formattedName, + documents: Array.from(this.outstandingDocuments), + }; + if (this.transactionOrReadTime instanceof Uint8Array) { + request.transaction = this.transactionOrReadTime; + } else if (this.transactionOrReadTime instanceof Timestamp) { + request.readTime = this.transactionOrReadTime.toProto().timestampValue; + } else if (this.transactionOrReadTime) { + request.newTransaction = this.transactionOrReadTime; + } + + if (this.fieldMask) { + const fieldPaths = this.fieldMask.map( + fieldPath => fieldPath.formattedName, + ); + request.mask = {fieldPaths}; + } + + let resultCount = 0; + + try { + const stream = await this.firestore.requestStream( + 'batchGetDocuments', + /* bidirectional= */ false, + request, + requestTag, + ); + stream.resume(); + + for await (const response of stream) { + // Proto comes with zero-length buffer by default + if (response.transaction?.length) { + this.retrievedTransactionId = response.transaction; + } + + let snapshot: DocumentSnapshot | undefined; + if (response.found) { + logger( + 'DocumentReader.fetchDocuments', + requestTag, + 'Received document: %s', + response.found.name!, + ); + snapshot = this.firestore.snapshot_( + response.found, + response.readTime!, + ); + } else if (response.missing) { + logger( + 'DocumentReader.fetchDocuments', + requestTag, + 'Document missing: %s', + response.missing, + ); + snapshot = this.firestore.snapshot_( + response.missing, + response.readTime!, + ); + } + + if (snapshot) { + const path = snapshot.ref.formattedName; + this.outstandingDocuments.delete(path); + this.retrievedDocuments.set(path, snapshot); + ++resultCount; + } + } + } catch (error) { + const shouldRetry = + // Transactional reads are retried via the transaction runner. + !request.transaction && + !request.newTransaction && + // Only retry if we made progress. + resultCount > 0 && + // Don't retry permanent errors. + error.code !== undefined && + !isPermanentRpcError(error, 'batchGetDocuments'); + + logger( + 'DocumentReader.fetchDocuments', + requestTag, + 'BatchGetDocuments failed with error: %s. Retrying: %s', + error, + shouldRetry, + ); + if (shouldRetry) { + return this.fetchDocuments(requestTag); + } else { + throw error; + } + } finally { + logger( + 'DocumentReader.fetchDocuments', + requestTag, + 'Received %d results', + resultCount, + ); + } + } +} diff --git a/handwritten/firestore/dev/src/document.ts b/handwritten/firestore/dev/src/document.ts new file mode 100644 index 00000000000..9c809c52b53 --- /dev/null +++ b/handwritten/firestore/dev/src/document.ts @@ -0,0 +1,1161 @@ +/*! + * Copyright 2019 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; + +import * as deepEqual from 'fast-deep-equal'; + +import * as assert from 'assert'; + +import {google} from '../protos/firestore_v1_proto_api'; +import {FieldTransform} from './field-value'; +import {FieldPath, validateFieldPath} from './path'; +import {DocumentReference} from './reference/document-reference'; +import {Serializer} from './serializer'; +import {Timestamp} from './timestamp'; +import {ApiMapValue, defaultConverter, UpdateMap} from './types'; +import {isEmpty, isObject, isPlainObject} from './util'; + +import api = google.firestore.v1; + +/** + * Returns a builder for DocumentSnapshot and QueryDocumentSnapshot instances. + * Invoke `.build()' to assemble the final snapshot. + * + * @private + * @internal + */ +export class DocumentSnapshotBuilder< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> { + /** The fields of the Firestore `Document` Protobuf backing this document. */ + fieldsProto?: ApiMapValue; + + /** The time when this document was read. */ + readTime?: Timestamp; + + /** The time when this document was created. */ + createTime?: Timestamp; + + /** The time when this document was last updated. */ + updateTime?: Timestamp; + + // We include the DocumentReference in the constructor in order to allow the + // DocumentSnapshotBuilder to be typed with when + // it is constructed. + constructor(readonly ref: DocumentReference) {} + + /** + * Builds the DocumentSnapshot. + * + * @private + * @internal + * @returns Returns either a QueryDocumentSnapshot (if `fieldsProto` was + * provided) or a DocumentSnapshot. + */ + build(): + | QueryDocumentSnapshot + | DocumentSnapshot { + assert( + (this.fieldsProto !== undefined) === (this.createTime !== undefined), + 'Create time should be set iff document exists.', + ); + assert( + (this.fieldsProto !== undefined) === (this.updateTime !== undefined), + 'Update time should be set iff document exists.', + ); + return this.fieldsProto + ? new QueryDocumentSnapshot( + this.ref, + this.fieldsProto!, + this.readTime!, + this.createTime!, + this.updateTime!, + ) + : new DocumentSnapshot( + this.ref, + undefined, + this.readTime!, + ); + } +} + +/** + * A DocumentSnapshot is an immutable representation for a document in a + * Firestore database. The data can be extracted with + * [data()]{@link DocumentSnapshot#data} or + * [get(fieldPath)]{@link DocumentSnapshot#get} to get a + * specific field. + * + *

For a DocumentSnapshot that points to a non-existing document, any data + * access will return 'undefined'. You can use the + * [exists]{@link DocumentSnapshot#exists} property to explicitly verify a + * document's existence. + * + * @class DocumentSnapshot + */ +export class DocumentSnapshot< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> implements firestore.DocumentSnapshot +{ + private _ref: DocumentReference; + private _serializer: Serializer; + private _readTime: Timestamp | undefined; + private _createTime: Timestamp | undefined; + private _updateTime: Timestamp | undefined; + + /** + * @private + * @internal + * + * @param ref The reference to the document. + * @param _fieldsProto The fields of the Firestore `Document` Protobuf backing + * this document (or undefined if the document does not exist). + * @param readTime The time when this snapshot was read (or undefined if + * the document exists only locally). + * @param createTime The time when the document was created (or undefined if + * the document does not exist). + * @param updateTime The time when the document was last updated (or undefined + * if the document does not exist). + */ + constructor( + ref: DocumentReference, + /** + * @internal + * @private + **/ + readonly _fieldsProto?: ApiMapValue, + readTime?: Timestamp, + createTime?: Timestamp, + updateTime?: Timestamp, + ) { + this._ref = ref; + this._serializer = ref.firestore._serializer!; + this._readTime = readTime; + this._createTime = createTime; + this._updateTime = updateTime; + } + + /** + * Creates a DocumentSnapshot from an object. + * + * @private + * @internal + * @param ref The reference to the document. + * @param obj The object to store in the DocumentSnapshot. + * @returns The created DocumentSnapshot. + */ + static fromObject( + ref: DocumentReference, + obj: firestore.DocumentData, + ): DocumentSnapshot { + const serializer = ref.firestore._serializer!; + return new DocumentSnapshot(ref, serializer.encodeFields(obj)); + } + /** + * Creates a DocumentSnapshot from an UpdateMap. + * + * This methods expands the top-level field paths in a JavaScript map and + * turns { foo.bar : foobar } into { foo { bar : foobar }} + * + * @private + * @internal + * @param ref The reference to the document. + * @param data The field/value map to expand. + * @returns The created DocumentSnapshot. + */ + static fromUpdateMap< + AppModelType, + DbModelType extends firestore.DocumentData, + >( + ref: firestore.DocumentReference, + data: UpdateMap, + ): DocumentSnapshot { + const serializer = (ref as DocumentReference) + .firestore._serializer!; + + /** + * Merges 'value' at the field path specified by the path array into + * 'target'. + */ + function merge( + target: ApiMapValue, + value: unknown, + path: string[], + pos: number, + ): ApiMapValue | null { + const key = path[pos]; + const isLast = pos === path.length - 1; + + if (target[key] === undefined) { + if (isLast) { + if (value instanceof FieldTransform) { + // If there is already data at this path, we need to retain it. + // Otherwise, we don't include it in the DocumentSnapshot. + return !isEmpty(target) ? target : null; + } + // The merge is done. + const leafNode = serializer.encodeValue(value); + if (leafNode) { + target[key] = leafNode; + } + return target; + } else { + // We need to expand the target object. + const childNode = { + mapValue: { + fields: {}, + }, + }; + + const nestedValue = merge( + childNode.mapValue.fields, + value, + path, + pos + 1, + ); + + if (nestedValue) { + childNode.mapValue.fields = nestedValue; + target[key] = childNode; + return target; + } else { + return !isEmpty(target) ? target : null; + } + } + } else { + assert(!isLast, "Can't merge current value into a nested object"); + target[key].mapValue!.fields = merge( + target[key].mapValue!.fields!, + value, + path, + pos + 1, + ); + return target; + } + } + + const res: ApiMapValue = {}; + + for (const [key, value] of data) { + const path = key.toArray(); + merge(res, value, path, 0); + } + + return new DocumentSnapshot( + ref as DocumentReference, + res, + ); + } + + /** + * True if the document exists. + * + * @type {boolean} + * @name DocumentSnapshot#exists + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then((documentSnapshot) => { + * if (documentSnapshot.exists) { + * console.log(`Data: ${JSON.stringify(documentSnapshot.data())}`); + * } + * }); + * ``` + */ + get exists(): boolean { + return this._fieldsProto !== undefined; + } + + /** + * A [DocumentReference]{@link DocumentReference} for the document + * stored in this snapshot. + * + * @type {DocumentReference} + * @name DocumentSnapshot#ref + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then((documentSnapshot) => { + * if (documentSnapshot.exists) { + * console.log(`Found document at '${documentSnapshot.ref.path}'`); + * } + * }); + * ``` + */ + get ref(): DocumentReference { + return this._ref; + } + + /** + * The ID of the document for which this DocumentSnapshot contains data. + * + * @type {string} + * @name DocumentSnapshot#id + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then((documentSnapshot) => { + * if (documentSnapshot.exists) { + * console.log(`Document found with name '${documentSnapshot.id}'`); + * } + * }); + * ``` + */ + get id(): string { + return this._ref.id; + } + + /** + * The time the document was created. Undefined for documents that don't + * exist. + * + * @type {Timestamp|undefined} + * @name DocumentSnapshot#createTime + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * if (documentSnapshot.exists) { + * let createTime = documentSnapshot.createTime; + * console.log(`Document created at '${createTime.toDate()}'`); + * } + * }); + * ``` + */ + get createTime(): Timestamp | undefined { + return this._createTime; + } + + /** + * The time the document was last updated (at the time the snapshot was + * generated). Undefined for documents that don't exist. + * + * @type {Timestamp|undefined} + * @name DocumentSnapshot#updateTime + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * if (documentSnapshot.exists) { + * let updateTime = documentSnapshot.updateTime; + * console.log(`Document updated at '${updateTime.toDate()}'`); + * } + * }); + * ``` + */ + get updateTime(): Timestamp | undefined { + return this._updateTime; + } + + /** + * The time this snapshot was read. + * + * @type {Timestamp} + * @name DocumentSnapshot#readTime + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * let readTime = documentSnapshot.readTime; + * console.log(`Document read at '${readTime.toDate()}'`); + * }); + * ``` + */ + get readTime(): Timestamp { + if (this._readTime === undefined) { + throw new Error("Called 'readTime' on a local document"); + } + return this._readTime; + } + + /** + * Retrieves all fields in the document as an object. Returns 'undefined' if + * the document doesn't exist. + * + * @returns {T|undefined} An object containing all fields in the document or + * 'undefined' if the document doesn't exist. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * let data = documentSnapshot.data(); + * console.log(`Retrieved data: ${JSON.stringify(data)}`); + * }); + * ``` + */ + data(): AppModelType | undefined { + const fields = this._fieldsProto; + + if (fields === undefined) { + return undefined; + } + + // We only want to use the converter and create a new QueryDocumentSnapshot + // if a converter has been provided. + if (this.ref._converter !== defaultConverter()) { + const untypedReference = new DocumentReference( + this.ref.firestore, + this.ref._path, + ); + return this.ref._converter.fromFirestore( + new QueryDocumentSnapshot( + untypedReference, + this._fieldsProto!, + this.readTime, + this.createTime!, + this.updateTime!, + ), + ); + } else { + const obj: firestore.DocumentData = {}; + for (const prop of Object.keys(fields)) { + obj[prop] = this._serializer.decodeValue(fields[prop]); + } + return obj as AppModelType; + } + } + + /** + * Retrieves the field specified by `field`. + * + * @param {string|FieldPath} field The field path + * (e.g. 'foo' or 'foo.bar') to a specific field. + * @returns {*} The data at the specified field location or undefined if no + * such field exists. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({ a: { b: 'c' }}).then(() => { + * return documentRef.get(); + * }).then(documentSnapshot => { + * let field = documentSnapshot.get('a.b'); + * console.log(`Retrieved field value: ${field}`); + * }); + * ``` + */ + // We deliberately use `any` in the external API to not impose type-checking + // on end users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(field: string | FieldPath): any { + validateFieldPath('field', field); + + const protoField = this.protoField(field); + + if (protoField === undefined) { + return undefined; + } + + return this._serializer.decodeValue(protoField); + } + + /** + * Retrieves the field specified by 'fieldPath' in its Protobuf JS + * representation. + * + * @private + * @internal + * @param field The path (e.g. 'foo' or 'foo.bar') to a specific field. + * @returns The Protobuf-encoded data at the specified field location or + * undefined if no such field exists. + */ + protoField(field: string | FieldPath): api.IValue | undefined { + let fields: ApiMapValue | api.IValue | undefined = this._fieldsProto; + + if (fields === undefined) { + return undefined; + } + + const components = FieldPath.fromArgument(field).toArray(); + while (components.length > 1) { + fields = (fields as ApiMapValue)[components.shift()!]; + + if (!fields || !fields.mapValue) { + return undefined; + } + + fields = fields.mapValue.fields!; + } + + return (fields as ApiMapValue)[components[0]]; + } + + /** + * Convert a document snapshot to the Firestore 'Write' proto. + * + * @private + * @internal + */ + toWriteProto(): api.IWrite { + return { + update: { + name: this._ref.formattedName, + fields: this._fieldsProto, + }, + }; + } + + /** + * Convert a document snapshot to the Firestore 'Document' proto. + * + * @private + * @internal + */ + toDocumentProto(): api.IDocument { + return { + name: this._ref.formattedName, + createTime: this.createTime?.toProto().timestampValue, + updateTime: this.updateTime?.toProto().timestampValue, + fields: this._fieldsProto, + }; + } + + /** + * Returns true if the document's data and path in this `DocumentSnapshot` is + * equal to the provided value. + * + * @param {*} other The value to compare against. + * @returns {boolean} true if this `DocumentSnapshot` is equal to the provided + * value. + */ + isEqual( + other: firestore.DocumentSnapshot, + ): boolean { + // Since the read time is different on every document read, we explicitly + // ignore all document metadata in this comparison. + return ( + this === other || + (other instanceof DocumentSnapshot && + this._ref.isEqual( + (other as DocumentSnapshot)._ref, + ) && + deepEqual(this._fieldsProto, other._fieldsProto)) + ); + } +} + +/** + * A QueryDocumentSnapshot contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with [data()]{@link QueryDocumentSnapshot#data} + * or [get()]{@link DocumentSnapshot#get} to get a specific field. + * + * A QueryDocumentSnapshot offers the same API surface as a + * {@link DocumentSnapshot}. Since query results contain only existing + * documents, the [exists]{@link DocumentSnapshot#exists} property will + * always be true and [data()]{@link QueryDocumentSnapshot#data} will never + * return 'undefined'. + * + * @class QueryDocumentSnapshot + * @extends DocumentSnapshot + */ +export class QueryDocumentSnapshot< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, + > + extends DocumentSnapshot + implements firestore.QueryDocumentSnapshot +{ + /** + * The time the document was created. + * + * @type {Timestamp} + * @name QueryDocumentSnapshot#createTime + * @readonly + * @override + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.get().forEach(snapshot => { + * console.log(`Document created at '${snapshot.createTime.toDate()}'`); + * }); + * ``` + */ + get createTime(): Timestamp { + return super.createTime!; + } + + /** + * The time the document was last updated (at the time the snapshot was + * generated). + * + * @type {Timestamp} + * @name QueryDocumentSnapshot#updateTime + * @readonly + * @override + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.get().forEach(snapshot => { + * console.log(`Document updated at '${snapshot.updateTime.toDate()}'`); + * }); + * ``` + */ + get updateTime(): Timestamp { + return super.updateTime!; + } + + /** + * Retrieves all fields in the document as an object. + * + * @override + * + * @returns {T} An object containing all fields in the document. + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.get().forEach(documentSnapshot => { + * let data = documentSnapshot.data(); + * console.log(`Retrieved data: ${JSON.stringify(data)}`); + * }); + * ``` + */ + data(): AppModelType { + const data = super.data(); + if (!data) { + throw new Error( + 'The data in a QueryDocumentSnapshot should always exist.', + ); + } + return data; + } +} + +/** + * A Firestore Document Mask contains the field paths affected by an update. + * + * @class + * @private + * @internal + */ +export class DocumentMask { + private _sortedPaths: FieldPath[]; + + /** + * @private + * @internal + * @private + * + * @param fieldPaths The field paths in this mask. + */ + constructor(fieldPaths: FieldPath[]) { + this._sortedPaths = fieldPaths; + this._sortedPaths.sort((a, b) => a.compareTo(b)); + } + + /** + * Creates a document mask with the field paths of a document. + * + * @private + * @internal + * @param data A map with fields to modify. Only the keys are used to extract + * the document mask. + */ + static fromUpdateMap(data: UpdateMap): DocumentMask { + const fieldPaths: FieldPath[] = []; + + data.forEach((value, key) => { + if (!(value instanceof FieldTransform) || value.includeInDocumentMask) { + fieldPaths.push(FieldPath.fromArgument(key)); + } + }); + + return new DocumentMask(fieldPaths); + } + + /** + * Creates a document mask from an array of field paths. + * + * @private + * @internal + * @param fieldMask A list of field paths. + */ + static fromFieldMask( + fieldMask: Array, + ): DocumentMask { + const fieldPaths: FieldPath[] = []; + + for (const fieldPath of fieldMask) { + fieldPaths.push(FieldPath.fromArgument(fieldPath)); + } + + return new DocumentMask(fieldPaths); + } + + /** + * Creates a document mask with the field names of a document. + * + * @private + * @internal + * @param data An object with fields to modify. Only the keys are used to + * extract the document mask. + */ + static fromObject(data: firestore.DocumentData): DocumentMask { + const fieldPaths: FieldPath[] = []; + + function extractFieldPaths( + currentData: firestore.DocumentData, + currentPath?: FieldPath, + ): void { + let isEmpty = true; + + for (const key of Object.keys(currentData)) { + isEmpty = false; + + // We don't split on dots since fromObject is called with + // DocumentData. + const childSegment = new FieldPath(key); + const childPath = currentPath + ? currentPath.append(childSegment) + : childSegment; + const value = currentData[key]; + if (value instanceof FieldTransform) { + if (value.includeInDocumentMask) { + fieldPaths.push(childPath); + } + } else if (isPlainObject(value)) { + extractFieldPaths(value, childPath); + } else if (value !== undefined) { + // If the value is undefined it can never participate in the document + // mask. With `ignoreUndefinedProperties` set to false, + // `validateDocumentData` will reject an undefined value before even + // computing the document mask. + fieldPaths.push(childPath); + } + } + + // Add a field path for an explicitly updated empty map. + if (currentPath && isEmpty) { + fieldPaths.push(currentPath); + } + } + + extractFieldPaths(data); + + return new DocumentMask(fieldPaths); + } + + /** + * Returns true if this document mask contains no fields. + * + * @private + * @internal + * @returns {boolean} Whether this document mask is empty. + */ + get isEmpty(): boolean { + return this._sortedPaths.length === 0; + } + + /** + * Removes the specified values from a sorted field path array. + * + * @private + * @internal + * @param input A sorted array of FieldPaths. + * @param values An array of FieldPaths to remove. + */ + private static removeFromSortedArray( + input: FieldPath[], + values: FieldPath[], + ): void { + for (let i = 0; i < input.length; ) { + let removed = false; + + for (const fieldPath of values) { + if (input[i].isEqual(fieldPath)) { + input.splice(i, 1); + removed = true; + break; + } + } + + if (!removed) { + ++i; + } + } + } + + /** + * Removes the field path specified in 'fieldPaths' from this document mask. + * + * @private + * @internal + * @param fieldPaths An array of FieldPaths. + */ + removeFields(fieldPaths: FieldPath[]): void { + DocumentMask.removeFromSortedArray(this._sortedPaths, fieldPaths); + } + + /** + * Returns whether this document mask contains 'fieldPath'. + * + * @private + * @internal + * @param fieldPath The field path to test. + * @returns Whether this document mask contains 'fieldPath'. + */ + contains(fieldPath: FieldPath): boolean { + for (const sortedPath of this._sortedPaths) { + const cmp = sortedPath.compareTo(fieldPath); + + if (cmp === 0) { + return true; + } else if (cmp > 0) { + return false; + } + } + + return false; + } + + /** + * Removes all properties from 'data' that are not contained in this document + * mask. + * + * @private + * @internal + * @param data An object to filter. + * @returns A shallow copy of the object filtered by this document mask. + */ + applyTo(data: firestore.DocumentData): firestore.DocumentData { + /*! + * Applies this DocumentMask to 'data' and computes the list of field paths + * that were specified in the mask but are not present in 'data'. + */ + const applyDocumentMask: ( + data: firestore.DocumentData, + ) => firestore.DocumentData = data => { + const remainingPaths = this._sortedPaths.slice(0); + + const processObject: ( + currentData: firestore.DocumentData, + currentPath?: FieldPath, + ) => firestore.DocumentData | null = (currentData, currentPath) => { + let result: firestore.DocumentData | null = null; + + Object.keys(currentData).forEach(key => { + const childPath = currentPath + ? currentPath.append(key) + : new FieldPath(key); + if (this.contains(childPath)) { + DocumentMask.removeFromSortedArray(remainingPaths, [childPath]); + result = result || {}; + result[key] = currentData[key]; + } else if (isObject(currentData[key])) { + const childObject = processObject( + currentData[key] as firestore.DocumentData, + childPath, + ); + if (childObject) { + result = result || {}; + result[key] = childObject; + } + } + }); + + return result; + }; + + // processObject() returns 'null' if the DocumentMask is empty. + const filteredData = processObject(data) || {}; + + return { + filteredData, + remainingPaths, + }; + }; + + const result = applyDocumentMask(data); + + if (result.remainingPaths.length !== 0) { + throw new Error( + `Input data is missing for field "${result.remainingPaths[0]}".`, + ); + } + + return result.filteredData; + } + + /** + * Converts a document mask to the Firestore 'DocumentMask' Proto. + * + * @private + * @internal + * @returns A Firestore 'DocumentMask' Proto. + */ + toProto(): api.IDocumentMask { + if (this.isEmpty) { + return {}; + } + + const encodedPaths: string[] = []; + for (const fieldPath of this._sortedPaths) { + encodedPaths.push(fieldPath.formattedName); + } + + return { + fieldPaths: encodedPaths, + }; + } +} + +/** + * A Firestore Document Transform. + * + * A DocumentTransform contains pending server-side transforms and their + * corresponding field paths. + * + * @private + * @internal + * @class + */ +export class DocumentTransform< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> { + /** + * @private + * @internal + * @private + * + * @param ref The DocumentReference for this transform. + * @param transforms A Map of FieldPaths to FieldTransforms. + */ + constructor( + private readonly ref: DocumentReference, + private readonly transforms: Map, + ) {} + + /** + * Generates a DocumentTransform from a JavaScript object. + * + * @private + * @internal + * @param ref The `DocumentReference` to use for the DocumentTransform. + * @param obj The object to extract the transformations from. + * @returns The Document Transform. + */ + static fromObject( + ref: firestore.DocumentReference, + obj: firestore.DocumentData, + ): DocumentTransform { + const updateMap = new Map(); + + for (const prop of Object.keys(obj)) { + updateMap.set(new FieldPath(prop), obj[prop]); + } + + return DocumentTransform.fromUpdateMap( + ref, + updateMap, + ); + } + + /** + * Generates a DocumentTransform from an Update Map. + * + * @private + * @internal + * @param ref The `DocumentReference` to use for the DocumentTransform. + * @param data The update data to extract the transformations from. + * @returns The Document Transform. + */ + static fromUpdateMap< + AppModelType, + DbModelType extends firestore.DocumentData, + >( + ref: firestore.DocumentReference, + data: UpdateMap, + ): DocumentTransform { + const transforms = new Map(); + + function encode_( + val: unknown, + path: FieldPath, + allowTransforms: boolean, + ): void { + if (val instanceof FieldTransform && val.includeInDocumentTransform) { + if (allowTransforms) { + transforms.set(path, val); + } else { + throw new Error( + `${val.methodName}() is not supported inside of array values.`, + ); + } + } else if (Array.isArray(val)) { + for (let i = 0; i < val.length; ++i) { + // We need to verify that no array value contains a document transform + encode_(val[i], path.append(String(i)), false); + } + } else if (isPlainObject(val)) { + for (const prop of Object.keys(val)) { + encode_(val[prop], path.append(new FieldPath(prop)), allowTransforms); + } + } + } + + data.forEach((value, key) => { + encode_(value, FieldPath.fromArgument(key), true); + }); + + return new DocumentTransform( + ref as DocumentReference, + transforms, + ); + } + + /** + * Whether this DocumentTransform contains any actionable transformations. + * + * @private + * @internal + */ + get isEmpty(): boolean { + return this.transforms.size === 0; + } + + /** + * Returns the array of fields in this DocumentTransform. + * + * @private + * @internal + */ + get fields(): FieldPath[] { + return Array.from(this.transforms.keys()); + } + + /** + * Validates the user provided field values in this document transform. + * @private + * @internal + */ + validate(): void { + const allowUndefined = + !!this.ref.firestore._settings.ignoreUndefinedProperties; + this.transforms.forEach(transform => transform.validate(allowUndefined)); + } + + /** + * Converts a document transform to the Firestore 'FieldTransform' Proto. + * + * @private + * @internal + * @param serializer The Firestore serializer + * @returns A list of Firestore 'FieldTransform' Protos + */ + toProto(serializer: Serializer): api.DocumentTransform.IFieldTransform[] { + return Array.from(this.transforms, ([path, transform]) => + transform.toProto(serializer, path), + ); + } +} + +/** + * A Firestore Precondition encapsulates options for database writes. + * + * @private + * @internal + * @class + */ +export class Precondition { + private _exists?: boolean; + private _lastUpdateTime?: Timestamp; + + /** + * @private + * @internal + * @private + * + * @param options.exists - Whether the referenced document should exist in + * Firestore, + * @param options.lastUpdateTime - The last update time of the referenced + * document in Firestore. + * @param options + */ + constructor(options?: { + exists?: boolean; + lastUpdateTime?: firestore.Timestamp; + }) { + if (options !== undefined) { + this._exists = options.exists; + this._lastUpdateTime = options.lastUpdateTime as Timestamp; + } + } + + /** + * Generates the Protobuf `Preconditon` object for this precondition. + * + * @private + * @internal + * @returns The `Preconditon` Protobuf object or 'null' if there are no + * preconditions. + */ + toProto(): api.IPrecondition | null { + if (this.isEmpty) { + return null; + } + + const proto: api.IPrecondition = {}; + + if (this._lastUpdateTime !== undefined) { + proto.updateTime = this._lastUpdateTime!.toProto().timestampValue; + } else { + proto.exists = this._exists; + } + + return proto; + } + + /** + * Whether this DocumentTransform contains any enforcement. + * + * @private + * @internal + */ + get isEmpty(): boolean { + return this._exists === undefined && !this._lastUpdateTime; + } +} diff --git a/handwritten/firestore/dev/src/external-modules.d.ts b/handwritten/firestore/dev/src/external-modules.d.ts new file mode 100644 index 00000000000..a7e069d4d38 --- /dev/null +++ b/handwritten/firestore/dev/src/external-modules.d.ts @@ -0,0 +1,19 @@ +/*! + * Copyright 2019 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// TODO(mrschmidt): Come up with actual definitions for these modules. +declare module 'functional-red-black-tree'; +declare module 'length-prefixed-json-stream'; diff --git a/handwritten/firestore/dev/src/field-value.ts b/handwritten/firestore/dev/src/field-value.ts new file mode 100644 index 00000000000..46d4a979442 --- /dev/null +++ b/handwritten/firestore/dev/src/field-value.ts @@ -0,0 +1,639 @@ +/*! + * Copyright 2018 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; + +import * as deepEqual from 'fast-deep-equal'; + +import * as proto from '../protos/firestore_v1_proto_api'; + +import {FieldPath} from './path'; +import {Serializer, validateUserInput} from './serializer'; +import {isPrimitiveArrayEqual} from './util'; +import { + invalidArgumentMessage, + validateMinNumberOfArguments, + validateNumber, +} from './validate'; + +import api = proto.google.firestore.v1; + +/** + * Represent a vector type in Firestore documents. + * Create an instance with {@link FieldValue.vector}. + * + * @class VectorValue + */ +export class VectorValue implements firestore.VectorValue { + private readonly _values: number[]; + + /** + * @private + * @internal + */ + constructor(values: number[] | undefined) { + // Making a copy of the parameter. + this._values = (values || []).map(n => n); + } + + /** + * Returns a copy of the raw number array form of the vector. + */ + public toArray(): number[] { + return this._values.map(n => n); + } + + /** + * @private + * @internal + */ + _toProto(serializer: Serializer): api.IValue { + return serializer.encodeVector(this._values); + } + + /** + * @private + * @internal + */ + static _fromProto(valueArray: api.IValue): VectorValue { + const values = valueArray.arrayValue?.values?.map(v => { + return v.doubleValue!; + }); + return new VectorValue(values); + } + + /** + * Returns `true` if the two VectorValue has the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean { + return isPrimitiveArrayEqual(this._values, other._values); + } +} + +/** + * Sentinel values that can be used when writing documents with set(), create() + * or update(). + * + * @class FieldValue + */ +export class FieldValue implements firestore.FieldValue { + /** @private */ + constructor() {} + + /** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ + static vector(values?: number[]): VectorValue { + return new VectorValue(values); + } + + /** + * Returns a sentinel for use with update() or set() with {merge:true} to mark + * a field for deletion. + * + * @returns {FieldValue} The sentinel value to use in your objects. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * let data = { a: 'b', c: 'd' }; + * + * documentRef.set(data).then(() => { + * return documentRef.update({a: Firestore.FieldValue.delete()}); + * }).then(() => { + * // Document now only contains { c: 'd' } + * }); + * ``` + */ + static delete(): FieldValue { + return DeleteTransform.DELETE_SENTINEL; + } + + /** + * Returns a sentinel used with set(), create() or update() to include a + * server-generated timestamp in the written data. + * + * @returns {FieldValue} The FieldValue sentinel for use in a call to set(), + * create() or update(). + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({ + * time: Firestore.FieldValue.serverTimestamp() + * }).then(() => { + * return documentRef.get(); + * }).then(doc => { + * console.log(`Server time set to ${doc.get('time')}`); + * }); + * ``` + */ + static serverTimestamp(): FieldValue { + return ServerTimestampTransform.SERVER_TIMESTAMP_SENTINEL; + } + + /** + * Returns a special value that can be used with set(), create() or update() + * that tells the server to increment the the field's current value by the + * given value. + * + * If either current field value or the operand uses floating point + * precision, both values will be interpreted as floating point numbers and + * all arithmetic will follow IEEE 754 semantics. Otherwise, integer + * precision is kept and the result is capped between -2^63 and 2^63-1. + * + * If the current field value is not of type 'number', or if the field does + * not yet exist, the transformation will set the field to the given value. + * + * @param {number} n The value to increment by. + * @returns {FieldValue} The FieldValue sentinel for use in a call to set(), + * create() or update(). + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.update( + * 'counter', Firestore.FieldValue.increment(1) + * ).then(() => { + * return documentRef.get(); + * }).then(doc => { + * // doc.get('counter') was incremented + * }); + * ``` + */ + static increment(n: number): FieldValue { + // eslint-disable-next-line prefer-rest-params + validateMinNumberOfArguments('FieldValue.increment', arguments, 1); + return new NumericIncrementTransform(n); + } + + /** + * Returns a special value that can be used with set(), create() or update() + * that tells the server to union the given elements with any array value that + * already exists on the server. Each specified element that doesn't already + * exist in the array will be added to the end. If the field being modified is + * not already an array it will be overwritten with an array containing + * exactly the specified elements. + * + * @param {...*} elements The elements to union into the array. + * @returns {FieldValue} The FieldValue sentinel for use in a call to set(), + * create() or update(). + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.update( + * 'array', Firestore.FieldValue.arrayUnion('foo') + * ).then(() => { + * return documentRef.get(); + * }).then(doc => { + * // doc.get('array') contains field 'foo' + * }); + * ``` + */ + static arrayUnion(...elements: unknown[]): FieldValue { + validateMinNumberOfArguments('FieldValue.arrayUnion', elements, 1); + return new ArrayUnionTransform(elements); + } + + /** + * Returns a special value that can be used with set(), create() or update() + * that tells the server to remove the given elements from any array value + * that already exists on the server. All instances of each element specified + * will be removed from the array. If the field being modified is not already + * an array it will be overwritten with an empty array. + * + * @param {...*} elements The elements to remove from the array. + * @returns {FieldValue} The FieldValue sentinel for use in a call to set(), + * create() or update(). + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.update( + * 'array', Firestore.FieldValue.arrayRemove('foo') + * ).then(() => { + * return documentRef.get(); + * }).then(doc => { + * // doc.get('array') no longer contains field 'foo' + * }); + * ``` + */ + static arrayRemove(...elements: unknown[]): FieldValue { + validateMinNumberOfArguments('FieldValue.arrayRemove', elements, 1); + return new ArrayRemoveTransform(elements); + } + + /** + * Returns true if this `FieldValue` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @returns {boolean} true if this `FieldValue` is equal to the provided value. + * + * @example + * ``` + * let fieldValues = [ + * Firestore.FieldValue.increment(-1.0), + * Firestore.FieldValue.increment(-1), + * Firestore.FieldValue.increment(-0.0), + * Firestore.FieldValue.increment(-0), + * Firestore.FieldValue.increment(0), + * Firestore.FieldValue.increment(0.0), + * Firestore.FieldValue.increment(1), + * Firestore.FieldValue.increment(1.0) + * ]; + * + * let equal = 0; + * for (let i = 0; i < fieldValues.length; ++i) { + * for (let j = i + 1; j < fieldValues.length; ++j) { + * if (fieldValues[i].isEqual(fieldValues[j])) { + * ++equal; + * } + * } + * } + * console.log(`Found ${equal} equalities.`); + * ``` + */ + isEqual(other: firestore.FieldValue): boolean { + return this === other; + } +} + +/** + * An internal interface shared by all field transforms. + * + * A 'FieldTransform` subclass should implement '.includeInDocumentMask', + * '.includeInDocumentTransform' and 'toProto' (if '.includeInDocumentTransform' + * is 'true'). + * + * @private + * @internal + * @abstract + */ +export abstract class FieldTransform extends FieldValue { + /** Whether this FieldTransform should be included in the document mask. */ + abstract get includeInDocumentMask(): boolean; + + /** + * Whether this FieldTransform should be included in the list of document + * transforms. + */ + abstract get includeInDocumentTransform(): boolean; + + /** The method name used to obtain the field transform. */ + abstract get methodName(): string; + + /** + * Performs input validation on the values of this field transform. + * + * @param allowUndefined Whether to allow nested properties that are `undefined`. + */ + abstract validate(allowUndefined: boolean): void; + + /*** + * The proto representation for this field transform. + * + * @param serializer The Firestore serializer. + * @param fieldPath The field path to apply this transformation to. + * @returns The 'FieldTransform' proto message. + */ + abstract toProto( + serializer: Serializer, + fieldPath: FieldPath, + ): api.DocumentTransform.IFieldTransform; +} + +/** + * A transform that deletes a field from a Firestore document. + * + * @private + * @internal + */ +export class DeleteTransform extends FieldTransform { + /** + * Sentinel value for a field delete. + * @private + * @internal + */ + static DELETE_SENTINEL = new DeleteTransform(); + + private constructor() { + super(); + } + + /** + * Deletes are included in document masks. + * @private + * @internal + */ + get includeInDocumentMask(): true { + return true; + } + + /** + * Deletes are are omitted from document transforms. + * @private + * @internal + */ + get includeInDocumentTransform(): false { + return false; + } + + get methodName(): string { + return 'FieldValue.delete'; + } + + validate(): void {} + + toProto(): never { + throw new Error( + 'FieldValue.delete() should not be included in a FieldTransform', + ); + } +} + +/** + * A transform that sets a field to the Firestore server time. + * + * @private + * @internal + */ +class ServerTimestampTransform extends FieldTransform { + /** + * Sentinel value for a server timestamp. + * + * @private + * @internal + */ + static SERVER_TIMESTAMP_SENTINEL = new ServerTimestampTransform(); + + private constructor() { + super(); + } + + /** + * Server timestamps are omitted from document masks. + * + * @private + * @internal + */ + get includeInDocumentMask(): false { + return false; + } + + /** + * Server timestamps are included in document transforms. + * + * @private + * @internal + */ + get includeInDocumentTransform(): true { + return true; + } + + get methodName(): string { + return 'FieldValue.serverTimestamp'; + } + + validate(): void {} + + toProto( + serializer: Serializer, + fieldPath: FieldPath, + ): api.DocumentTransform.IFieldTransform { + return { + fieldPath: fieldPath.formattedName, + setToServerValue: 'REQUEST_TIME', + }; + } +} + +/** + * Increments a field value on the backend. + * + * @private + * @internal + */ +class NumericIncrementTransform extends FieldTransform { + constructor(private readonly operand: number) { + super(); + } + + /** + * Numeric transforms are omitted from document masks. + * + * @private + * @internal + */ + get includeInDocumentMask(): false { + return false; + } + + /** + * Numeric transforms are included in document transforms. + * + * @private + * @internal + */ + get includeInDocumentTransform(): true { + return true; + } + + get methodName(): string { + return 'FieldValue.increment'; + } + + validate(): void { + validateNumber('FieldValue.increment()', this.operand); + } + + toProto( + serializer: Serializer, + fieldPath: FieldPath, + ): api.DocumentTransform.IFieldTransform { + const encodedOperand = serializer.encodeValue(this.operand)!; + return {fieldPath: fieldPath.formattedName, increment: encodedOperand}; + } + + isEqual(other: firestore.FieldValue): boolean { + return ( + this === other || + (other instanceof NumericIncrementTransform && + this.operand === other.operand) + ); + } +} + +/** + * Transforms an array value via a union operation. + * + * @private + * @internal + */ +class ArrayUnionTransform extends FieldTransform { + constructor(private readonly elements: unknown[]) { + super(); + } + + /** + * Array transforms are omitted from document masks. + * @private + * @internal + */ + get includeInDocumentMask(): false { + return false; + } + + /** + * Array transforms are included in document transforms. + * @private + * @internal + */ + get includeInDocumentTransform(): true { + return true; + } + + get methodName(): string { + return 'FieldValue.arrayUnion'; + } + + validate(allowUndefined: boolean): void { + for (let i = 0; i < this.elements.length; ++i) { + validateArrayElement(i, this.elements[i], allowUndefined); + } + } + + toProto( + serializer: Serializer, + fieldPath: FieldPath, + ): api.DocumentTransform.IFieldTransform { + const encodedElements = serializer.encodeValue(this.elements)!.arrayValue!; + return { + fieldPath: fieldPath.formattedName, + appendMissingElements: encodedElements, + }; + } + + isEqual(other: firestore.FieldValue): boolean { + return ( + this === other || + (other instanceof ArrayUnionTransform && + deepEqual(this.elements, other.elements)) + ); + } +} + +/** + * Transforms an array value via a remove operation. + * + * @private + * @internal + */ +class ArrayRemoveTransform extends FieldTransform { + constructor(private readonly elements: unknown[]) { + super(); + } + + /** + * Array transforms are omitted from document masks. + * @private + * @internal + */ + get includeInDocumentMask(): false { + return false; + } + + /** + * Array transforms are included in document transforms. + * @private + * @internal + */ + get includeInDocumentTransform(): true { + return true; + } + + get methodName(): string { + return 'FieldValue.arrayRemove'; + } + + validate(allowUndefined: boolean): void { + for (let i = 0; i < this.elements.length; ++i) { + validateArrayElement(i, this.elements[i], allowUndefined); + } + } + + toProto( + serializer: Serializer, + fieldPath: FieldPath, + ): api.DocumentTransform.IFieldTransform { + const encodedElements = serializer.encodeValue(this.elements)!.arrayValue!; + return { + fieldPath: fieldPath.formattedName, + removeAllFromArray: encodedElements, + }; + } + + isEqual(other: firestore.FieldValue): boolean { + return ( + this === other || + (other instanceof ArrayRemoveTransform && + deepEqual(this.elements, other.elements)) + ); + } +} + +/** + * Validates that `value` can be used as an element inside of an array. Certain + * field values (such as ServerTimestamps) are rejected. Nested arrays are also + * rejected. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The value to validate. + * @param allowUndefined Whether to allow nested properties that are `undefined`. + */ +function validateArrayElement( + arg: string | number, + value: unknown, + allowUndefined: boolean, +): void { + if (Array.isArray(value)) { + throw new Error( + `${invalidArgumentMessage( + arg, + 'array element', + )} Nested arrays are not supported.`, + ); + } + validateUserInput( + arg, + value, + 'array element', + /*path=*/ {allowDeletes: 'none', allowTransforms: false, allowUndefined}, + /*path=*/ undefined, + /*level=*/ 0, + /*inArray=*/ true, + ); +} diff --git a/handwritten/firestore/dev/src/filter.ts b/handwritten/firestore/dev/src/filter.ts new file mode 100644 index 00000000000..cb884d539e2 --- /dev/null +++ b/handwritten/firestore/dev/src/filter.ts @@ -0,0 +1,222 @@ +/*! + * Copyright 2023 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; + +/** + * A `Filter` represents a restriction on one or more field values and can + * be used to refine the results of a {@link Query}. + * `Filters`s are created by invoking {@link Filter#where}, {@link Filter#or}, + * or {@link Filter#and} and can then be passed to {@link Query#where} + * to create a new {@link Query} instance that also contains this `Filter`. + */ +export abstract class Filter { + /** + * Creates and returns a new [Filter]{@link Filter}, which can be + * applied to [Query.where()]{@link Query#where}, [Filter.or()]{@link Filter#or}, + * or [Filter.and()]{@link Filter#and}. When applied to a [Query]{@link Query} + * it requires that documents must contain the specified field and that its value should + * satisfy the relation constraint provided. + * + * @param {string|FieldPath} fieldPath The name of a property value to compare. + * @param {string} opStr A comparison operation in the form of a string. + * Acceptable operator strings are "<", "<=", "==", "!=", ">=", ">", "array-contains", + * "in", "not-in", and "array-contains-any". + * @param {*} value The value to which to compare the field for inclusion in + * a query. + * @returns {Filter} The created Filter. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.where(Filter.where('foo', '==', 'bar')).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + public static where( + fieldPath: string | firestore.FieldPath, + opStr: firestore.WhereFilterOp, + value: unknown, + ): Filter { + return new UnaryFilter(fieldPath, opStr, value); + } + + /** + * Creates and returns a new [Filter]{@link Filter} that is a + * disjunction of the given {@link Filter}s. A disjunction filter includes + * a document if it satisfies any of the given {@link Filter}s. + * + * The returned Filter can be applied to [Query.where()]{@link Query#where}, + * [Filter.or()]{@link Filter#or}, or [Filter.and()]{@link Filter#and}. When + * applied to a [Query]{@link Query} it requires that documents must satisfy + * one of the provided {@link Filter}s. + * + * @param {...Filter} filters Optional. The {@link Filter}s + * for OR operation. These must be created with calls to {@link Filter#where}, + * {@link Filter#or}, or {@link Filter#and}. + * @returns {Filter} The created {@link Filter}. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * // doc.foo == 'bar' || doc.baz > 0 + * let orFilter = Filter.or(Filter.where('foo', '==', 'bar'), Filter.where('baz', '>', 0)); + * + * collectionRef.where(orFilter).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + public static or(...filters: Filter[]): Filter { + return new CompositeFilter(filters, 'OR'); + } + + /** + * Creates and returns a new [Filter]{@link Filter} that is a + * conjunction of the given {@link Filter}s. A conjunction filter includes + * a document if it satisfies all of the given {@link Filter}s. + * + * The returned Filter can be applied to [Query.where()]{@link Query#where}, + * [Filter.or()]{@link Filter#or}, or [Filter.and()]{@link Filter#and}. When + * applied to a [Query]{@link Query} it requires that documents must satisfy + * one of the provided {@link Filter}s. + * + * @param {...Filter} filters Optional. The {@link Filter}s + * for AND operation. These must be created with calls to {@link Filter#where}, + * {@link Filter#or}, or {@link Filter#and}. + * @returns {Filter} The created {@link Filter}. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * // doc.foo == 'bar' && doc.baz > 0 + * let andFilter = Filter.and(Filter.where('foo', '==', 'bar'), Filter.where('baz', '>', 0)); + * + * collectionRef.where(andFilter).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + public static and(...filters: Filter[]): Filter { + return new CompositeFilter(filters, 'AND'); + } +} + +/** + * A `UnaryFilter` represents a restriction on one field value and can + * be used to refine the results of a {@link Query}. + * `UnaryFilter`s are created by invoking {@link Filter#where} and can then + * be passed to {@link Query#where} to create a new {@link Query} instance + * that also contains this `UnaryFilter`. + * + * @private + * @internal + */ +export class UnaryFilter extends Filter { + /** + @private + @internal + */ + public constructor( + private field: string | firestore.FieldPath, + private operator: firestore.WhereFilterOp, + private value: unknown, + ) { + super(); + } + + /** + @private + @internal + */ + public _getField(): string | firestore.FieldPath { + return this.field; + } + + /** + @private + @internal + */ + public _getOperator(): firestore.WhereFilterOp { + return this.operator; + } + + /** + @private + @internal + */ + public _getValue(): unknown { + return this.value; + } +} + +/** + * A `CompositeFilter` is used to narrow the set of documents returned + * by a Firestore query by performing the logical OR or AND of multiple + * {@link Filters}s. `CompositeFilters`s are created by invoking {@link Filter#or} + * or {@link Filter#and} and can then be passed to {@link Query#where} + * to create a new query instance that also contains the `CompositeFilter`. + * + * @private + * @internal + */ +export class CompositeFilter extends Filter { + /** + @private + @internal + */ + public constructor( + private filters: Filter[], + private operator: CompositeOperator, + ) { + super(); + } + + /** + @private + @internal + */ + public _getFilters(): Filter[] { + return this.filters; + } + + /** + @private + @internal + */ + public _getOperator(): CompositeOperator { + return this.operator; + } +} + +/** + * Composition operator of a `CompositeFilter`. This operator specifies the + * behavior of the `CompositeFilter`. + * + * @private + * @internal + */ +export type CompositeOperator = 'AND' | 'OR'; diff --git a/handwritten/firestore/dev/src/geo-point.ts b/handwritten/firestore/dev/src/geo-point.ts new file mode 100644 index 00000000000..0c9ecab1315 --- /dev/null +++ b/handwritten/firestore/dev/src/geo-point.ts @@ -0,0 +1,120 @@ +/*! + * Copyright 2018 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; + +import {google} from '../protos/firestore_v1_proto_api'; +import {Serializable} from './serializer'; +import {validateNumber} from './validate'; + +import api = google.firestore.v1; + +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as a latitude/longitude pair. + * + * @class + */ +export class GeoPoint implements Serializable, firestore.GeoPoint { + private readonly _latitude: number; + private readonly _longitude: number; + + /** + * Creates a [GeoPoint]{@link GeoPoint}. + * + * @param {number} latitude The latitude as a number between -90 and 90. + * @param {number} longitude The longitude as a number between -180 and 180. + * + * @example + * ``` + * let data = { + * google: new Firestore.GeoPoint(37.422, 122.084) + * }; + * + * firestore.doc('col/doc').set(data).then(() => { + * console.log(`Location is ${data.google.latitude}, ` + + * `${data.google.longitude}`); + * }); + * ``` + */ + constructor(latitude: number, longitude: number) { + validateNumber('latitude', latitude, {minValue: -90, maxValue: 90}); + validateNumber('longitude', longitude, {minValue: -180, maxValue: 180}); + + this._latitude = latitude; + this._longitude = longitude; + } + + /** + * The latitude as a number between -90 and 90. + * + * @type {number} + * @name GeoPoint#latitude + * @readonly + */ + get latitude(): number { + return this._latitude; + } + + /** + * The longitude as a number between -180 and 180. + * + * @type {number} + * @name GeoPoint#longitude + * @readonly + */ + get longitude(): number { + return this._longitude; + } + + /** + * Returns true if this `GeoPoint` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @returns {boolean} true if this `GeoPoint` is equal to the provided value. + */ + isEqual(other: firestore.GeoPoint): boolean { + return ( + this === other || + (other instanceof GeoPoint && + this.latitude === other.latitude && + this.longitude === other.longitude) + ); + } + + /** + * Converts the GeoPoint to a google.type.LatLng proto. + * @private + * @internal + */ + toProto(): api.IValue { + return { + geoPointValue: { + latitude: this.latitude, + longitude: this.longitude, + }, + }; + } + + /** + * Converts a google.type.LatLng proto to its GeoPoint representation. + * @private + * @internal + */ + static fromProto(proto: google.type.ILatLng): GeoPoint { + return new GeoPoint(proto.latitude || 0, proto.longitude || 0); + } +} diff --git a/handwritten/firestore/dev/src/index.ts b/handwritten/firestore/dev/src/index.ts new file mode 100644 index 00000000000..d5a74afd5eb --- /dev/null +++ b/handwritten/firestore/dev/src/index.ts @@ -0,0 +1,2047 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; + +import type {CallOptions, ClientOptions} from 'google-gax'; +import type * as googleGax from 'google-gax'; +import type * as googleGaxFallback from 'google-gax/build/src/fallback'; +import {Duplex, PassThrough, Transform} from 'stream'; + +import {URL} from 'url'; + +import {google} from '../protos/firestore_v1_proto_api'; +import {ExponentialBackoff, ExponentialBackoffSetting} from './backoff'; +import {BulkWriter} from './bulk-writer'; +import {BundleBuilder} from './bundle'; +import {fieldsFromJson, timestampFromJson} from './convert'; +import {DocumentReader} from './document-reader'; +import { + DocumentSnapshot, + DocumentSnapshotBuilder, + QueryDocumentSnapshot, +} from './document'; +import {logger, setLibVersion} from './logger'; +import { + DEFAULT_DATABASE_ID, + QualifiedResourcePath, + ResourcePath, + validateResourcePath, +} from './path'; +import {ClientPool} from './pool'; +import {CollectionReference} from './reference/collection-reference'; +import {DocumentReference} from './reference/document-reference'; +import {Serializer} from './serializer'; +import {Timestamp} from './timestamp'; +import {parseGetAllArguments, Transaction} from './transaction'; +import { + ApiMapValue, + FirestoreStreamingMethod, + FirestoreUnaryMethod, + GapicClient, + UnaryMethod, +} from './types'; +import { + autoId, + Deferred, + getRetryParams, + isPermanentRpcError, + requestTag, + wrapError, + tryGetPreferRestEnvironmentVariable, +} from './util'; +import { + validateBoolean, + validateFunction, + validateHost, + validateInteger, + validateMinNumberOfArguments, + validateObject, + validateString, + validateTimestamp, +} from './validate'; +import {WriteBatch} from './write-batch'; + +import {interfaces} from './v1/firestore_client_config.json'; +const serviceConfig = interfaces['google.firestore.v1.Firestore']; + +import api = google.firestore.v1; +import {CollectionGroup} from './collection-group'; +import { + RECURSIVE_DELETE_MAX_PENDING_OPS, + RECURSIVE_DELETE_MIN_PENDING_OPS, + RecursiveDelete, +} from './recursive-delete'; +import { + ATTRIBUTE_KEY_DOC_COUNT, + ATTRIBUTE_KEY_IS_TRANSACTIONAL, + ATTRIBUTE_KEY_NUM_RESPONSES, + SPAN_NAME_BATCH_GET_DOCUMENTS, + TraceUtil, +} from './telemetry/trace-util'; +import {DisabledTraceUtil} from './telemetry/disabled-trace-util'; +import {EnabledTraceUtil} from './telemetry/enabled-trace-util'; +import {PipelineSource} from './pipelines'; + +import * as Pipelines from './pipelines'; +export {Pipelines}; + +export {CollectionReference} from './reference/collection-reference'; +export {DocumentReference} from './reference/document-reference'; +export {QuerySnapshot} from './reference/query-snapshot'; +export {Query} from './reference/query'; +export type {AggregateQuery} from './reference/aggregate-query'; +export type {AggregateQuerySnapshot} from './reference/aggregate-query-snapshot'; +export type {VectorQuery} from './reference/vector-query'; +export type {VectorQuerySnapshot} from './reference/vector-query-snapshot'; +export type {VectorQueryOptions} from './reference/vector-query-options'; +export {BulkWriter} from './bulk-writer'; +export type {BulkWriterError} from './bulk-writer'; +export type {BundleBuilder} from './bundle'; +export {DocumentSnapshot, QueryDocumentSnapshot} from './document'; +export {FieldValue, VectorValue} from './field-value'; +export {Filter} from './filter'; +export {WriteBatch, WriteResult} from './write-batch'; +export {Transaction} from './transaction'; +export {Timestamp} from './timestamp'; +export {DocumentChange} from './document-change'; +export type {DocumentChangeType} from './document-change'; +export {FieldPath} from './path'; +export {GeoPoint} from './geo-point'; +export {CollectionGroup}; +export {QueryPartition} from './query-partition'; +export {setLogFunction} from './logger'; +export {Aggregate, AggregateField} from './aggregate'; +export type { + AggregateFieldType, + AggregateSpec, + AggregateType, +} from './aggregate'; +export type { + PlanSummary, + ExecutionStats, + ExplainMetrics, + ExplainResults, +} from './query-profile'; + +const libVersion = require('../../package.json').version; +setLibVersion(libVersion); + +/*! + * DO NOT REMOVE THE FOLLOWING NAMESPACE DEFINITIONS + */ +/** + * @namespace google.protobuf + */ +/** + * @namespace google.rpc + */ +/** + * @namespace google.longrunning + */ +/** + * @namespace google.firestore.v1 + */ +/** + * @namespace google.firestore.v1beta1 + */ +/** + * @namespace google.firestore.admin.v1 + */ + +/*! + * HTTP header for the resource prefix to improve routing and project isolation + * by the backend. + */ +const CLOUD_RESOURCE_HEADER = 'google-cloud-resource-prefix'; + +/** + * The maximum number of times to retry idempotent requests. + * @private + */ +export const MAX_REQUEST_RETRIES = 5; + +/** + * The maximum number of times to attempt a transaction before failing. + * @private + */ +export const DEFAULT_MAX_TRANSACTION_ATTEMPTS = 5; + +/*! + * The default number of idle GRPC channel to keep. + */ +export const DEFAULT_MAX_IDLE_CHANNELS = 1; + +/*! + * The maximum number of concurrent requests supported by a single GRPC channel, + * as enforced by Google's Frontend. If the SDK issues more than 100 concurrent + * operations, we need to use more than one GAPIC client since these clients + * multiplex all requests over a single channel. + */ +const MAX_CONCURRENT_REQUESTS_PER_CLIENT = 100; + +/** + * Document data (e.g. for use with + * [set()]{@link DocumentReference#set}) consisting of fields mapped + * to values. + * + * @typedef {Object.} DocumentData + */ + +/** + * Converter used by [withConverter()]{@link Query#withConverter} to transform + * user objects of type `AppModelType` into Firestore data of type + * `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when storing + * and retrieving objects from Firestore. + * + * @example + * ``` + * class Post { + * constructor(readonly title: string, readonly author: string) {} + * + * toString(): string { + * return this.title + ', by ' + this.author; + * } + * } + * + * const postConverter = { + * toFirestore(post: Post): FirebaseFirestore.DocumentData { + * return {title: post.title, author: post.author}; + * }, + * fromFirestore( + * snapshot: FirebaseFirestore.QueryDocumentSnapshot + * ): Post { + * const data = snapshot.data(); + * return new Post(data.title, data.author); + * } + * }; + * + * const postSnap = await Firestore() + * .collection('posts') + * .withConverter(postConverter) + * .doc().get(); + * const post = postSnap.data(); + * if (post !== undefined) { + * post.title; // string + * post.toString(); // Should be defined + * post.someNonExistentProperty; // TS error + * } + * + * ``` + * @property {Function} toFirestore Called by the Firestore SDK to convert a + * custom model object of type `AppModelType` into a plain Javascript object + * (suitable for writing directly to the Firestore database). + * @property {Function} fromFirestore Called by the Firestore SDK to convert + * Firestore data into an object of type `AppModelType`. + * @typedef {Object} FirestoreDataConverter + */ + +/** + * Update data (for use with [update]{@link DocumentReference#update}) + * that contains paths mapped to values. Fields that contain dots + * reference nested fields within the document. + * + * You can update a top-level field in your document by using the field name + * as a key (e.g. `foo`). The provided value completely replaces the contents + * for this field. + * + * You can also update a nested field directly by using its field path as a key + * (e.g. `foo.bar`). This nested field update replaces the contents at `bar` + * but does not modify other data under `foo`. + * + * @example + * ``` + * const documentRef = firestore.doc('coll/doc'); + * documentRef.set({a1: {a2: 'val'}, b1: {b2: 'val'}, c1: {c2: 'val'}}); + * documentRef.update({ + * b1: {b3: 'val'}, + * 'c1.c3': 'val', + * }); + * // Value is {a1: {a2: 'val'}, b1: {b3: 'val'}, c1: {c2: 'val', c3: 'val'}} + * + * ``` + * @typedef {Object.} UpdateData + */ + +/** + * An options object that configures conditional behavior of + * [update()]{@link DocumentReference#update} and + * [delete()]{@link DocumentReference#delete} calls in + * [DocumentReference]{@link DocumentReference}, + * [WriteBatch]{@link WriteBatch}, [BulkWriter]{@link BulkWriter}, and + * [Transaction]{@link Transaction}. Using Preconditions, these calls + * can be restricted to only apply to documents that match the specified + * conditions. + * + * @example + * ``` + * const documentRef = firestore.doc('coll/doc'); + * + * documentRef.get().then(snapshot => { + * const updateTime = snapshot.updateTime; + * + * console.log(`Deleting document at update time: ${updateTime.toDate()}`); + * return documentRef.delete({ lastUpdateTime: updateTime }); + * }); + * + * ``` + * @property {Timestamp} lastUpdateTime The update time to enforce. If set, + * enforces that the document was last updated at lastUpdateTime. Fails the + * operation if the document was last updated at a different time. + * @property {boolean} exists If set, enforces that the target document must + * or must not exist. + * @typedef {Object} Precondition + */ + +/** + * An options object that configures the behavior of + * [set()]{@link DocumentReference#set} calls in + * [DocumentReference]{@link DocumentReference}, + * [WriteBatch]{@link WriteBatch}, and + * [Transaction]{@link Transaction}. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a SetOptions object with + * { merge : true }. + * + * @property {boolean} merge Changes the behavior of a set() call to only + * replace the values specified in its data argument. Fields omitted from the + * set() call remain untouched. + * @property {Array<(string|FieldPath)>} mergeFields Changes the behavior of + * set() calls to only replace the specified field paths. Any field path that is + * not specified is ignored and remains untouched. + * It is an error to pass a SetOptions object to a set() call that is missing a + * value for any of the fields specified here. + * @typedef {Object} SetOptions + */ + +/** + * An options object that can be used to configure the behavior of + * [getAll()]{@link Firestore#getAll} calls. By providing a `fieldMask`, these + * calls can be configured to only return a subset of fields. + * + * @property {Array<(string|FieldPath)>} fieldMask Specifies the set of fields + * to return and reduces the amount of data transmitted by the backend. + * Adding a field mask does not filter results. Documents do not need to + * contain values for all the fields in the mask to be part of the result set. + * @typedef {Object} ReadOptions + */ + +/** + * An options object to configure throttling on BulkWriter. + * + * Whether to disable or configure throttling. By default, throttling is + * enabled. `throttling` can be set to either a boolean or a config object. + * Setting it to `true` will use default values. You can override the defaults + * by setting it to `false` to disable throttling, or by setting the config + * values to enable throttling with the provided values. + * + * @property {boolean|Object} throttling Whether to disable or enable + * throttling. Throttling is enabled by default, if the field is set to `true` + * or if any custom throttling options are provided. `{ initialOpsPerSecond: + * number }` sets the initial maximum number of operations per second allowed by + * the throttler. If `initialOpsPerSecond` is not set, the default is 500 + * operations per second. `{ maxOpsPerSecond: number }` sets the maximum number + * of operations per second allowed by the throttler. If `maxOpsPerSecond` is + * not set, no maximum is enforced. + * @typedef {Object} BulkWriterOptions + */ + +/** + * An error thrown when a BulkWriter operation fails. + * + * The error used by {@link BulkWriter~shouldRetryCallback} set in + * {@link BulkWriter#onWriteError}. + * + * @property {GrpcStatus} code The status code of the error. + * @property {string} message The error message of the error. + * @property {DocumentReference} documentRef The document reference the + * operation was performed on. + * @property {'create' | 'set' | 'update' | 'delete'} operationType The type + * of operation performed. + * @property {number} failedAttempts How many times this operation has been + * attempted unsuccessfully. + * @typedef {Error} BulkWriterError + */ + +/** + * Status codes returned by GRPC operations. + * + * @see https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * @enum {number} + * @typedef {Object} GrpcStatus + */ + +/** + * The Firestore client represents a Firestore Database and is the entry point + * for all Firestore operations. + * + * @see [Firestore Documentation]{@link https://firebase.google.com/docs/firestore/} + * + * @class + * + * @example Install the client library with npm: + * ``` + * npm install --save @google-cloud/firestore + * + * ``` + * @example Import the client library + * ``` + * var Firestore = require('@google-cloud/firestore'); + * + * ``` + * @example Create a client that uses Application Default Credentials (ADC): + * ``` + * var firestore = new Firestore(); + * + * ``` + * @example Create a client with explicit credentials: + * ``` + * var firestore = new Firestore({ projectId: + * 'your-project-id', keyFilename: '/path/to/keyfile.json' + * }); + * + * ``` + * @example

+ * region_tag:firestore_quickstart + * Full quickstart example: + */ +export class Firestore implements firestore.Firestore { + /** + * A client pool to distribute requests over multiple GAPIC clients in order + * to work around a connection limit of 100 concurrent requests per client. + * @private + * @internal + */ + private _clientPool: ClientPool; + + /** + * Preloaded instance of google-gax (full module, with gRPC support). + */ + private _gax?: typeof googleGax; + + /** + * Preloaded instance of google-gax HTTP fallback implementation (no gRPC). + */ + private _gaxFallback?: typeof googleGaxFallback; + + /** + * The configuration options for the GAPIC client. + * @private + * @internal + */ + _settings: firestore.Settings = {}; + + /** + * Settings for the exponential backoff used by the streaming endpoints. + * @private + * @internal + */ + private _backoffSettings: ExponentialBackoffSetting; + + /** + * Whether the initialization settings can still be changed by invoking + * `settings()`. + * @private + * @internal + */ + private _settingsFrozen = false; + + /** + * The serializer to use for the Protobuf transformation. + * @private + * @internal + */ + _serializer: Serializer | null = null; + + /** + * The OpenTelemetry tracing utility object. + * @private + * @internal + */ + _traceUtil: TraceUtil; + + /** + * The project ID for this client. + * + * The project ID is auto-detected during the first request unless a project + * ID is passed to the constructor (or provided via `.settings()`). + * @private + * @internal + */ + private _projectId: string | undefined = undefined; + + /** + * The database ID provided via `.settings()`. + * + * @private + * @internal + */ + private _databaseId: string | undefined = undefined; + + /** + * Count of listeners that have been registered on the client. + * + * The client can only be terminated when there are no pending writes or + * registered listeners. + * @private + * @internal + */ + private registeredListenersCount = 0; + + /** + * A lazy-loaded BulkWriter instance to be used with recursiveDelete() if no + * BulkWriter instance is provided. + * + * @private + * @internal + */ + private _bulkWriter: BulkWriter | undefined; + + /** + * Lazy-load the Firestore's default BulkWriter. + * + * @private + * @internal + */ + private getBulkWriter(): BulkWriter { + if (!this._bulkWriter) { + this._bulkWriter = this.bulkWriter(); + } + return this._bulkWriter; + } + + /** + * Number of pending operations on the client. + * + * The client can only be terminated when there are no pending writes or + * registered listeners. + * @private + * @internal + */ + private bulkWritersCount = 0; + + /** + * @param {Object=} settings [Configuration object](#/docs). + * @param {string=} settings.projectId The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check the + * environment variable GCLOUD_PROJECT for your project ID. Can be omitted in + * environments that support + * {@link https://cloud.google.com/docs/authentication Application Default + * Credentials} + * @param {string=} settings.keyFilename Local file containing the Service + * Account credentials as downloaded from the Google Developers Console. Can + * be omitted in environments that support + * {@link https://cloud.google.com/docs/authentication Application Default + * Credentials}. To configure Firestore with custom credentials, use + * `settings.credentials` and provide the `client_email` and `private_key` of + * your service account. + * @param {{client_email:string=, private_key:string=}=} settings.credentials + * The `client_email` and `private_key` properties of the service account + * to use with your Firestore project. Can be omitted in environments that + * support {@link https://cloud.google.com/docs/authentication Application + * Default Credentials}. If your credentials are stored in a JSON file, you + * can specify a `keyFilename` instead. + * @param {string=} settings.host The host to connect to. + * @param {boolean=} settings.ssl Whether to use SSL when connecting. + * @param {number=} settings.maxIdleChannels The maximum number of idle GRPC + * channels to keep. A smaller number of idle channels reduces memory usage + * but increases request latency for clients with fluctuating request rates. + * If set to 0, shuts down all GRPC channels when the client becomes idle. + * Defaults to 1. + * @param {boolean=} settings.ignoreUndefinedProperties Whether to skip nested + * properties that are set to `undefined` during object serialization. If set + * to `true`, these properties are skipped and not written to Firestore. If + * set `false` or omitted, the SDK throws an exception when it encounters + * properties of type `undefined`. + * @param {boolean=} settings.preferRest Whether to force the use of HTTP/1.1 REST + * transport until a method that requires gRPC is called. When a method requires gRPC, + * this Firestore client will load dependent gRPC libraries and then use gRPC transport + * for communication from that point forward. Currently the only operation + * that requires gRPC is creating a snapshot listener with the method + * `DocumentReference.onSnapshot()`, `CollectionReference.onSnapshot()`, or + * `Query.onSnapshot()`. If specified, this setting value will take precedent over the + * environment variable `FIRESTORE_PREFER_REST`. If not specified, the + * SDK will use the value specified in the environment variable `FIRESTORE_PREFER_REST`. + * Valid values of `FIRESTORE_PREFER_REST` are `true` ('1') or `false` (`0`). Values are + * not case-sensitive. Any other value for the environment variable will be ignored and + * a warning will be logged to the console. + */ + constructor(settings?: firestore.Settings) { + const libraryHeader = { + libName: 'gccl', + libVersion, + }; + + if (settings && settings.firebaseVersion) { + libraryHeader.libVersion += ' fire/' + settings.firebaseVersion; + } + + if (settings && settings.firebaseAdminVersion) { + libraryHeader.libVersion += + ' fire-admin/' + settings.firebaseAdminVersion; + } + + this.validateAndApplySettings({...settings, ...libraryHeader}); + this._traceUtil = this.newTraceUtilInstance(this._settings); + + const retryConfig = serviceConfig.retry_params.default; + this._backoffSettings = { + initialDelayMs: retryConfig.initial_retry_delay_millis, + maxDelayMs: retryConfig.max_retry_delay_millis, + backoffFactor: retryConfig.retry_delay_multiplier, + }; + + const maxIdleChannels = + this._settings.maxIdleChannels === undefined + ? DEFAULT_MAX_IDLE_CHANNELS + : this._settings.maxIdleChannels; + this._clientPool = new ClientPool( + MAX_CONCURRENT_REQUESTS_PER_CLIENT, + maxIdleChannels, + /* clientFactory= */ (requiresGrpc: boolean) => { + let client: GapicClient; + + // Use the rest fallback if enabled and if the method does not require GRPC + const useFallback = + !this._settings.preferRest || requiresGrpc ? false : 'rest'; + + let gax: typeof googleGax | typeof googleGaxFallback; + if (useFallback) { + if (!this._gaxFallback) { + gax = this._gaxFallback = require('google-gax/fallback'); + } else { + gax = this._gaxFallback; + } + } else { + if (!this._gax) { + gax = this._gax = require('google-gax'); + } else { + gax = this._gax; + } + } + + if (this._settings.ssl === false) { + const grpcModule = this._settings.grpc ?? require('google-gax').grpc; + const sslCreds = grpcModule.credentials.createInsecure(); + + const settings: ClientOptions = { + sslCreds, + ...this._settings, + fallback: useFallback, + }; + + // Since `ssl === false`, if we're using the GAX fallback then + // also set the `protocol` option for GAX fallback to force http + if (useFallback) { + settings.protocol = 'http'; + } + + client = new module.exports.v1(settings, gax); + } else { + client = new module.exports.v1( + { + ...this._settings, + fallback: useFallback, + }, + gax, + ); + } + + logger( + 'clientFactory', + null, + 'Initialized Firestore GAPIC Client (useFallback: %s)', + useFallback, + ); + return client; + }, + /* clientDestructor= */ client => client.close(), + ); + + logger('Firestore', null, 'Initialized Firestore'); + } + + /** + * Specifies custom settings to be used to configure the `Firestore` + * instance. Can only be invoked once and before any other Firestore method. + * + * If settings are provided via both `settings()` and the `Firestore` + * constructor, both settings objects are merged and any settings provided via + * `settings()` take precedence. + * + * @param {object} settings The settings to use for all Firestore operations. + */ + settings(settings: firestore.Settings): void { + validateObject('settings', settings); + validateString('settings.projectId', settings.projectId, {optional: true}); + validateString('settings.databaseId', settings.databaseId, { + optional: true, + }); + + if (this._settingsFrozen) { + throw new Error( + 'Firestore has already been initialized. You can only call ' + + 'settings() once, and only before calling any other methods on a ' + + 'Firestore object.', + ); + } + + const mergedSettings = {...this._settings, ...settings}; + this.validateAndApplySettings(mergedSettings); + this._traceUtil = this.newTraceUtilInstance(this._settings); + this._settingsFrozen = true; + } + + private validateAndApplySettings(settings: firestore.Settings): void { + if (settings.projectId !== undefined) { + validateString('settings.projectId', settings.projectId); + this._projectId = settings.projectId; + } + + if (settings.databaseId !== undefined) { + validateString('settings.databaseId', settings.databaseId); + this._databaseId = settings.databaseId; + } + + let url: URL | null = null; + + // If preferRest is not specified in settings, but is set as environment variable, + // then use the environment variable value. + const preferRestEnvValue = tryGetPreferRestEnvironmentVariable(); + if (settings.preferRest === undefined && preferRestEnvValue !== undefined) { + settings = { + ...settings, + preferRest: preferRestEnvValue, + }; + } + + // If the environment variable is set, it should always take precedence + // over any user passed in settings. + if (process.env.FIRESTORE_EMULATOR_HOST) { + validateHost( + 'FIRESTORE_EMULATOR_HOST', + process.env.FIRESTORE_EMULATOR_HOST, + ); + + settings = { + ...settings, + host: process.env.FIRESTORE_EMULATOR_HOST, + ssl: false, + }; + url = new URL(`http://${settings.host}`); + } else if (settings.host !== undefined) { + validateHost('settings.host', settings.host); + url = new URL(`http://${settings.host}`); + } + + // Only store the host if a valid value was provided in `host`. + if (url !== null) { + if ( + (settings.servicePath !== undefined && + settings.servicePath !== url.hostname) || + (settings.apiEndpoint !== undefined && + settings.apiEndpoint !== url.hostname) + ) { + // eslint-disable-next-line no-console + console.warn( + `The provided host (${url.hostname}) in "settings" does not ` + + `match the existing host (${ + settings.servicePath ?? settings.apiEndpoint + }). Using the provided host.`, + ); + } + + settings.servicePath = url.hostname; + if (url.port !== '' && settings.port === undefined) { + settings.port = Number(url.port); + } + + // We need to remove the `host` and `apiEndpoint` setting, in case a user + // calls `settings()`, which will compare the the provided `host` to the + // existing hostname stored on `servicePath`. + delete settings.host; + delete settings.apiEndpoint; + } + + if (settings.ssl !== undefined) { + validateBoolean('settings.ssl', settings.ssl); + } + + if (settings.maxIdleChannels !== undefined) { + validateInteger('settings.maxIdleChannels', settings.maxIdleChannels, { + minValue: 0, + }); + } + + this._settings = settings; + this._settings.toJSON = function () { + const temp = Object.assign({}, this); + if (temp.credentials) { + temp.credentials = {private_key: '***', client_email: '***'}; + } + return temp; + }; + this._serializer = new Serializer(this); + } + + private newTraceUtilInstance(settings: firestore.Settings): TraceUtil { + let createEnabledInstance = true; + + // The environment variable can override options to enable/disable telemetry collection. + if ('FIRESTORE_ENABLE_TRACING' in process.env) { + const enableTracingEnvVar = + process.env.FIRESTORE_ENABLE_TRACING!.toLowerCase(); + if (enableTracingEnvVar === 'on' || enableTracingEnvVar === 'true') { + createEnabledInstance = true; + } + if (enableTracingEnvVar === 'off' || enableTracingEnvVar === 'false') { + createEnabledInstance = false; + } + } + + if (createEnabledInstance) { + return new EnabledTraceUtil(settings); + } else { + return new DisabledTraceUtil(); + } + } + + /** + * Returns the Project ID for this Firestore instance. Validates that + * `initializeIfNeeded()` was called before. + * + * @private + * @internal + */ + get projectId(): string { + if (this._projectId === undefined) { + throw new Error( + 'INTERNAL ERROR: Client is not yet ready to issue requests.', + ); + } + return this._projectId; + } + + /** + * Returns the Database ID for this Firestore instance. + */ + get databaseId(): string { + return this._databaseId || DEFAULT_DATABASE_ID; + } + + /** + * Returns the root path of the database. Validates that + * `initializeIfNeeded()` was called before. + * + * @private + * @internal + */ + get formattedName(): string { + return `projects/${this.projectId}/databases/${this.databaseId}`; + } + + /** + * Gets a [DocumentReference]{@link DocumentReference} instance that + * refers to the document at the specified path. + * + * @param {string} documentPath A slash-separated path to a document. + * @returns {DocumentReference} The + * [DocumentReference]{@link DocumentReference} instance. + * + * @example + * ``` + * let documentRef = firestore.doc('collection/document'); + * console.log(`Path of document is ${documentRef.path}`); + * ``` + */ + doc(documentPath: string): DocumentReference { + validateResourcePath('documentPath', documentPath); + + const path = ResourcePath.EMPTY.append(documentPath); + if (!path.isDocument) { + throw new Error( + `Value for argument "documentPath" must point to a document, but was "${documentPath}". Your path does not contain an even number of components.`, + ); + } + + return new DocumentReference(this, path); + } + + /** + * Gets a [CollectionReference]{@link CollectionReference} instance + * that refers to the collection at the specified path. + * + * @param {string} collectionPath A slash-separated path to a collection. + * @returns {CollectionReference} The + * [CollectionReference]{@link CollectionReference} instance. + * + * @example + * ``` + * let collectionRef = firestore.collection('collection'); + * + * // Add a document with an auto-generated ID. + * collectionRef.add({foo: 'bar'}).then((documentRef) => { + * console.log(`Added document at ${documentRef.path})`); + * }); + * ``` + */ + collection(collectionPath: string): CollectionReference { + validateResourcePath('collectionPath', collectionPath); + + const path = ResourcePath.EMPTY.append(collectionPath); + if (!path.isCollection) { + throw new Error( + `Value for argument "collectionPath" must point to a collection, but was "${collectionPath}". Your path does not contain an odd number of components.`, + ); + } + + return new CollectionReference(this, path); + } + + /** + * Creates and returns a new Query that includes all documents in the + * database that are contained in a collection or subcollection with the + * given collectionId. + * + * @param {string} collectionId Identifies the collections to query over. + * Every collection or subcollection with this ID as the last segment of its + * path will be included. Cannot contain a slash. + * @returns {CollectionGroup} The created CollectionGroup. + * + * @example + * ``` + * let docA = firestore.doc('mygroup/docA').set({foo: 'bar'}); + * let docB = firestore.doc('abc/def/mygroup/docB').set({foo: 'bar'}); + * + * Promise.all([docA, docB]).then(() => { + * let query = firestore.collectionGroup('mygroup'); + * query = query.where('foo', '==', 'bar'); + * return query.get().then(snapshot => { + * console.log(`Found ${snapshot.size} documents.`); + * }); + * }); + * ``` + */ + collectionGroup(collectionId: string): CollectionGroup { + if (collectionId.indexOf('/') !== -1) { + throw new Error( + `Invalid collectionId '${collectionId}'. Collection IDs must not contain '/'.`, + ); + } + + return new CollectionGroup(this, collectionId, /* converter= */ undefined); + } + + /** + * @beta + * Creates and returns a new PipelineSource, which allows specifying the source stage of a `Pipeline`. + * + * @example + * ``` + * let myPipeline: Pipeline = firestore.pipeline().collection('books'); + * ``` + */ + pipeline(): PipelineSource { + return new PipelineSource(this); + } + + /** + * Creates a [WriteBatch]{@link WriteBatch}, used for performing + * multiple writes as a single atomic operation. + * + * @returns {WriteBatch} A WriteBatch that operates on this Firestore + * client. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * + * // Add two documents in an atomic batch. + * let data = { foo: 'bar' }; + * writeBatch.set(firestore.doc('col/doc1'), data); + * writeBatch.set(firestore.doc('col/doc2'), data); + * + * writeBatch.commit().then(res => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + batch(): WriteBatch { + return new WriteBatch(this); + } + + /** + * Creates a [BulkWriter]{@link BulkWriter}, used for performing + * multiple writes in parallel. Gradually ramps up writes as specified + * by the 500/50/5 rule. + * + * If you pass `BulkWriterOptions`, you can + * configure the throttling rates for the created BulkWriter. + * + * @see [500/50/5 Documentation]{@link https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic} + * + * @param {BulkWriterOptions=} options BulkWriter options. + * @returns {BulkWriter} A BulkWriter that operates on this Firestore + * client. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * + * bulkWriter.create(firestore.doc('col/doc1'), {foo: 'bar'}) + * .then(res => { + * console.log(`Added document at ${res.writeTime}`); + * }); + * bulkWriter.update(firestore.doc('col/doc2'), {foo: 'bar'}) + * .then(res => { + * console.log(`Updated document at ${res.writeTime}`); + * }); + * bulkWriter.delete(firestore.doc('col/doc3')) + * .then(res => { + * console.log(`Deleted document at ${res.writeTime}`); + * }); + * await bulkWriter.close().then(() => { + * console.log('Executed all writes'); + * }); + * ``` + */ + bulkWriter(options?: firestore.BulkWriterOptions): BulkWriter { + return new BulkWriter(this, options); + } + + /** + * Creates a [DocumentSnapshot]{@link DocumentSnapshot} or a + * [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} from a + * `firestore.v1.Document` proto (or from a resource name for missing + * documents). + * + * This API is used by Google Cloud Functions and can be called with both + * 'Proto3 JSON' and 'Protobuf JS' encoded data. + * + * @private + * @param documentOrName The Firestore 'Document' proto or the resource name + * of a missing document. + * @param readTime A 'Timestamp' proto indicating the time this document was + * read. + * @param encoding One of 'json' or 'protobufJS'. Applies to both the + * 'document' Proto and 'readTime'. Defaults to 'protobufJS'. + * @returns A QueryDocumentSnapshot for existing documents, otherwise a + * DocumentSnapshot. + */ + snapshot_( + documentName: string, + readTime?: google.protobuf.ITimestamp, + encoding?: 'protobufJS', + ): DocumentSnapshot; + /** @private */ + snapshot_( + documentName: string, + readTime: string, + encoding: 'json', + ): DocumentSnapshot; + /** @private */ + snapshot_( + document: api.IDocument, + readTime: google.protobuf.ITimestamp, + encoding?: 'protobufJS', + ): QueryDocumentSnapshot; + /** @private */ + snapshot_( + document: {[k: string]: unknown}, + readTime: string, + encoding: 'json', + ): QueryDocumentSnapshot; + /** @private */ + snapshot_( + documentOrName: api.IDocument | {[k: string]: unknown} | string, + readTime?: google.protobuf.ITimestamp | string, + encoding?: 'json' | 'protobufJS', + ): DocumentSnapshot { + // TODO: Assert that Firestore Project ID is valid. + + let convertTimestamp: ( + timestampValue?: string | google.protobuf.ITimestamp, + argumentName?: string, + ) => google.protobuf.ITimestamp | undefined; + let convertFields: (data: ApiMapValue) => ApiMapValue; + + if (encoding === undefined || encoding === 'protobufJS') { + convertTimestamp = data => data as google.protobuf.ITimestamp; + convertFields = data => data; + } else if (encoding === 'json') { + // Google Cloud Functions calls us with Proto3 JSON format data, which we + // must convert to Protobuf JS. + convertTimestamp = timestampFromJson; + convertFields = fieldsFromJson; + } else { + throw new Error( + 'Unsupported encoding format. Expected "json" or "protobufJS", ' + + `but was "${encoding}".`, + ); + } + + let ref: DocumentReference; + let document: DocumentSnapshotBuilder; + if (typeof documentOrName === 'string') { + ref = new DocumentReference( + this, + QualifiedResourcePath.fromSlashSeparatedString(documentOrName), + ); + document = new DocumentSnapshotBuilder(ref); + } else { + ref = new DocumentReference( + this, + QualifiedResourcePath.fromSlashSeparatedString( + documentOrName.name as string, + ), + ); + document = new DocumentSnapshotBuilder(ref); + document.fieldsProto = documentOrName.fields + ? convertFields(documentOrName.fields as ApiMapValue) + : {}; + document.createTime = Timestamp.fromProto( + convertTimestamp( + documentOrName.createTime as string | google.protobuf.ITimestamp, + 'documentOrName.createTime', + )!, + ); + document.updateTime = Timestamp.fromProto( + convertTimestamp( + documentOrName.updateTime as string | google.protobuf.ITimestamp, + 'documentOrName.updateTime', + )!, + ); + } + + if (readTime) { + document.readTime = Timestamp.fromProto( + convertTimestamp(readTime, 'readTime')!, + ); + } + + return document.build(); + } + + /** + * Creates a new `BundleBuilder` instance to package selected Firestore data into + * a bundle. + * + * @param bundleId. The id of the bundle. When loaded on clients, client SDKs use this id + * and the timestamp associated with the built bundle to tell if it has been loaded already. + * If not specified, a random identifier will be used. + */ + bundle(name?: string): BundleBuilder { + return new BundleBuilder(name || autoId()); + } + + /** + * Function executed by {@link Firestore#runTransaction} within the transaction + * context. + * + * @callback Firestore~updateFunction + * @template T + * @param {Transaction} transaction The transaction object for this + * transaction. + * @returns {Promise} The promise returned at the end of the transaction. + * This promise will be returned by {@link Firestore#runTransaction} if the + * transaction completed successfully. + */ + + /** + * Options object for {@link Firestore#runTransaction} to configure a + * read-only transaction. + * + * @param {true} readOnly Set to true to indicate a read-only transaction. + * @param {Timestamp=} readTime If specified, documents are read at the given + * time. This may not be more than 60 seconds in the past from when the + * request is processed by the server. + * @typedef {Object} Firestore~ReadOnlyTransactionOptions + */ + + /** + * Options object for {@link Firestore#runTransaction} to configure a + * read-write transaction. + * + * @param {false=} readOnly Set to false or omit to indicate a read-write + * transaction. + * @param {number=} maxAttempts The maximum number of attempts for this + * transaction. Defaults to 5. + * @typedef {Object} Firestore~ReadWriteTransactionOptions + */ + + /** + * Executes the given updateFunction and commits the changes applied within + * the transaction. + * + * You can use the transaction object passed to 'updateFunction' to read and + * modify Firestore documents under lock. You have to perform all reads before + * before you perform any write. + * + * Transactions can be performed as read-only or read-write transactions. By + * default, transactions are executed in read-write mode. + * + * A read-write transaction obtains a pessimistic lock on all documents that + * are read during the transaction. These locks block other transactions, + * batched writes, and other non-transactional writes from changing that + * document. Any writes in a read-write transactions are committed once + * 'updateFunction' resolves, which also releases all locks. + * + * If a read-write transaction fails with contention, the transaction is + * retried up to five times. The `updateFunction` is invoked once for each + * attempt. + * + * Read-only transactions do not lock documents. They can be used to read + * documents at a consistent snapshot in time, which may be up to 60 seconds + * in the past. Read-only transactions are not retried. + * + * Transactions time out after 60 seconds if no documents are read. + * Transactions that are not committed within than 270 seconds are also + * aborted. Any remaining locks are released when a transaction times out. + * + * @template T + * @param {Firestore~updateFunction} updateFunction The user function to + * execute within the transaction context. + * @param { + * Firestore~ReadWriteTransactionOptions|Firestore~ReadOnlyTransactionOptions= + * } transactionOptions Transaction options. + * @returns {Promise} If the transaction completed successfully or was + * explicitly aborted (by the updateFunction returning a failed Promise), the + * Promise returned by the updateFunction will be returned here. Else if the + * transaction failed, a rejected Promise with the corresponding failure + * error will be returned. + * + * @example + * ``` + * let counterTransaction = firestore.runTransaction(transaction => { + * let documentRef = firestore.doc('col/doc'); + * return transaction.get(documentRef).then(doc => { + * if (doc.exists) { + * let count = doc.get('count') || 0; + * if (count > 10) { + * return Promise.reject('Reached maximum count'); + * } + * transaction.update(documentRef, { count: ++count }); + * return Promise.resolve(count); + * } + * + * transaction.create(documentRef, { count: 1 }); + * return Promise.resolve(1); + * }); + * }); + * + * counterTransaction.then(res => { + * console.log(`Count updated to ${res}`); + * }); + * ``` + */ + runTransaction( + updateFunction: (transaction: Transaction) => Promise, + transactionOptions?: + | firestore.ReadWriteTransactionOptions + | firestore.ReadOnlyTransactionOptions, + ): Promise { + validateFunction('updateFunction', updateFunction); + + const tag = requestTag(); + + if (transactionOptions) { + validateObject('transactionOptions', transactionOptions); + validateBoolean( + 'transactionOptions.readOnly', + transactionOptions.readOnly, + {optional: true}, + ); + + if (transactionOptions.readOnly) { + validateTimestamp( + 'transactionOptions.readTime', + transactionOptions.readTime, + {optional: true}, + ); + } else { + validateInteger( + 'transactionOptions.maxAttempts', + transactionOptions.maxAttempts, + {optional: true, minValue: 1}, + ); + } + } + + const transaction = new Transaction(this, tag, transactionOptions); + return this.initializeIfNeeded(tag).then(() => + transaction.runTransaction(updateFunction), + ); + } + + /** + * Fetches the root collections that are associated with this Firestore + * database. + * + * @returns {Promise.>} A Promise that resolves + * with an array of CollectionReferences. + * + * @example + * ``` + * firestore.listCollections().then(collections => { + * for (let collection of collections) { + * console.log(`Found collection with id: ${collection.id}`); + * } + * }); + * ``` + */ + listCollections(): Promise { + const rootDocument = new DocumentReference(this, ResourcePath.EMPTY); + return rootDocument.listCollections(); + } + + /** + * Retrieves multiple documents from Firestore. + * + * The first argument is required and must be of type `DocumentReference` + * followed by any additional `DocumentReference` documents. If used, the + * optional `ReadOptions` must be the last argument. + * + * @param {...DocumentReference|ReadOptions} documentRefsOrReadOptions The + * `DocumentReferences` to receive, followed by an optional field mask. + * @returns {Promise>} A Promise that + * contains an array with the resulting document snapshots. + * + * @example + * ``` + * let docRef1 = firestore.doc('col/doc1'); + * let docRef2 = firestore.doc('col/doc2'); + * + * firestore.getAll(docRef1, docRef2, { fieldMask: ['user'] }).then(docs => { + * console.log(`First document: ${JSON.stringify(docs[0])}`); + * console.log(`Second document: ${JSON.stringify(docs[1])}`); + * }); + * ``` + */ + getAll( + ...documentRefsOrReadOptions: Array< + | firestore.DocumentReference + | firestore.ReadOptions + > + ): Promise>> { + return this._traceUtil.startActiveSpan( + SPAN_NAME_BATCH_GET_DOCUMENTS, + () => { + validateMinNumberOfArguments( + 'Firestore.getAll', + documentRefsOrReadOptions, + 1, + ); + + const {documents, fieldMask} = parseGetAllArguments( + documentRefsOrReadOptions, + ); + + this._traceUtil.currentSpan().setAttributes({ + [ATTRIBUTE_KEY_IS_TRANSACTIONAL]: false, + [ATTRIBUTE_KEY_DOC_COUNT]: documents.length, + }); + + const tag = requestTag(); + + // Capture the error stack to preserve stack tracing across async calls. + const stack = Error().stack!; + + return this.initializeIfNeeded(tag) + .then(() => { + const reader = new DocumentReader(this, documents, fieldMask); + return reader.get(tag); + }) + .catch(err => { + throw wrapError(err, stack); + }); + }, + ); + } + + /** + * Registers a listener on this client, incrementing the listener count. This + * is used to verify that all listeners are unsubscribed when terminate() is + * called. + * + * @private + * @internal + */ + registerListener(): void { + this.registeredListenersCount += 1; + } + + /** + * Unregisters a listener on this client, decrementing the listener count. + * This is used to verify that all listeners are unsubscribed when terminate() + * is called. + * + * @private + * @internal + */ + unregisterListener(): void { + this.registeredListenersCount -= 1; + } + + /** + * Increments the number of open BulkWriter instances. This is used to verify + * that all pending operations are complete when terminate() is called. + * + * @private + * @internal + */ + _incrementBulkWritersCount(): void { + this.bulkWritersCount += 1; + } + + /** + * Decrements the number of open BulkWriter instances. This is used to verify + * that all pending operations are complete when terminate() is called. + * + * @private + * @internal + */ + _decrementBulkWritersCount(): void { + this.bulkWritersCount -= 1; + } + + /** + * Recursively deletes all documents and subcollections at and under the + * specified level. + * + * If any delete fails, the promise is rejected with an error message + * containing the number of failed deletes and the stack trace of the last + * failed delete. The provided reference is deleted regardless of whether + * all deletes succeeded. + * + * `recursiveDelete()` uses a BulkWriter instance with default settings to + * perform the deletes. To customize throttling rates or add success/error + * callbacks, pass in a custom BulkWriter instance. + * + * @param ref The reference of a document or collection to delete. + * @param bulkWriter A custom BulkWriter instance used to perform the + * deletes. + * @returns A promise that resolves when all deletes have been performed. + * The promise is rejected if any of the deletes fail. + * + * @example + * ``` + * // Recursively delete a reference and log the references of failures. + * const bulkWriter = firestore.bulkWriter(); + * bulkWriter + * .onWriteError((error) => { + * if ( + * error.failedAttempts < MAX_RETRY_ATTEMPTS + * ) { + * return true; + * } else { + * console.log('Failed write at document: ', error.documentRef.path); + * return false; + * } + * }); + * await firestore.recursiveDelete(docRef, bulkWriter); + * ``` + */ + recursiveDelete( + ref: // eslint-disable-next-line @typescript-eslint/no-explicit-any + | firestore.CollectionReference + // eslint-disable-next-line @typescript-eslint/no-explicit-any + | firestore.DocumentReference, + bulkWriter?: BulkWriter, + ): Promise { + return this._recursiveDelete( + ref, + RECURSIVE_DELETE_MAX_PENDING_OPS, + RECURSIVE_DELETE_MIN_PENDING_OPS, + bulkWriter, + ); + } + + /** + * This overload is not private in order to test the query resumption with + * startAfter() once the RecursiveDelete instance has MAX_PENDING_OPS pending. + * + * @private + * @internal + */ + // Visible for testing + _recursiveDelete( + ref: + | firestore.CollectionReference + | firestore.DocumentReference, + maxPendingOps: number, + minPendingOps: number, + bulkWriter?: BulkWriter, + ): Promise { + const writer = bulkWriter ?? this.getBulkWriter(); + const deleter = new RecursiveDelete( + this, + writer, + ref, + maxPendingOps, + minPendingOps, + ); + return deleter.run(); + } + + /** + * Terminates the Firestore client and closes all open streams. + * + * @returns A Promise that resolves when the client is terminated. + */ + async terminate(): Promise { + if (this._bulkWriter) { + await this._bulkWriter.close(); + this._bulkWriter = undefined; + } + if (this.registeredListenersCount > 0 || this.bulkWritersCount > 0) { + return Promise.reject( + 'All onSnapshot() listeners must be unsubscribed, and all BulkWriter ' + + 'instances must be closed before terminating the client. ' + + `There are ${this.registeredListenersCount} active listeners and ` + + `${this.bulkWritersCount} open BulkWriter instances.`, + ); + } + return this._clientPool.terminate(); + } + + /** + * Returns the Project ID to serve as the JSON representation of this + * Firestore instance. + * + * @returns An object that contains the project ID (or `undefined` if not yet + * available). + */ + toJSON(): object { + return {projectId: this._projectId}; + } + /** + * Initializes the client if it is not already initialized. All methods in the + * SDK can be used after this method completes. + * + * @private + * @internal + * @param requestTag A unique client-assigned identifier that caused this + * initialization. + * @returns A Promise that resolves when the client is initialized. + */ + async initializeIfNeeded(requestTag: string): Promise { + this._settingsFrozen = true; + + if (this._settings.ssl === false) { + // If SSL is false, we assume that we are talking to the emulator. We + // provide an Authorization header by default so that the connection is + // recognized as admin in Firestore Emulator. (If for some reason we're + // not connecting to the emulator, then this will result in denials with + // invalid token, rather than behave like clients not logged in. The user + // can then provide their own Authorization header, which will take + // precedence). + this._settings.customHeaders = { + Authorization: 'Bearer owner', + ...this._settings.customHeaders, + }; + } + + if (this._projectId === undefined) { + try { + this._projectId = await this._clientPool.run( + requestTag, + /* requiresGrpc= */ false, + gapicClient => gapicClient.getProjectId(), + ); + logger( + 'Firestore.initializeIfNeeded', + null, + 'Detected project ID: %s', + this._projectId, + ); + + // If the project ID was undefined when the TraceUtil was set up, we + // need to record it. + this._traceUtil.recordProjectIdAndResourceName( + this.projectId, + this.databaseId, + ); + } catch (err) { + logger( + 'Firestore.initializeIfNeeded', + null, + 'Failed to detect project ID: %s', + err, + ); + return Promise.reject(err); + } + } + } + + /** + * Returns GAX call options that set the cloud resource header. + * @private + * @internal + */ + private createCallOptions( + methodName: string, + retryCodes?: number[], + ): CallOptions { + const callOptions: CallOptions = { + otherArgs: { + headers: { + [CLOUD_RESOURCE_HEADER]: this.formattedName, + ...this._settings.customHeaders, + ...this._settings[methodName]?.customHeaders, + }, + }, + }; + + if (retryCodes) { + const retryParams = getRetryParams(methodName); + callOptions.retry = new (require('google-gax/fallback').RetryOptions)( + retryCodes, + retryParams, + ); + } + + return callOptions; + } + + /** + * A function returning a Promise that can be retried. + * + * @private + * @internal + * @callback retryFunction + * @returns {Promise} A Promise indicating the function's success. + */ + + /** + * Helper method that retries failed Promises. + * + * If 'delayMs' is specified, waits 'delayMs' between invocations. Otherwise, + * schedules the first attempt immediately, and then waits 100 milliseconds + * for further attempts. + * + * @private + * @internal + * @param methodName Name of the Veneer API endpoint that takes a request + * and GAX options. + * @param requestTag A unique client-assigned identifier for this request. + * @param func Method returning a Promise than can be retried. + * @returns A Promise with the function's result if successful within + * `attemptsRemaining`. Otherwise, returns the last rejected Promise. + */ + private async _retry( + methodName: string, + requestTag: string, + func: () => Promise, + ): Promise { + const backoff = new ExponentialBackoff(); + + let lastError: Error | undefined = undefined; + + for (let attempt = 0; attempt < MAX_REQUEST_RETRIES; ++attempt) { + if (lastError) { + logger( + 'Firestore._retry', + requestTag, + 'Retrying request that failed with error:', + lastError, + ); + } + + try { + await backoff.backoffAndWait(); + return await func(); + } catch (err) { + lastError = err; + + if (isPermanentRpcError(err, methodName)) { + break; + } + } + } + + logger( + 'Firestore._retry', + requestTag, + 'Request failed with error:', + lastError, + ); + return Promise.reject(lastError); + } + + /** + * Waits for the provided stream to become active and returns a paused but + * healthy stream. If an error occurs before the first byte is read, the + * method rejects the returned Promise. + * + * @private + * @internal + * @param backendStream The Node stream to monitor. + * @param lifetime A Promise that resolves when the stream receives an 'end', + * 'close' or 'finish' message. + * @param requestTag A unique client-assigned identifier for this request. + * @param request If specified, the request that should be written to the + * stream after opening. + * @returns A guaranteed healthy stream that should be used instead of + * `backendStream`. + */ + private _initializeStream( + backendStream: Duplex, + lifetime: Deferred, + requestTag: string, + request?: {}, + ): Promise { + const resultStream = new PassThrough({objectMode: true}); + resultStream.pause(); + + /** + * Whether we have resolved the Promise and returned the stream to the + * caller. + */ + let streamInitialized = false; + + return new Promise((resolve, reject) => { + function streamReady(): void { + if (!streamInitialized) { + streamInitialized = true; + logger('Firestore._initializeStream', requestTag, 'Stream ready'); + resolve(resultStream); + } + } + + function streamEnded(): void { + logger( + 'Firestore._initializeStream', + requestTag, + 'Received stream end', + ); + resultStream.unpipe(backendStream); + resolve(resultStream); + lifetime.resolve(); + } + + function streamFailed(err: Error): void { + if (!streamInitialized) { + // If we receive an error before we were able to receive any data, + // reject this stream. + logger( + 'Firestore._initializeStream', + requestTag, + 'Received initial error:', + err, + ); + reject(err); + } else { + logger( + 'Firestore._initializeStream', + requestTag, + 'Received stream error:', + err, + ); + // We execute the forwarding of the 'error' event via setImmediate() as + // V8 guarantees that the Promise chain returned from this method + // is resolved before any code executed via setImmediate(). This + // allows the caller to attach an error handler. + setImmediate(() => { + resultStream.emit('error', err); + }); + } + } + + backendStream.on('data', () => streamReady()); + backendStream.on('error', err => streamFailed(err)); + backendStream.on('end', () => streamEnded()); + backendStream.on('close', () => streamEnded()); + backendStream.on('finish', () => streamEnded()); + + backendStream.pipe(resultStream); + + if (request) { + logger( + 'Firestore._initializeStream', + requestTag, + 'Sending request: %j', + request, + ); + backendStream.write(request, 'utf-8', err => { + if (err) { + streamFailed(err); + } else { + logger( + 'Firestore._initializeStream', + requestTag, + 'Marking stream as healthy', + ); + streamReady(); + } + }); + } + }); + } + + /** + * A funnel for all non-streaming API requests, assigning a project ID where + * necessary within the request options. + * + * @private + * @internal + * @param methodName Name of the Veneer API endpoint that takes a request + * and GAX options. + * @param request The Protobuf request to send. + * @param requestTag A unique client-assigned identifier for this request. + * @param retryCodes If provided, a custom list of retry codes. If not + * provided, retry is based on the behavior as defined in the ServiceConfig. + * @returns A Promise with the request result. + */ + request( + methodName: FirestoreUnaryMethod, + request: Req, + requestTag: string, + retryCodes?: number[], + ): Promise { + const callOptions = this.createCallOptions(methodName, retryCodes); + + return this._clientPool.run( + requestTag, + /* requiresGrpc= */ false, + async gapicClient => { + try { + logger( + 'Firestore.request', + requestTag, + 'Sending request: %j', + request, + ); + const [result] = await ( + gapicClient[methodName] as UnaryMethod + )(request, callOptions); + logger( + 'Firestore.request', + requestTag, + 'Received response: %j', + result, + ); + return result; + } catch (err) { + logger('Firestore.request', requestTag, 'Received error:', err); + return Promise.reject(err); + } + }, + ); + } + + /** + * A funnel for streaming API requests, assigning a project ID where necessary + * within the request options. + * + * The stream is returned in paused state and needs to be resumed once all + * listeners are attached. + * + * @private + * @internal + * @param methodName Name of the streaming Veneer API endpoint that + * takes a request and GAX options. + * @param bidrectional Whether the request is bidirectional (true) or + * unidirectional (false_ + * @param request The Protobuf request to send. + * @param requestTag A unique client-assigned identifier for this request. + * @returns A Promise with the resulting read-only stream. + */ + requestStream( + methodName: FirestoreStreamingMethod, + bidrectional: boolean, + request: {}, + requestTag: string, + ): Promise { + const callOptions = this.createCallOptions(methodName); + + const bidirectional = methodName === 'listen'; + let numResponses = 0; + const NUM_RESPONSES_PER_TRACE_EVENT = 100; + + return this._retry(methodName, requestTag, () => { + const result = new Deferred(); + + void this._clientPool.run(requestTag, bidrectional, async gapicClient => { + logger( + 'Firestore.requestStream', + requestTag, + 'Sending request: %j', + request, + ); + + this._traceUtil + .currentSpan() + .addEvent(`Firestore.${methodName}: Start`); + + try { + const stream = bidirectional + ? gapicClient[methodName](callOptions) + : gapicClient[methodName](request, callOptions); + const logStream = new Transform({ + objectMode: true, + transform: (chunk, encoding, callback) => { + logger( + 'Firestore.requestStream', + requestTag, + 'Received response: %j', + chunk, + ); + numResponses++; + if (numResponses === 1) { + this._traceUtil + .currentSpan() + .addEvent(`Firestore.${methodName}: First response received`); + } else if (numResponses % NUM_RESPONSES_PER_TRACE_EVENT === 0) { + this._traceUtil + .currentSpan() + .addEvent( + `Firestore.${methodName}: Received ${numResponses} responses`, + ); + } + callback(); + }, + }); + stream.pipe(logStream); + + const lifetime = new Deferred(); + const resultStream = await this._initializeStream( + stream, + lifetime, + requestTag, + bidirectional ? request : undefined, + ); + resultStream.on('end', () => { + stream.end(); + this._traceUtil + .currentSpan() + .addEvent(`Firestore.${methodName}: Completed`, { + [ATTRIBUTE_KEY_NUM_RESPONSES]: numResponses, + }); + }); + result.resolve(resultStream); + + // While we return the stream to the callee early, we don't want to + // release the GAPIC client until the callee has finished processing the + // stream. + return lifetime.promise; + } catch (e) { + result.reject(e); + } + }); + + return result.promise; + }); + } +} + +/** + * A logging function that takes a single string. + * + * @callback Firestore~logFunction + * @param {string} Log message + */ + +// tslint:disable-next-line:no-default-export +/** + * The default export of the `@google-cloud/firestore` package is the + * {@link Firestore} class. + * + * See {@link Firestore} and {@link ClientConfig} for client methods and + * configuration options. + * + * @module {Firestore} @google-cloud/firestore + * @alias nodejs-firestore + * + * @example Install the client library with npm: + * ``` + * npm install --save @google-cloud/firestore + * + * ``` + * @example Import the client library + * ``` + * var Firestore = require('@google-cloud/firestore'); + * + * ``` + * @example Create a client that uses Application Default Credentials (ADC): + * ``` + * var firestore = new Firestore(); + * + * ``` + * @example Create a client with explicit credentials: + * ``` + * var firestore = new Firestore({ projectId: + * 'your-project-id', keyFilename: '/path/to/keyfile.json' + * }); + * + * ``` + * @example + * region_tag:firestore_quickstart + * Full quickstart example: + */ +// tslint:disable-next-line:no-default-export +export default Firestore; + +// Horrible hack to ensure backwards compatibility with <= 17.0, which allows +// users to call the default constructor via +// `const Fs = require(`@google-cloud/firestore`); new Fs()`; +const existingExports = module.exports; +module.exports = Firestore; +module.exports = Object.assign(module.exports, existingExports); + +/** + * {@link v1beta1} factory function. + * + * @private + * @internal + * @name Firestore.v1beta1 + * @type {function} + */ +Object.defineProperty(module.exports, 'v1beta1', { + // The v1beta1 module is very large. To avoid pulling it in from static + // scope, we lazy-load the module. + get: () => require('./v1beta1'), +}); + +/** + * {@link v1} factory function. + * + * @private + * @internal + * @name Firestore.v1 + * @type {function} + */ +Object.defineProperty(module.exports, 'v1', { + // The v1 module is very large. To avoid pulling it in from static + // scope, we lazy-load the module. + get: () => require('./v1'), +}); + +/** + * {@link Status} factory function. + * + * @private + * @internal + * @name Firestore.GrpcStatus + * @type {function} + */ +Object.defineProperty(module.exports, 'GrpcStatus', { + // The gax module is very large. To avoid pulling it in from static + // scope, we lazy-load the module. + get: () => require('google-gax').Status, +}); diff --git a/handwritten/firestore/dev/src/logger.ts b/handwritten/firestore/dev/src/logger.ts new file mode 100644 index 00000000000..50acc8f455f --- /dev/null +++ b/handwritten/firestore/dev/src/logger.ts @@ -0,0 +1,71 @@ +/*! + * Copyright 2018 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as util from 'util'; + +import {validateFunction} from './validate'; + +/*! The Firestore library version */ +let libVersion: string; + +/*! The external function used to emit logs. */ +let logFunction: ((msg: string) => void) | null = null; + +/** + * Log function to use for debug output. By default, we don't perform any + * logging. + * + * @private + * @internal + */ +export function logger( + methodName: string, + requestTag: string | null, + logMessage: string, + ...additionalArgs: unknown[] +): void { + requestTag = requestTag || '#####'; + + if (logFunction) { + const formattedMessage = util.format(logMessage, ...additionalArgs); + const time = new Date().toISOString(); + logFunction( + `Firestore (${libVersion}) ${time} ${requestTag} [${methodName}]: ` + + formattedMessage, + ); + } +} + +/** + * Sets or disables the log function for all active Firestore instances. + * + * @param logger A log function that takes a message (such as `console.log`) or + * `null` to turn off logging. + */ +export function setLogFunction(logger: ((msg: string) => void) | null): void { + if (logger !== null) validateFunction('logger', logger); + logFunction = logger; +} + +/** + * Sets the library version to be used in log messages. + * + * @private + * @internal + */ +export function setLibVersion(version: string): void { + libVersion = version; +} diff --git a/handwritten/firestore/dev/src/map-type.ts b/handwritten/firestore/dev/src/map-type.ts new file mode 100644 index 00000000000..f876220714c --- /dev/null +++ b/handwritten/firestore/dev/src/map-type.ts @@ -0,0 +1,19 @@ +/*! + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const RESERVED_MAP_KEY = '__type__'; +export const RESERVED_MAP_KEY_VECTOR_VALUE = '__vector__'; +export const VECTOR_MAP_VECTORS_KEY = 'value'; diff --git a/handwritten/firestore/dev/src/order.ts b/handwritten/firestore/dev/src/order.ts new file mode 100644 index 00000000000..cca7d744cd8 --- /dev/null +++ b/handwritten/firestore/dev/src/order.ts @@ -0,0 +1,368 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {google} from '../protos/firestore_v1_proto_api'; +import {detectValueType} from './convert'; +import {QualifiedResourcePath} from './path'; +import {ApiMapValue} from './types'; + +import api = google.firestore.v1; + +/*! + * The type order as defined by the backend. + */ +enum TypeOrder { + NULL = 0, + BOOLEAN = 1, + NUMBER = 2, + TIMESTAMP = 3, + STRING = 4, + BLOB = 5, + REF = 6, + GEO_POINT = 7, + ARRAY = 8, + VECTOR = 9, + OBJECT = 10, +} + +/*! + * @private + * @internal + */ +function typeOrder(val: api.IValue): TypeOrder { + const valueType = detectValueType(val); + + switch (valueType) { + case 'nullValue': + return TypeOrder.NULL; + case 'integerValue': + return TypeOrder.NUMBER; + case 'doubleValue': + return TypeOrder.NUMBER; + case 'stringValue': + return TypeOrder.STRING; + case 'booleanValue': + return TypeOrder.BOOLEAN; + case 'arrayValue': + return TypeOrder.ARRAY; + case 'timestampValue': + return TypeOrder.TIMESTAMP; + case 'geoPointValue': + return TypeOrder.GEO_POINT; + case 'bytesValue': + return TypeOrder.BLOB; + case 'referenceValue': + return TypeOrder.REF; + case 'mapValue': + return TypeOrder.OBJECT; + case 'vectorValue': + return TypeOrder.VECTOR; + default: + throw new Error('Unexpected value type: ' + valueType); + } +} + +/*! + * @private + * @internal + */ +export function primitiveComparator( + left: string | boolean | number, + right: string | boolean | number, +): number { + if (left < right) { + return -1; + } + if (left > right) { + return 1; + } + return 0; +} + +/*! + * Utility function to compare doubles (using Firestore semantics for NaN). + * @private + * @internal + */ +function compareNumbers(left: number, right: number): number { + if (left < right) { + return -1; + } + if (left > right) { + return 1; + } + if (left === right) { + return 0; + } + // one or both are NaN. + if (isNaN(left)) { + return isNaN(right) ? 0 : -1; + } + return 1; +} + +/*! + * @private + * @internal + */ +function compareNumberProtos(left: api.IValue, right: api.IValue): number { + let leftValue, rightValue; + if (left.integerValue !== undefined) { + leftValue = Number(left.integerValue!); + } else { + leftValue = Number(left.doubleValue!); + } + if (right.integerValue !== undefined) { + rightValue = Number(right.integerValue); + } else { + rightValue = Number(right.doubleValue!); + } + return compareNumbers(leftValue, rightValue); +} + +/*! + * @private + * @internal + */ +function compareTimestamps( + left: google.protobuf.ITimestamp, + right: google.protobuf.ITimestamp, +): number { + const seconds = primitiveComparator(left.seconds || 0, right.seconds || 0); + if (seconds !== 0) { + return seconds; + } + return primitiveComparator(left.nanos || 0, right.nanos || 0); +} + +/*! + * @private + * @internal + */ +function compareBlobs(left: Uint8Array, right: Uint8Array): number { + if (!(left instanceof Buffer) || !(right instanceof Buffer)) { + throw new Error('Blobs can only be compared if they are Buffers.'); + } + return Buffer.compare(left, right); +} + +/*! + * @private + * @internal + */ +function compareReferenceProtos(left: api.IValue, right: api.IValue): number { + const leftPath = QualifiedResourcePath.fromSlashSeparatedString( + left.referenceValue!, + ); + const rightPath = QualifiedResourcePath.fromSlashSeparatedString( + right.referenceValue!, + ); + return leftPath.compareTo(rightPath); +} + +/*! + * @private + * @internal + */ +function compareGeoPoints( + left: google.type.ILatLng, + right: google.type.ILatLng, +): number { + return ( + primitiveComparator(left.latitude || 0, right.latitude || 0) || + primitiveComparator(left.longitude || 0, right.longitude || 0) + ); +} + +/*! + * @private + * @internal + */ +export function compareArrays(left: api.IValue[], right: api.IValue[]): number { + for (let i = 0; i < left.length && i < right.length; i++) { + const valueComparison = compare(left[i], right[i]); + if (valueComparison !== 0) { + return valueComparison; + } + } + // If all the values matched so far, just check the length. + return primitiveComparator(left.length, right.length); +} + +/*! + * @private + * @internal + */ +function compareObjects(left: ApiMapValue, right: ApiMapValue): number { + // This requires iterating over the keys in the object in order and doing a + // deep comparison. + const leftKeys = Object.keys(left); + const rightKeys = Object.keys(right); + leftKeys.sort(); + rightKeys.sort(); + for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) { + const keyComparison = compareUtf8Strings(leftKeys[i], rightKeys[i]); + if (keyComparison !== 0) { + return keyComparison; + } + const key = leftKeys[i]; + const valueComparison = compare(left[key], right[key]); + if (valueComparison !== 0) { + return valueComparison; + } + } + // If all the keys matched so far, just check the length. + return primitiveComparator(leftKeys.length, rightKeys.length); +} + +/*! + * @private + * @internal + */ +function compareVectors(left: ApiMapValue, right: ApiMapValue): number { + // The vector is a map, but only vector value is compared. + const leftArray = left?.['value']?.arrayValue?.values ?? []; + const rightArray = right?.['value']?.arrayValue?.values ?? []; + + const lengthCompare = primitiveComparator( + leftArray.length, + rightArray.length, + ); + if (lengthCompare !== 0) { + return lengthCompare; + } + + return compareArrays(leftArray, rightArray); +} + +/*! + * Compare strings in UTF-8 encoded byte order + * @private + * @internal + */ +export function compareUtf8Strings(left: string, right: string): number { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // + // After finding the first pair of differing characters, there are two cases: + // + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // + // An example of why Case 2 is required is comparing the following two Unicode code points: + // + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const length = Math.min(left.length, right.length); + for (let i = 0; i < length; i++) { + const leftChar = left.charAt(i); + const rightChar = right.charAt(i); + if (leftChar !== rightChar) { + return isSurrogate(leftChar) === isSurrogate(rightChar) + ? primitiveComparator(leftChar, rightChar) + : isSurrogate(leftChar) + ? 1 + : -1; + } + } + + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return primitiveComparator(left.length, right.length); +} + +const MIN_SURROGATE = 0xd800; +const MAX_SURROGATE = 0xdfff; + +function isSurrogate(s: string): boolean { + const c = s.charCodeAt(0); + return c >= MIN_SURROGATE && c <= MAX_SURROGATE; +} + +/*! + * @private + * @internal + */ +export function compare(left: api.IValue, right: api.IValue): number { + // First compare the types. + const leftType = typeOrder(left); + const rightType = typeOrder(right); + const typeComparison = primitiveComparator(leftType, rightType); + if (typeComparison !== 0) { + return typeComparison; + } + + // So they are the same type. + switch (leftType) { + case TypeOrder.NULL: + // Nulls are all equal. + return 0; + case TypeOrder.BOOLEAN: + return primitiveComparator(left.booleanValue!, right.booleanValue!); + case TypeOrder.STRING: + return compareUtf8Strings(left.stringValue!, right.stringValue!); + case TypeOrder.NUMBER: + return compareNumberProtos(left, right); + case TypeOrder.TIMESTAMP: + return compareTimestamps(left.timestampValue!, right.timestampValue!); + case TypeOrder.BLOB: + return compareBlobs(left.bytesValue!, right.bytesValue!); + case TypeOrder.REF: + return compareReferenceProtos(left, right); + case TypeOrder.GEO_POINT: + return compareGeoPoints(left.geoPointValue!, right.geoPointValue!); + case TypeOrder.ARRAY: + return compareArrays( + left.arrayValue!.values || [], + right.arrayValue!.values || [], + ); + case TypeOrder.OBJECT: + return compareObjects( + left.mapValue!.fields || {}, + right.mapValue!.fields || {}, + ); + case TypeOrder.VECTOR: + return compareVectors( + left.mapValue!.fields || {}, + right.mapValue!.fields || {}, + ); + default: + throw new Error(`Encountered unknown type order: ${leftType}`); + } +} diff --git a/handwritten/firestore/dev/src/path.ts b/handwritten/firestore/dev/src/path.ts new file mode 100644 index 00000000000..05446275e60 --- /dev/null +++ b/handwritten/firestore/dev/src/path.ts @@ -0,0 +1,886 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; + +import {google} from '../protos/firestore_v1_proto_api'; +import {compareUtf8Strings, primitiveComparator} from './order'; + +import {isObject} from './util'; +import { + customObjectMessage, + invalidArgumentMessage, + validateMinNumberOfArguments, + validateString, +} from './validate'; + +import api = google.firestore.v1; + +/*! + * The default database ID for this Firestore client. We do not yet expose the + * ability to use different databases. + */ +export const DEFAULT_DATABASE_ID = '(default)'; + +/*! + * A regular expression to verify an absolute Resource Path in Firestore. It + * extracts the project ID, the database name and the relative resource path + * if available. + * + * @type {RegExp} + */ +const RESOURCE_PATH_RE = + /^projects\/([^/]+)\/databases\/([^/]+)(?:\/documents(?:\/([^/]+(?:\/[^/]+)*))?)?$/; + +/*! + * A regular expression to verify whether a field name can be passed to the + * backend without escaping. + * + * @type {RegExp} + */ +const UNESCAPED_FIELD_NAME_RE = /^[_a-zA-Z][_a-zA-Z0-9]*$/; + +/*! + * A regular expression to verify field paths that are passed to the API as + * strings. Field paths that do not match this expression have to be provided + * as a [FieldPath]{@link FieldPath} object. + * + * @type {RegExp} + */ +const FIELD_PATH_RE = /^[^*~/[\]]+$/; + +/** + * An abstract class representing a Firestore path. + * + * Subclasses have to implement `split()` and `canonicalString()`. + * + * @private + * @internal + * @class + */ +abstract class Path { + /** + * Creates a new Path with the given segments. + * + * @private + * @internal + * @private + * @param segments Sequence of parts of a path. + */ + constructor(protected readonly segments: string[]) {} + + /** + * Returns the number of segments of this field path. + * + * @private + * @internal + */ + get size(): number { + return this.segments.length; + } + + abstract construct(segments: string[] | string): T; + abstract split(relativePath: string): string[]; + + /** + * Create a child path beneath the current level. + * + * @private + * @internal + * @param relativePath Relative path to append to the current path. + * @returns The new path. + */ + append(relativePath: Path | string): T { + if (relativePath instanceof Path) { + return this.construct(this.segments.concat(relativePath.segments)); + } + return this.construct(this.segments.concat(this.split(relativePath))); + } + + /** + * Returns the path of the parent node. + * + * @private + * @internal + * @returns The new path or null if we are already at the root. + */ + parent(): T | null { + if (this.segments.length === 0) { + return null; + } + + return this.construct(this.segments.slice(0, this.segments.length - 1)); + } + + /** + * Checks whether the current path is a prefix of the specified path. + * + * @private + * @internal + * @param other The path to check against. + * @returns 'true' iff the current path is a prefix match with 'other'. + */ + isPrefixOf(other: Path): boolean { + if (other.segments.length < this.segments.length) { + return false; + } + + for (let i = 0; i < this.segments.length; i++) { + if (this.segments[i] !== other.segments[i]) { + return false; + } + } + + return true; + } + + /** + * Compare the current path against another Path object. + * + * Compare the current path against another Path object. Paths are compared segment by segment, + * prioritizing numeric IDs (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + * + * @private + * @internal + * @param other The path to compare to. + * @returns -1 if current < other, 1 if current > other, 0 if equal + */ + compareTo(other: Path): number { + const len = Math.min(this.segments.length, other.segments.length); + for (let i = 0; i < len; i++) { + const comparison = this.compareSegments( + this.segments[i], + other.segments[i], + ); + if (comparison !== 0) { + return comparison; + } + } + return primitiveComparator(this.segments.length, other.segments.length); + } + + private compareSegments(lhs: string, rhs: string): number { + const isLhsNumeric = this.isNumericId(lhs); + const isRhsNumeric = this.isNumericId(rhs); + + if (isLhsNumeric && !isRhsNumeric) { + // Only lhs is numeric + return -1; + } else if (!isLhsNumeric && isRhsNumeric) { + // Only rhs is numeric + return 1; + } else if (isLhsNumeric && isRhsNumeric) { + // both numeric + return this.compareNumbers( + this.extractNumericId(lhs), + this.extractNumericId(rhs), + ); + } else { + // both non-numeric + return compareUtf8Strings(lhs, rhs); + } + } + + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + private isNumericId(segment: string): boolean { + return segment.startsWith('__id') && segment.endsWith('__'); + } + + // Extracts the long number from a numeric ID segment. + private extractNumericId(segment: string): bigint { + return BigInt(segment.substring(4, segment.length - 2)); + } + + private compareNumbers(lhs: bigint, rhs: bigint): number { + if (lhs < rhs) { + return -1; + } else if (lhs > rhs) { + return 1; + } else { + return 0; + } + } + + /** + * Returns a copy of the underlying segments. + * + * @private + * @internal + * @returns A copy of the segments that make up this path. + */ + toArray(): string[] { + return this.segments.slice(); + } + + /** + * Pops the last segment from this `Path` and returns a newly constructed + * `Path`. + * + * @private + * @internal + * @returns The newly created Path. + */ + popLast(): T { + return this.construct(this.segments.slice(0, -1)); + } + + /** + * Returns the last segment from this `Path`; + * + * @private + * @internal + * @returns The last segment of this Path. + */ + lastSegment(): string { + return this.get(this.size - 1); + } + + /** + * Returns the path segment at the specified index. + * @param index + */ + get(index: number): string { + return this.segments[index]; + } + + /** + * Returns `true` if this path is the immediate + * parent of the given `potentialChild` path. + * @param potentialChild + */ + isImmediateParentOf(potentialChild: this): boolean { + if (this.size + 1 !== potentialChild.size) { + return false; + } + + for (let i = 0; i < this.size; i++) { + if (this.get(i) !== potentialChild.get(i)) { + return false; + } + } + + return true; + } + + /** + * Returns true if this `Path` is equal to the provided value. + * + * @private + * @internal + * @param other The value to compare against. + * @returns true if this `Path` is equal to the provided value. + */ + isEqual(other: Path): boolean { + return this === other || this.compareTo(other) === 0; + } +} + +/** + * A slash-separated path for navigating resources within the current Firestore + * instance. + * + * @private + * @internal + */ +export class ResourcePath extends Path { + /** + * A default instance pointing to the root collection. + * @private + * @internal + */ + static EMPTY = new ResourcePath(); + + /** + * Constructs a ResourcePath. + * + * @private + * @internal + * @param segments Sequence of names of the parts of the path. + */ + constructor(...segments: string[]) { + super(segments); + } + + /** + * Indicates whether this path points to a document. + * @private + * @internal + */ + get isDocument(): boolean { + return this.segments.length > 0 && this.segments.length % 2 === 0; + } + + /** + * Indicates whether this path points to a collection. + * @private + * @internal + */ + get isCollection(): boolean { + return this.segments.length % 2 === 1; + } + + /** + * The last component of the path. + * @private + * @internal + */ + get id(): string | null { + if (this.segments.length > 0) { + return this.segments[this.segments.length - 1]; + } + return null; + } + + /** + * Returns the location of this path relative to the root of the project's + * database. + * @private + * @internal + */ + get relativeName(): string { + return this.segments.join('/'); + } + + /** + * Constructs a new instance of ResourcePath. + * + * @private + * @internal + * @param segments Sequence of parts of the path. + * @returns The newly created ResourcePath. + */ + construct(segments: string[]): ResourcePath { + return new ResourcePath(...segments); + } + + /** + * Splits a string into path segments, using slashes as separators. + * + * @private + * @internal + * @param relativePath The path to split. + * @returns The split path segments. + */ + split(relativePath: string): string[] { + // We may have an empty segment at the beginning or end if they had a + // leading or trailing slash (which we allow). + return relativePath.split('/').filter(segment => segment.length > 0); + } + + /** + * Converts this path to a fully qualified ResourcePath. + * + * @private + * @internal + * @param projectId The project ID of the current Firestore project. + * @returns A fully-qualified resource path pointing to the same element. + */ + toQualifiedResourcePath( + projectId: string, + databaseId: string, + ): QualifiedResourcePath { + return new QualifiedResourcePath(projectId, databaseId, ...this.segments); + } +} + +/** + * A slash-separated path that includes a project and database ID for referring + * to resources in any Firestore project. + * + * @private + * @internal + */ +export class QualifiedResourcePath extends ResourcePath { + /** + * The project ID of this path. + */ + readonly projectId: string; + + /** + * The database ID of this path. + */ + readonly databaseId: string; + + /** + * Constructs a Firestore Resource Path. + * + * @private + * @internal + * @param projectId The Firestore project id. + * @param databaseId The Firestore database id. + * @param segments Sequence of names of the parts of the path. + */ + constructor(projectId: string, databaseId: string, ...segments: string[]) { + super(...segments); + + this.projectId = projectId; + this.databaseId = databaseId; + } + + /** + * String representation of the path relative to the database root. + * @private + * @internal + */ + get relativeName(): string { + return this.segments.join('/'); + } + + /** + * Creates a resource path from an absolute Firestore path. + * + * @private + * @internal + * @param absolutePath A string representation of a Resource Path. + * @returns The new ResourcePath. + */ + static fromSlashSeparatedString(absolutePath: string): QualifiedResourcePath { + const elements = RESOURCE_PATH_RE.exec(absolutePath); + + if (elements) { + const project = elements[1]; + const database = elements[2]; + const root = new QualifiedResourcePath(project, database); + + if (!elements[3]) { + return root; + } else { + return root.append(elements[3]); + } + } + + throw new Error(`Resource name '${absolutePath}' is not valid.`); + } + + /** + * Create a child path beneath the current level. + * + * @private + * @internal + * @param relativePath Relative path to append to the current path. + * @returns The new path. + */ + append(relativePath: ResourcePath | string): QualifiedResourcePath { + // `super.append()` calls `QualifiedResourcePath.construct()` when invoked + // from here and returns a QualifiedResourcePath. + return super.append(relativePath) as QualifiedResourcePath; + } + + /** + * Create a child path beneath the current level. + * + * @private + * @internal + * @returns The new path. + */ + parent(): QualifiedResourcePath | null { + return super.parent() as QualifiedResourcePath | null; + } + + /** + * String representation of a ResourcePath as expected by the API. + * + * @private + * @internal + * @returns The representation as expected by the API. + */ + get formattedName(): string { + const components = [ + 'projects', + this.projectId, + 'databases', + this.databaseId, + 'documents', + ...this.segments, + ]; + return components.join('/'); + } + + /** + * Constructs a new instance of ResourcePath. We need this instead of using + * the normal constructor because polymorphic 'this' doesn't work on static + * methods. + * + * @private + * @internal + * @param segments Sequence of names of the parts of the path. + * @returns The newly created QualifiedResourcePath. + */ + construct(segments: string[]): QualifiedResourcePath { + return new QualifiedResourcePath( + this.projectId, + this.databaseId, + ...segments, + ); + } + + /** + * Convenience method to match the ResourcePath API. This method always + * returns the current instance. + * + * @private + * @internal + */ + toQualifiedResourcePath(): QualifiedResourcePath { + return this; + } + + /** + * Compare the current path against another ResourcePath object. + * + * @private + * @internal + * @param other The path to compare to. + * @returns -1 if current < other, 1 if current > other, 0 if equal + */ + compareTo(other: ResourcePath): number { + if (other instanceof QualifiedResourcePath) { + if (this.projectId < other.projectId) { + return -1; + } + if (this.projectId > other.projectId) { + return 1; + } + + if (this.databaseId < other.databaseId) { + return -1; + } + if (this.databaseId > other.databaseId) { + return 1; + } + } + + return super.compareTo(other); + } + + /** + * Converts this ResourcePath to the Firestore Proto representation. + * @private + * @internal + */ + toProto(): api.IValue { + return { + referenceValue: this.formattedName, + }; + } +} + +/** + * Validates that the given string can be used as a relative or absolute + * resource path. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param resourcePath The path to validate. + * @throws if the string can't be used as a resource path. + */ +export function validateResourcePath( + arg: string | number, + resourcePath: string, +): void { + if (typeof resourcePath !== 'string' || resourcePath === '') { + throw new Error( + `${invalidArgumentMessage( + arg, + 'resource path', + )} Path must be a non-empty string.`, + ); + } + + if (resourcePath.indexOf('//') >= 0) { + throw new Error( + `${invalidArgumentMessage( + arg, + 'resource path', + )} Paths must not contain //.`, + ); + } +} + +/** + * A dot-separated path for navigating sub-objects (e.g. nested maps) within a document. + * + * @class + */ +export class FieldPath extends Path implements firestore.FieldPath { + /** + * A special sentinel value to refer to the ID of a document. + * + * @private + * @internal + */ + private static _DOCUMENT_ID = new FieldPath('__name__'); + + /** + * @private + * @internal + * Defines the minimum number of segments allowed in a FieldPath + */ + get _minNumSegments(): number { + return 1; + } + + /** + * Constructs a Firestore Field Path. + * + * @param {...string} segments Sequence of field names that form this path. + * + * @example + * ``` + * let query = firestore.collection('col'); + * let fieldPath = new FieldPath('f.o.o', 'bar'); + * + * query.where(fieldPath, '==', 42).get().then(snapshot => { + * snapshot.forEach(document => { + * console.log(`Document contains {'f.o.o' : {'bar' : 42}}`); + * }); + * }); + * ``` + */ + constructor(...segments: string[]) { + if (Array.isArray(segments[0])) { + throw new Error( + 'The FieldPath constructor no longer supports an array as its first argument. ' + + 'Please unpack your array and call FieldPath() with individual arguments.', + ); + } + + for (let i = 0; i < segments.length; ++i) { + validateString(i, segments[i]); + if (segments[i].length === 0) { + throw new Error(`Element at index ${i} should not be an empty string.`); + } + } + + super(segments); + + validateMinNumberOfArguments('FieldPath', segments, this._minNumSegments); + } + + /** + * A special FieldPath value to refer to the ID of a document. It can be used + * in queries to sort or filter by the document ID. + * + * @returns {FieldPath} + */ + static documentId(): FieldPath { + return FieldPath._DOCUMENT_ID; + } + + /** + * Create an empty FieldPath. + * @private + * @internal + * + * @returns {FieldPath} + */ + static _emptyPath(): FieldPath { + const result = new FieldPath('empty'); + result.segments.pop(); + return result; + } + + /** + * Turns a field path argument into a [FieldPath]{@link FieldPath}. + * Supports FieldPaths as input (which are passed through) and dot-separated + * strings. + * + * @private + * @internal + * @param {string|FieldPath} fieldPath The FieldPath to create. + * @returns {FieldPath} A field path representation. + */ + static fromArgument(fieldPath: string | firestore.FieldPath): FieldPath { + // validateFieldPath() is used in all public API entry points to validate + // that fromArgument() is only called with a Field Path or a string. + return fieldPath instanceof FieldPath + ? fieldPath + : new FieldPath(...(fieldPath as string).split('.')); + } + + /** + * String representation of a FieldPath as expected by the API. + * + * @private + * @internal + * @override + * @returns {string} The representation as expected by the API. + */ + get formattedName(): string { + return this.segments + .map(str => { + return UNESCAPED_FIELD_NAME_RE.test(str) + ? str + : '`' + str.replace(/\\/g, '\\\\').replace(/`/g, '\\`') + '`'; + }) + .join('.'); + } + + /** + * Returns a string representation of this path. + * + * @private + * @internal + * @returns A string representing this path. + */ + toString(): string { + return this.formattedName; + } + + /** + * Splits a string into path segments, using dots as separators. + * + * @private + * @internal + * @override + * @param {string} fieldPath The path to split. + * @returns {Array.} - The split path segments. + */ + split(fieldPath: string): string[] { + return fieldPath.split('.'); + } + + /** + * Constructs a new instance of FieldPath. We need this instead of using + * the normal constructor because polymorphic 'this' doesn't work on static + * methods. + * + * @private + * @internal + * @override + * @param segments Sequence of field names. + * @returns The newly created FieldPath. + */ + construct(segments: string[]): FieldPath { + return new FieldPath(...segments); + } + + /** + * Returns true if this `FieldPath` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @returns {boolean} true if this `FieldPath` is equal to the provided value. + */ + isEqual(other: FieldPath): boolean { + return super.isEqual(other); + } +} +/** + * A dot-separated path for navigating ObjectValues. + * This type is like its parent, FieldPath, except + * it allows for zero length segments. + * + * @private + * @internal + * @class + */ +export class ObjectValueFieldPath extends FieldPath { + /** + * Zero length field paths are allowed in object value traverse. + */ + get _minNumSegments(): number { + return 0; + } + + constructor(...segments: string[]) { + super(...segments); + } + + static fromDotNotation(path: string): ObjectValueFieldPath { + return new ObjectValueFieldPath(...path.split('.')); + } + + /** + * Constructs a new instance of FieldPath. We need this instead of using + * the normal constructor because polymorphic 'this' doesn't work on static + * methods. + * + * @private + * @internal + * @override + * @param segments Sequence of field names. + * @returns The newly created FieldPath. + */ + construct(segments: string[]): FieldPath { + return new ObjectValueFieldPath(...segments); + } +} + +/** + * Validates that the provided value can be used as a field path argument. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param fieldPath The value to verify. + * @throws if the string can't be used as a field path. + */ +export function validateFieldPath( + arg: string | number, + fieldPath: unknown, +): asserts fieldPath is string | FieldPath { + if (fieldPath instanceof FieldPath) { + return; + } + + if (fieldPath === undefined) { + throw new Error( + invalidArgumentMessage(arg, 'field path') + + ' The path cannot be omitted.', + ); + } + + if (isObject(fieldPath) && fieldPath.constructor.name === 'FieldPath') { + throw new Error(customObjectMessage(arg, fieldPath)); + } + + if (typeof fieldPath !== 'string') { + throw new Error( + `${invalidArgumentMessage( + arg, + 'field path', + )} Paths can only be specified as strings or via a FieldPath object.`, + ); + } + + if (fieldPath.indexOf('..') >= 0) { + throw new Error( + `${invalidArgumentMessage( + arg, + 'field path', + )} Paths must not contain ".." in them.`, + ); + } + + if (fieldPath.startsWith('.') || fieldPath.endsWith('.')) { + throw new Error( + `${invalidArgumentMessage( + arg, + 'field path', + )} Paths must not start or end with ".".`, + ); + } + + if (!FIELD_PATH_RE.test(fieldPath)) { + throw new Error(`${invalidArgumentMessage( + arg, + 'field path', + )} Paths can't be empty and must not contain + "*~/[]".`); + } +} diff --git a/handwritten/firestore/dev/src/pipelines/expression.ts b/handwritten/firestore/dev/src/pipelines/expression.ts new file mode 100644 index 00000000000..01ee1e4fc49 --- /dev/null +++ b/handwritten/firestore/dev/src/pipelines/expression.ts @@ -0,0 +1,8672 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; + +import type * as firestore from '@google-cloud/firestore'; + +import {VectorValue} from '../field-value'; +import {FieldPath} from '../path'; +import { + fieldOrExpression, + isFirestoreValue, + isString, + valueToDefaultExpr, + vectorToExpr, +} from './pipeline-util'; +import {HasUserData, Serializer, validateUserInput} from '../serializer'; +import {cast} from '../util'; + +/** + * @beta + * + * An enumeration of the different types generated by the Firestore backend. + * + *
    + *
  • Numerics evaluate directly to backend representation (`int64` or `float64`), not JS `number`.
  • + *
  • JavaScript `Date` and firestore `Timestamp` objects strictly evaluate to `'timestamp'`.
  • + *
  • Advanced configurations parsing backend types (such as `decimal128`, `max_key` or `min_key` from BSON) are also incorporated in this union string type. Note that `decimal128` is a backend-only numeric type that the JavaScript SDK cannot create natively, but can be evaluated in pipelines.
  • + *
+ */ +export type Type = + | 'null' + | 'array' + | 'boolean' + | 'bytes' + | 'timestamp' + | 'geo_point' + | 'number' + | 'int32' + | 'int64' + | 'float64' + | 'decimal128' + | 'map' + | 'reference' + | 'string' + | 'vector' + | 'max_key' + | 'min_key' + | 'object_id' + | 'regex' + | 'request_timestamp'; + +/** + * @beta + * Represents an expression that can be evaluated to a value within the execution of a `Pipeline`. + * + * Expressions are the building blocks for creating complex queries and transformations in + * Firestore pipelines. They can represent: + * + * - **Field references:** Access values from document fields. + * - **Literals:** Represent constant values (strings, numbers, booleans). + * - **Function calls:** Apply functions to one or more expressions. + * + * The `Expression` class provides a fluent API for building expressions. You can chain together + * method calls to create complex expressions. + */ +export abstract class Expression + implements firestore.Pipelines.Expression, HasUserData +{ + abstract expressionType: firestore.Pipelines.ExpressionType; + + /** + * @beta + * @internal + * @private + * Indicates if this expression was created from a literal value passed + * by the caller. + */ + _createdFromLiteral = false; + + /** + * @beta + * @private + * @internal + */ + abstract _toProto(serializer: Serializer): api.IValue; + _protoValueType = 'ProtoValue' as const; + + /** + * @beta + * @private + * @internal + */ + abstract _validateUserData(ignoreUndefinedProperties: boolean): void; + + /** + * @beta + * Creates an expression that adds this expression to another expression. + * + * @example + * ```typescript + * // Add the value of the 'quantity' field and the 'reserve' field. + * field("quantity").add(field("reserve")); + * ``` + * + * @param second The expression or literal to add to this expression. + * @param others Optional additional expressions or literals to add to this expression. + * @returns A new `Expression` representing the addition operation. + */ + add( + second: firestore.Pipelines.Expression | unknown, + ...others: Array + ): FunctionExpression { + const values = [second, ...others]; + return new FunctionExpression('add', [ + this, + ...values.map(value => valueToDefaultExpr(value)), + ]); + } + + /** + * @beta + * Wraps the expression in a [BooleanExpression]. + * + * @returns A `BooleanExpression` representing the same expression. + */ + asBoolean(): BooleanExpression { + if (this instanceof BooleanExpression) { + return this; + } else if (this instanceof Constant) { + return new BooleanConstant(this); + } else if (this instanceof Field) { + return new BooleanField(this); + } else if (this instanceof FunctionExpression) { + return new BooleanFunctionExpression(this); + } else { + throw new Error( + `Conversion of type ${typeof this} to BooleanExpression not supported.`, + ); + } + } + + /** + * @beta + * Creates an expression that subtracts another expression from this expression. + * + * @example + * ```typescript + * // Subtract the 'discount' field from the 'price' field + * field("price").subtract(field("discount")); + * ``` + * + * @param subtrahend The expression to subtract from this expression. + * @returns A new `Expression` representing the subtraction operation. + */ + subtract(subtrahend: firestore.Pipelines.Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that subtracts a constant value from this expression. + * + * @example + * ```typescript + * // Subtract 20 from the value of the 'total' field + * field("total").subtract(20); + * ``` + * + * @param subtrahend The constant value to subtract. + * @returns A new `Expression` representing the subtraction operation. + */ + subtract(subtrahend: number): FunctionExpression; + subtract( + subtrahend: number | firestore.Pipelines.Expression, + ): FunctionExpression { + return new FunctionExpression('subtract', [ + this, + valueToDefaultExpr(subtrahend), + ]); + } + + /** + * @beta + * Creates an expression that multiplies this expression by another expression. + * + * @example + * ```typescript + * // Multiply the 'quantity' field by the 'price' field + * field("quantity").multiply(field("price")); + * ``` + * + * @param second The second expression or literal to multiply by. + * @param others Optional additional expressions or literals to multiply by. + * @returns A new `Expression` representing the multiplication operation. + */ + multiply( + second: Expression | number, + ...others: Array + ): FunctionExpression { + return new FunctionExpression('multiply', [ + this, + valueToDefaultExpr(second), + ...others.map(value => valueToDefaultExpr(value)), + ]); + } + + /** + * @beta + * Creates an expression that divides this expression by another expression. + * + * @example + * ```typescript + * // Divide the 'total' field by the 'count' field + * field("total").divide(field("count")); + * ``` + * + * @param divisor The expression to divide by. + * @returns A new `Expression` representing the division operation. + */ + divide(divisor: Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that divides this expression by a constant value. + * + * @example + * ```typescript + * // Divide the 'value' field by 10 + * field("value").divide(10); + * ``` + * + * @param divisor The constant value to divide by. + * @returns A new `Expression` representing the division operation. + */ + divide(divisor: number): FunctionExpression; + divide(divisor: number | Expression): FunctionExpression { + return new FunctionExpression('divide', [ + this, + valueToDefaultExpr(divisor), + ]); + } + + /** + * @beta + * Creates an expression that calculates the modulo (remainder) of dividing this expression by another expression. + * + * @example + * ```typescript + * // Calculate the remainder of dividing the 'value' field by the 'divisor' field + * field("value").mod(field("divisor")); + * ``` + * + * @param expression The expression to divide by. + * @returns A new `Expression` representing the modulo operation. + */ + mod(expression: Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that calculates the modulo (remainder) of dividing this expression by a constant value. + * + * @example + * ```typescript + * // Calculate the remainder of dividing the 'value' field by 10 + * field("value").mod(10); + * ``` + * + * @param value The constant value to divide by. + * @returns A new `Expression` representing the modulo operation. + */ + mod(value: number): FunctionExpression; + mod(other: number | Expression): FunctionExpression { + return new FunctionExpression('mod', [this, valueToDefaultExpr(other)]); + } + + /** + * @beta + * Creates an expression that checks if this expression is equal to another expression. + * + * @example + * ```typescript + * // Check if the 'age' field is equal to 21 + * field("age").equal(21); + * ``` + * + * @param expression The expression to compare for equality. + * @returns A new `Expression` representing the equality comparison. + */ + equal(expression: Expression): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if this expression is equal to a constant value. + * + * @example + * ```typescript + * // Check if the 'city' field is equal to "London" + * field("city").equal("London"); + * ``` + * + * @param value The constant value to compare for equality. + * @returns A new `Expression` representing the equality comparison. + */ + equal(value: unknown): BooleanExpression; + equal(other: unknown): BooleanExpression { + return new FunctionExpression('equal', [ + this, + valueToDefaultExpr(other), + ]).asBoolean(); + } + + /** + * @beta + * Creates an expression that checks if this expression is not equal to another expression. + * + * @example + * ```typescript + * // Check if the 'status' field is not equal to "completed" + * field("status").notEqual("completed"); + * ``` + * + * @param expression The expression to compare for inequality. + * @returns A new `Expression` representing the inequality comparison. + */ + notEqual(expression: Expression): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if this expression is not equal to a constant value. + * + * @example + * ```typescript + * // Check if the 'country' field is not equal to "USA" + * field("country").notEqual("USA"); + * ``` + * + * @param value The constant value to compare for inequality. + * @returns A new `Expression` representing the inequality comparison. + */ + notEqual(value: unknown): BooleanExpression; + notEqual(other: unknown): BooleanExpression { + return new FunctionExpression('not_equal', [ + this, + valueToDefaultExpr(other), + ]).asBoolean(); + } + + /** + * @beta + * Creates an expression that checks if this expression is less than another expression. + * + * @example + * ```typescript + * // Check if the 'age' field is less than 'limit' + * field("age").lessThan(field('limit')); + * ``` + * + * @param experession The expression to compare for less than. + * @returns A new `Expression` representing the less than comparison. + */ + lessThan(experession: Expression): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if this expression is less than a constant value. + * + * @example + * ```typescript + * // Check if the 'price' field is less than 50 + * field("price").lessThan(50); + * ``` + * + * @param value The constant value to compare for less than. + * @returns A new `Expression` representing the less than comparison. + */ + lessThan(value: unknown): BooleanExpression; + lessThan(other: unknown): BooleanExpression { + return new FunctionExpression('less_than', [ + this, + valueToDefaultExpr(other), + ]).asBoolean(); + } + + /** + * @beta + * Creates an expression that checks if this expression is less than or equal to another + * expression. + * + * @example + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * field("quantity").lessThanOrEqual(constant(20)); + * ``` + * + * @param expression The expression to compare for less than or equal to. + * @returns A new `Expression` representing the less than or equal to comparison. + */ + lessThanOrEqual(expression: Expression): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if this expression is less than or equal to a constant value. + * + * @example + * ```typescript + * // Check if the 'score' field is less than or equal to 70 + * field("score").lessThanOrEqual(70); + * ``` + * + * @param value The constant value to compare for less than or equal to. + * @returns A new `Expression` representing the less than or equal to comparison. + */ + lessThanOrEqual(value: unknown): BooleanExpression; + lessThanOrEqual(other: unknown): BooleanExpression { + return new FunctionExpression('less_than_or_equal', [ + this, + valueToDefaultExpr(other), + ]).asBoolean(); + } + + /** + * @beta + * Creates an expression that checks if this expression is greater than another expression. + * + * @example + * ```typescript + * // Check if the 'age' field is greater than the 'limit' field + * field("age").greaterThan(field("limit")); + * ``` + * + * @param expression The expression to compare for greater than. + * @returns A new `Expression` representing the greater than comparison. + */ + greaterThan(expression: Expression): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if this expression is greater than a constant value. + * + * @example + * ```typescript + * // Check if the 'price' field is greater than 100 + * field("price").greaterThan(100); + * ``` + * + * @param value The constant value to compare for greater than. + * @returns A new `Expression` representing the greater than comparison. + */ + greaterThan(value: unknown): BooleanExpression; + greaterThan(other: unknown): BooleanExpression { + return new FunctionExpression('greater_than', [ + this, + valueToDefaultExpr(other), + ]).asBoolean(); + } + + /** + * @beta + * Creates an expression that checks if this expression is greater than or equal to another + * expression. + * + * @example + * ```typescript + * // Check if the 'quantity' field is greater than or equal to field 'requirement' plus 1 + * field("quantity").greaterThanOrEqual(field('requirement').add(1)); + * ``` + * + * @param expression The expression to compare for greater than or equal to. + * @returns A new `Expression` representing the greater than or equal to comparison. + */ + greaterThanOrEqual(expression: Expression): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if this expression is greater than or equal to a constant + * value. + * + * @example + * ```typescript + * // Check if the 'score' field is greater than or equal to 80 + * field("score").greaterThanOrEqual(80); + * ``` + * + * @param value The constant value to compare for greater than or equal to. + * @returns A new `Expression` representing the greater than or equal to comparison. + */ + greaterThanOrEqual(value: unknown): BooleanExpression; + greaterThanOrEqual(other: unknown): BooleanExpression { + return new FunctionExpression('greater_than_or_equal', [ + this, + valueToDefaultExpr(other), + ]).asBoolean(); + } + + /** + * @beta + * Creates an expression that concatenates an array expression with one or more other arrays. + * + * @example + * ```typescript + * // Combine the 'items' array with another array field. + * field("items").arrayConcat(field("otherItems")); + * ``` + * @param secondArray Second array expression or array literal to concatenate. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @returns A new `Expr` representing the concatenated array. + */ + arrayConcat( + secondArray: Expression | unknown[], + ...otherArrays: Array + ): FunctionExpression { + const elements = [secondArray, ...otherArrays]; + const exprValues = elements.map(value => valueToDefaultExpr(value)); + return new FunctionExpression('array_concat', [this, ...exprValues]); + } + + /** + * @beta + * Creates an expression that checks if an array contains a specific element. + * + * @example + * ```typescript + * // Check if the 'sizes' array contains the value from the 'selectedSize' field + * field("sizes").arrayContains(field("selectedSize")); + * ``` + * + * @param expression The element to search for in the array. + * @returns A new `Expression` representing the 'array_contains' comparison. + */ + arrayContains(expression: Expression): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if an array contains a specific value. + * + * @example + * ```typescript + * // Check if the 'colors' array contains "red" + * field("colors").arrayContains("red"); + * ``` + * + * @param value The element to search for in the array. + * @returns A new `Expression` representing the 'array_contains' comparison. + */ + arrayContains(value: unknown): BooleanExpression; + arrayContains(element: unknown): BooleanExpression { + return new FunctionExpression('array_contains', [ + this, + valueToDefaultExpr(element), + ]).asBoolean(); + } + + /** + * @beta + * Creates an expression that checks if an array contains all the specified elements. + * + * @example + * ```typescript + * // Check if the 'tags' array contains both the value in field "tag1" and the literal value "tag2" + * field("tags").arrayContainsAll([field("tag1"), "tag2"]); + * ``` + * + * @param values The elements to check for in the array. + * @returns A new `Expression` representing the 'array_contains_all' comparison. + */ + arrayContainsAll(values: Array): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if an array contains all the specified elements. + * + * @example + * ```typescript + * // Check if the 'tags' array contains both of the values from field "tag1" and the literal value "tag2" + * field("tags").arrayContainsAll(array([field("tag1"), "tag2"])); + * ``` + * + * @param arrayExpression The elements to check for in the array. + * @returns A new `Expression` representing the 'array_contains_all' comparison. + */ + arrayContainsAll(arrayExpression: Expression): BooleanExpression; + arrayContainsAll(values: unknown[] | Expression): BooleanExpression { + const normalizedExpr = Array.isArray(values) + ? new ListOfExprs(values.map(valueToDefaultExpr)) + : cast(values); + return new FunctionExpression('array_contains_all', [ + this, + normalizedExpr, + ]).asBoolean(); + } + + /** + * @beta + * Creates an expression that checks if an array contains any of the specified elements. + * + * @example + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "cate2" + * field("categories").arrayContainsAny([field("cate1"), field("cate2")]); + * ``` + * + * @param values The elements to check for in the array. + * @returns A new `Expression` representing the 'array_contains_any' comparison. + */ + arrayContainsAny(values: Array): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if an array contains any of the specified elements. + * + * @example + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * field("groups").arrayContainsAny(array([field("userGroup"), "guest"])); + * ``` + * + * @param arrayExpression The elements to check for in the array. + * @returns A new `Expression` representing the 'array_contains_any' comparison. + */ + arrayContainsAny(arrayExpression: Expression): BooleanExpression; + arrayContainsAny( + values: Array | Expression, + ): BooleanExpression { + const normalizedExpr = Array.isArray(values) + ? new ListOfExprs(values.map(valueToDefaultExpr)) + : cast(values); + return new FunctionExpression('array_contains_any', [ + this, + normalizedExpr, + ]).asBoolean(); + } + + /** + * @beta + * Creates an expression that reverses an array. + * + * @example + * ```typescript + * // Reverse the value of the 'myArray' field. + * field("myArray").arrayReverse(); + * ``` + * + * @returns A new `Expression` representing the reversed array. + */ + arrayReverse(): FunctionExpression { + return new FunctionExpression('array_reverse', [this]); + } + + /** + * @beta + * Creates an expression that calculates the length of an array. + * + * @example + * ```typescript + * // Get the number of items in the 'cart' array + * field("cart").arrayLength(); + * ``` + * + * @returns A new `Expression` representing the length of the array. + */ + arrayLength(): FunctionExpression { + return new FunctionExpression('array_length', [this]); + } + + /** + * @beta + * Creates an expression that checks if this expression is equal to any of the provided values or + * expressions. + * + * @example + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * field("category").equalAny("Electronics", field("primaryType")); + * ``` + * + * @param values The values or expressions to check against. + * @returns A new `Expression` representing the 'IN' comparison. + */ + equalAny(values: Array): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if this expression is equal to any of the provided values or + * expressions. + * + * @example + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * field("category").equalAny(array(["Electronics", field("primaryType")])); + * ``` + * + * @param arrayExpression An expression that evaluates to an array of values to check against. + * @returns A new `Expression` representing the 'IN' comparison. + */ + equalAny(arrayExpression: Expression): BooleanExpression; + equalAny(others: unknown[] | Expression): BooleanExpression { + const exprOthers = Array.isArray(others) + ? new ListOfExprs(others.map(valueToDefaultExpr)) + : cast(others); + return new FunctionExpression('equal_any', [this, exprOthers]).asBoolean(); + } + + /** + * @beta + * Creates an expression that checks if this expression is not equal to any of the provided values or + * expressions. + * + * @example + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * field("status").notEqualAny(["pending", field("rejectedStatus")]); + * ``` + * + * @param values The values or expressions to check against. + * @returns A new `Expression` representing the 'NotEqAny' comparison. + */ + notEqualAny(values: Array): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if this expression is not equal to any of the values in the evaluated expression. + * + * @example + * ```typescript + * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' + * field("status").notEqualAny(field('rejectedStatuses')); + * ``` + * + * @param arrayExpression The values or expressions to check against. + * @returns A new `Expression` representing the 'NotEqAny' comparison. + */ + notEqualAny(arrayExpression: Expression): BooleanExpression; + notEqualAny(others: unknown[] | Expression): BooleanExpression { + const exprOthers = Array.isArray(others) + ? new ListOfExprs(others.map(valueToDefaultExpr)) + : cast(others); + return new FunctionExpression('not_equal_any', [ + this, + exprOthers, + ]).asBoolean(); + } + + /** + * @beta + * Creates an expression that checks if a field exists in the document. + * + * @example + * ```typescript + * // Check if the document has a field named "phoneNumber" + * field("phoneNumber").exists(); + * ``` + * + * @returns A new `Expression` representing the 'exists' check. + */ + exists(): BooleanExpression { + return new FunctionExpression('exists', [this]).asBoolean(); + } + + /** + * @beta + * Creates an expression that calculates the character length of a string in UTF-8. + * + * @example + * ```typescript + * // Get the character length of the 'name' field in its UTF-8 form. + * field("name").charLength(); + * ``` + * + * @returns A new `Expression` representing the length of the string. + */ + charLength(): FunctionExpression { + return new FunctionExpression('char_length', [this]); + } + + /** + * @beta + * Creates an expression that performs a case-sensitive string comparison. + * + * @example + * ```typescript + * // Check if the 'title' field contains the word "guide" (case-sensitive) + * field("title").like("%guide%"); + * ``` + * + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @returns A new `Expression` representing the 'like' comparison. + */ + like(pattern: string): BooleanExpression; + + /** + * @beta + * Creates an expression that performs a case-sensitive string comparison. + * + * @example + * ```typescript + * // Check if the 'title' field contains the word "guide" (case-sensitive) + * field("title").like("%guide%"); + * ``` + * + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @returns A new `Expression` representing the 'like' comparison. + */ + like(pattern: Expression): BooleanExpression; + like(stringOrExpr: string | Expression): BooleanExpression { + return new FunctionExpression('like', [ + this, + valueToDefaultExpr(stringOrExpr), + ]).asBoolean(); + } + + /** + * @beta + * Creates an expression that checks if a string contains a specified regular expression as a + * substring. + * + * @example + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * field("description").regexContains("(?i)example"); + * ``` + * + * @param pattern The regular expression to use for the search. + * @returns A new `Expression` representing the 'contains' comparison. + */ + regexContains(pattern: string): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a string contains a specified regular expression as a + * substring. + * + * @example + * ```typescript + * // Check if the 'description' field contains the regular expression stored in field 'regex' + * field("description").regexContains(field("regex")); + * ``` + * + * @param pattern The regular expression to use for the search. + * @returns A new `Expression` representing the 'contains' comparison. + */ + regexContains(pattern: Expression): BooleanExpression; + regexContains(stringOrExpr: string | Expression): BooleanExpression { + return new FunctionExpression('regex_contains', [ + this, + valueToDefaultExpr(stringOrExpr), + ]).asBoolean(); + } + + /** + * @beta + * Creates an expression that returns the first substring of a string expression that matches + * a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract the domain from an email address + * field("email").regexFind("@.+") + * ``` + * + * @param pattern The regular expression to search for. + * @returns A new `Expression` representing the regular expression find function. + */ + regexFind(pattern: string): FunctionExpression; + + /** + * @beta + * Creates an expression that returns the first substring of a string expression that matches + * a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract the domain from an email address + * field("email").regexFind(field("domain")) + * ``` + * + * @param pattern The regular expression to search for. + * @returns A new `Expression` representing the regular expression find function. + */ + regexFind(pattern: Expression): FunctionExpression; + regexFind(stringOrExpr: string | Expression): FunctionExpression { + return new FunctionExpression('regex_find', [ + this, + valueToDefaultExpr(stringOrExpr), + ]); + } + + /** + * @beta + * + * Creates an expression that evaluates to a list of all substrings in this string expression that + * match a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract all hashtags from a post content field + * field("content").regexFindAll("#[A-Za-z0-9_]+") + * ``` + * + * @param pattern The regular expression to search for. + * @returns A new `Expression` that evaluates to an array of matched substrings. + */ + regexFindAll(pattern: string): FunctionExpression; + + /** + * @beta + * + * Creates an expression that evaluates to a list of all substrings in this string expression that + * match a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract all names from a post content field + * field("content").regexFindAll(field("names")) + * ``` + * + * @param pattern The regular expression to search for. + * @returns A new `Expression` that evaluates to an array of matched substrings. + */ + regexFindAll(pattern: Expression): FunctionExpression; + regexFindAll(stringOrExpr: string | Expression): FunctionExpression { + return new FunctionExpression('regex_find_all', [ + this, + valueToDefaultExpr(stringOrExpr), + ]); + } + + /** + * @beta + * Creates an expression that checks if a string matches a specified regular expression. + * + * @example + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * field("email").regexMatch("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * ``` + * + * @param pattern The regular expression to use for the match. + * @returns A new `Expression` representing the regular expression match. + */ + regexMatch(pattern: string): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a string matches a specified regular expression. + * + * @example + * ```typescript + * // Check if the 'email' field matches a regular expression stored in field 'regex' + * field("email").regexMatch(field("regex")); + * ``` + * + * @param pattern The regular expression to use for the match. + * @returns A new `Expression` representing the regular expression match. + */ + regexMatch(pattern: Expression): BooleanExpression; + regexMatch(stringOrExpr: string | Expression): BooleanExpression { + return new FunctionExpression('regex_match', [ + this, + valueToDefaultExpr(stringOrExpr), + ]).asBoolean(); + } + + /** + * @beta + * Creates an expression that checks if a string contains a specified substring. + * + * @example + * ```typescript + * // Check if the 'description' field contains "example". + * field("description").stringContains("example"); + * ``` + * + * @param substring The substring to search for. + * @returns A new `Expression` representing the 'contains' comparison. + */ + stringContains(substring: string): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a string contains the string represented by another expression. + * + * @example + * ```typescript + * // Check if the 'description' field contains the value of the 'keyword' field. + * field("description").stringContains(field("keyword")); + * ``` + * + * @param expr The expression representing the substring to search for. + * @returns A new `Expression` representing the 'contains' comparison. + */ + stringContains(expr: Expression): BooleanExpression; + stringContains(stringOrExpr: string | Expression): BooleanExpression { + return new FunctionExpression('string_contains', [ + this, + valueToDefaultExpr(stringOrExpr), + ]).asBoolean(); + } + + /** + * @beta + * Creates an expression that checks if a string starts with a given prefix. + * + * @example + * ```typescript + * // Check if the 'name' field starts with "Mr." + * field("name").startsWith("Mr."); + * ``` + * + * @param prefix The prefix to check for. + * @returns A new `Expression` representing the 'starts with' comparison. + */ + startsWith(prefix: string): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a string starts with a given prefix (represented as an + * expression). + * + * @example + * ```typescript + * // Check if the 'fullName' field starts with the value of the 'firstName' field + * field("fullName").startsWith(field("firstName")); + * ``` + * + * @param prefix The prefix expression to check for. + * @returns A new `Expression` representing the 'starts with' comparison. + */ + startsWith(prefix: Expression): BooleanExpression; + startsWith(stringOrExpr: string | Expression): BooleanExpression { + return new FunctionExpression('starts_with', [ + this, + valueToDefaultExpr(stringOrExpr), + ]).asBoolean(); + } + + /** + * @beta + * Creates an expression that checks if a string ends with a given postfix. + * + * @example + * ```typescript + * // Check if the 'filename' field ends with ".txt" + * field("filename").endsWith(".txt"); + * ``` + * + * @param suffix The postfix to check for. + * @returns A new `Expression` representing the 'ends with' comparison. + */ + endsWith(suffix: string): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a string ends with a given postfix (represented as an + * expression). + * + * @example + * ```typescript + * // Check if the 'url' field ends with the value of the 'extension' field + * field("url").endsWith(field("extension")); + * ``` + * + * @param suffix The postfix expression to check for. + * @returns A new `Expression` representing the 'ends with' comparison. + */ + endsWith(suffix: Expression): BooleanExpression; + endsWith(stringOrExpr: string | Expression): BooleanExpression { + return new FunctionExpression('ends_with', [ + this, + valueToDefaultExpr(stringOrExpr), + ]).asBoolean(); + } + + /** + * @beta + * Creates an expression that converts a string to lowercase. + * + * @example + * ```typescript + * // Convert the 'name' field to lowercase + * field("name").toLower(); + * ``` + * + * @returns A new `Expression` representing the lowercase string. + */ + toLower(): FunctionExpression { + return new FunctionExpression('to_lower', [this]); + } + + /** + * @beta + * Creates an expression that converts a string to uppercase. + * + * @example + * ```typescript + * // Convert the 'title' field to uppercase + * field("title").toUpper(); + * ``` + * + * @returns A new `Expression` representing the uppercase string. + */ + toUpper(): FunctionExpression { + return new FunctionExpression('to_upper', [this]); + } + + /** + * @beta + * Creates an expression that removes leading and trailing characters from a string or byte array. + * + * @example + * ```typescript + * // Trim whitespace from the 'userInput' field + * field("userInput").trim(); + * + * // Trim quotes from the 'userInput' field + * field("userInput").trim('"'); + * ``` + * @param valueToTrim Optional This parameter is treated as a set of characters or bytes that will be + * trimmed from the input. If not specified, then whitespace will be trimmed. + * @returns A new `Expr` representing the trimmed string or byte array. + */ + trim( + valueToTrim?: string | Expression | Uint8Array | Buffer, + ): FunctionExpression { + const args: Expression[] = [this]; + if (valueToTrim) { + args.push(valueToDefaultExpr(valueToTrim)); + } + return new FunctionExpression('trim', args); + } + + /** + * @beta + * Creates an expression that concatenates string expressions together. + * + * @example + * ```typescript + * // Combine the 'firstName', " ", and 'lastName' fields into a single string + * field("firstName").stringConcat(constant(" "), field("lastName")); + * ``` + * + * @param secondString The additional expression or string literal to concatenate. + * @param otherStrings Optional additional expressions or string literals to concatenate. + * @returns A new `Expression` representing the concatenated string. + */ + stringConcat( + secondString: Expression | string, + ...otherStrings: Array + ): FunctionExpression { + const elements = [secondString, ...otherStrings]; + const exprs = elements.map(valueToDefaultExpr); + return new FunctionExpression('string_concat', [this, ...exprs]); + } + + /** + * @beta + * Creates an expression that concatenates expression results together. + * + * @example + * ```typescript + * // Combine the 'firstName', ' ', and 'lastName' fields into a single value. + * field("firstName").concat(constant(" "), field("lastName")); + * ``` + * + * @param second The additional expression or literal to concatenate. + * @param others Optional additional expressions or literals to concatenate. + * @returns A new `Expr` representing the concatenated value. + */ + concat( + second: Expression | unknown, + ...others: Array + ): FunctionExpression { + const elements = [second, ...others]; + const exprs = elements.map(valueToDefaultExpr); + return new FunctionExpression('concat', [this, ...exprs]); + } + + /** + * @beta + * Creates an expression that reverses this string or bytes expression. + * + * @example + * ```typescript + * // Reverse the value of the 'myString' field. + * field("myString").reverse(); + * ``` + * + * @returns A new `Expression` representing the reversed string or bytes. + */ + reverse(): FunctionExpression { + return new FunctionExpression('reverse', [this]); + } + + /** + * @beta + * Creates an expression that calculates the length of this string expression in bytes. + * + * @example + * ```typescript + * // Calculate the length of the 'myString' field in bytes. + * field("myString").byteLength(); + * ``` + * + * @returns A new `Expression` representing the length of the string in bytes. + */ + byteLength(): FunctionExpression { + return new FunctionExpression('byte_length', [this]); + } + + /** + * @beta + * Creates an expression that computes the ceiling of a numeric value. + * + * @example + * ```typescript + * // Compute the ceiling of the 'price' field. + * field("price").ceil(); + * ``` + * + * @returns A new `Expression` representing the ceiling of the numeric value. + */ + ceil(): FunctionExpression { + return new FunctionExpression('ceil', [this]); + } + + /** + * @beta + * Creates an expression that computes the floor of a numeric value. + * + * @example + * ```typescript + * // Compute the floor of the 'price' field. + * field("price").floor(); + * ``` + * + * @returns A new `Expression` representing the floor of the numeric value. + */ + floor(): FunctionExpression { + return new FunctionExpression('floor', [this]); + } + + /** + * @beta + * Creates an expression that computes the absolute value of a numeric value. + * + * @example + * ```typescript + * // Compute the absolute value of the 'price' field. + * field("price").abs(); + * ``` + * + * @returns A new `Expr` representing the absolute value of the numeric value. + */ + abs(): FunctionExpression { + return new FunctionExpression('abs', [this]); + } + + /** + * @beta + * Creates an expression that computes e to the power of this expression. + * + * @example + * ```typescript + * // Compute e to the power of the 'value' field. + * field("value").exp(); + * ``` + * + * @returns A new `Expression` representing the exp of the numeric value. + */ + exp(): FunctionExpression { + return new FunctionExpression('exp', [this]); + } + + /** + * @beta + * Accesses a value from a map (object) field using the provided key. + * + * @example + * ```typescript + * // Get the 'city' value from the 'address' map field + * field("address").mapGet("city"); + * ``` + * + * @param subfield The key to access in the map. + * @returns A new `Expression` representing the value associated with the given key in the map. + */ + mapGet(subfield: string): FunctionExpression { + return new FunctionExpression('map_get', [this, constant(subfield)]); + } + + /** + * @beta + * Creates an expression that returns a new map with the specified entries added or updated. + * + * @remarks + * Note that `mapSet` only performs shallow updates to the map. Setting a value to `null` + * will retain the key with a `null` value. To remove a key entirely, use `mapRemove`. + * + * @example + * ```typescript + * // Set the 'city' to "San Francisco" in the 'address' map + * field("address").mapSet("city", "San Francisco"); + * ``` + * + * @param key The key to set. Must be a string or a constant string expression. + * @param value The value to set. + * @param moreKeyValues Additional key-value pairs to set. + * @returns A new `Expression` representing the map with the entries set. + */ + mapSet( + key: string | Expression, + value: unknown, + ...moreKeyValues: unknown[] + ): FunctionExpression { + const args = [ + this, + valueToDefaultExpr(key), + valueToDefaultExpr(value), + ...moreKeyValues.map(valueToDefaultExpr), + ]; + return new FunctionExpression('map_set', args); + } + + /** + * @beta + * Creates an expression that returns the keys of a map. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the keys of the 'address' map + * field("address").mapKeys(); + * ``` + * + * @returns A new `Expression` representing the keys of the map. + */ + mapKeys(): FunctionExpression { + return new FunctionExpression('map_keys', [this]); + } + + /** + * @beta + * Creates an expression that returns the values of a map. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the values of the 'address' map + * field("address").mapValues(); + * ``` + * + * @returns A new `Expression` representing the values of the map. + */ + mapValues(): FunctionExpression { + return new FunctionExpression('map_values', [this]); + } + + /** + * @beta + * Creates an expression that returns the entries of a map as an array of maps, + * where each map contains a `"k"` property for the key and a `"v"` property for the value. + * For example: `[{ k: "key1", v: "value1" }, ...]`. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the entries of the 'address' map + * field("address").mapEntries(); + * ``` + * + * @returns A new `Expression` representing the entries of the map. + */ + mapEntries(): FunctionExpression { + return new FunctionExpression('map_entries', [this]); + } + + /** + * @beta + * Creates an aggregation that counts the number of stage inputs with valid evaluations of the + * expression or field. + * + * @example + * ```typescript + * // Count the total number of products + * field("productId").count().as("totalProducts"); + * ``` + * + * @returns A new `AggregateFunction` representing the 'count' aggregation. + */ + count(): AggregateFunction { + return new AggregateFunction('count', [this]); + } + + /** + * @beta + * Creates an aggregation that calculates the sum of a numeric field across multiple stage inputs. + * + * @example + * ```typescript + * // Calculate the total revenue from a set of orders + * field("orderAmount").sum().as("totalRevenue"); + * ``` + * + * @returns A new `AggregateFunction` representing the 'sum' aggregation. + */ + sum(): AggregateFunction { + return new AggregateFunction('sum', [this]); + } + + /** + * @beta + * Creates an aggregation that calculates the average (mean) of a numeric field across multiple + * stage inputs. + * + * @example + * ```typescript + * // Calculate the average age of users + * field("age").average().as("averageAge"); + * ``` + * + * @returns A new `AggregateFunction` representing the 'average' aggregation. + */ + average(): AggregateFunction { + return new AggregateFunction('average', [this]); + } + + /** + * @beta + * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. + * + * @example + * ```typescript + * // Find the lowest price of all products + * field("price").minimum().as("lowestPrice"); + * ``` + * + * @returns A new `AggregateFunction` representing the 'min' aggregation. + */ + minimum(): AggregateFunction { + return new AggregateFunction('minimum', [this]); + } + + /** + * @beta + * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. + * + * @example + * ```typescript + * // Find the highest score in a leaderboard + * field("score").maximum().as("highestScore"); + * ``` + * + * @returns A new `AggregateFunction` representing the 'max' aggregation. + */ + maximum(): AggregateFunction { + return new AggregateFunction('maximum', [this]); + } + + /** + * @beta + * Creates an aggregation that counts the number of distinct values of the expression or field. + * + * @example + * ```typescript + * // Count the distinct number of products + * field("productId").countDistinct().as("distinctProducts"); + * ``` + * + * @returns A new `AggregateFunction` representing the 'count_distinct' aggregation. + */ + countDistinct(): AggregateFunction { + return new AggregateFunction('count_distinct', [this]); + } + + /** + * @beta + * Creates an expression that returns the larger value between this expression and another expression, based on Firestore's value type ordering. + * + * @example + * ```typescript + * // Returns the larger value between the 'timestamp' field and the current timestamp. + * field("timestamp").logicalMaximum(Function.currentTimestamp()); + * ``` + * + * @param second The second expression or literal to compare with. + * @param others Optional additional expressions or literals to compare with. + * @returns A new `Expression` representing the logical max operation. + */ + logicalMaximum( + second: Expression | unknown, + ...others: Array + ): FunctionExpression { + const values = [second, ...others]; + return new FunctionExpression('maximum', [ + this, + ...values.map(valueToDefaultExpr), + ]); + } + + /** + * @beta + * Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering. + * + * @example + * ```typescript + * // Returns the smaller value between the 'timestamp' field and the current timestamp. + * field("timestamp").logicalMinimum(Function.currentTimestamp()); + * ``` + * + * @param second The second expression or literal to compare with. + * @param others Optional additional expressions or literals to compare with. + * @returns A new `Expression` representing the logical min operation. + */ + logicalMinimum( + second: Expression | unknown, + ...others: Array + ): FunctionExpression { + const values = [second, ...others]; + return new FunctionExpression('minimum', [ + this, + ...values.map(valueToDefaultExpr), + ]); + } + + /** + * @beta + * Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression. + * + * @example + * ```typescript + * // Get the vector length (dimension) of the field 'embedding'. + * field("embedding").vectorLength(); + * ``` + * + * @returns A new `Expression` representing the length of the vector. + */ + vectorLength(): FunctionExpression { + return new FunctionExpression('vector_length', [this]); + } + + /** + * @beta + * Calculates the cosine distance between two vectors. + * + * @example + * ```typescript + * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field + * field("userVector").cosineDistance(field("itemVector")); + * ``` + * + * @param vectorExpression The other vector (represented as an Expression) to compare against. + * @returns A new `Expression` representing the cosine distance between the two vectors. + */ + cosineDistance(vectorExpression: Expression): FunctionExpression; + /** + * @beta + * Calculates the Cosine distance between two vectors. + * + * @example + * ```typescript + * // Calculate the Cosine distance between the 'location' field and a target location + * field("location").cosineDistance(new VectorValue([37.7749, -122.4194])); + * ``` + * + * @param vector The other vector (as a VectorValue) to compare against. + * @returns A new `Expression` representing the Cosine distance between the two vectors. + */ + cosineDistance(vector: firestore.VectorValue | number[]): FunctionExpression; + cosineDistance( + other: Expression | firestore.VectorValue | number[], + ): FunctionExpression { + return new FunctionExpression('cosine_distance', [ + this, + vectorToExpr(other), + ]); + } + + /** + * @beta + * Calculates the dot product between two vectors. + * + * @example + * ```typescript + * // Calculate the dot product between a feature vector and a target vector + * field("features").dotProduct([0.5, 0.8, 0.2]); + * ``` + * + * @param vectorExpression The other vector (as an array of numbers) to calculate with. + * @returns A new `Expression` representing the dot product between the two vectors. + */ + dotProduct(vectorExpression: Expression): FunctionExpression; + + /** + * @beta + * Calculates the dot product between two vectors. + * + * @example + * ```typescript + * // Calculate the dot product between a feature vector and a target vector + * field("features").dotProduct(new VectorValue([0.5, 0.8, 0.2])); + * ``` + * + * @param vector The other vector (as an array of numbers) to calculate with. + * @returns A new `Expression` representing the dot product between the two vectors. + */ + dotProduct(vector: firestore.VectorValue | number[]): FunctionExpression; + dotProduct( + other: Expression | firestore.VectorValue | number[], + ): FunctionExpression { + return new FunctionExpression('dot_product', [this, vectorToExpr(other)]); + } + + /** + * @beta + * Calculates the Euclidean distance between two vectors. + * + * @example + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * field("location").euclideanDistance([37.7749, -122.4194]); + * ``` + * + * @param vectorExpression The other vector (as an array of numbers) to calculate with. + * @returns A new `Expression` representing the Euclidean distance between the two vectors. + */ + euclideanDistance(vectorExpression: Expression): FunctionExpression; + + /** + * @beta + * Calculates the Euclidean distance between two vectors. + * + * @example + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * field("location").euclideanDistance(new VectorValue([37.7749, -122.4194])); + * ``` + * + * @param vector The other vector (as a VectorValue) to compare against. + * @returns A new `Expression` representing the Euclidean distance between the two vectors. + */ + euclideanDistance( + vector: firestore.VectorValue | number[], + ): FunctionExpression; + euclideanDistance( + other: Expression | firestore.VectorValue | number[], + ): FunctionExpression { + return new FunctionExpression('euclidean_distance', [ + this, + vectorToExpr(other), + ]); + } + + /** + * @beta + * Creates an expression that interprets this expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * @example + * ```typescript + * // Interpret the 'microseconds' field as microseconds since epoch. + * field("microseconds").unixMicrosToTimestamp(); + * ``` + * + * @returns A new `Expression` representing the timestamp. + */ + unixMicrosToTimestamp(): FunctionExpression { + return new FunctionExpression('unix_micros_to_timestamp', [this]); + } + + /** + * @beta + * Creates an expression that converts this timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * @example + * ```typescript + * // Convert the 'timestamp' field to microseconds since epoch. + * field("timestamp").timestampToUnixMicros(); + * ``` + * + * @returns A new `Expression` representing the number of microseconds since epoch. + */ + timestampToUnixMicros(): FunctionExpression { + return new FunctionExpression('timestamp_to_unix_micros', [this]); + } + + /** + * @beta + * Creates an expression that interprets this expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * @example + * ```typescript + * // Interpret the 'milliseconds' field as milliseconds since epoch. + * field("milliseconds").unixMillisToTimestamp(); + * ``` + * + * @returns A new `Expression` representing the timestamp. + */ + unixMillisToTimestamp(): FunctionExpression { + return new FunctionExpression('unix_millis_to_timestamp', [this]); + } + + /** + * @beta + * Creates an expression that converts this timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * @example + * ```typescript + * // Convert the 'timestamp' field to milliseconds since epoch. + * field("timestamp").timestampToUnixMillis(); + * ``` + * + * @returns A new `Expression` representing the number of milliseconds since epoch. + */ + timestampToUnixMillis(): FunctionExpression { + return new FunctionExpression('timestamp_to_unix_millis', [this]); + } + + /** + * @beta + * Creates an expression that interprets this expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * @example + * ```typescript + * // Interpret the 'seconds' field as seconds since epoch. + * field("seconds").unixSecondsToTimestamp(); + * ``` + * + * @returns A new `Expression` representing the timestamp. + */ + unixSecondsToTimestamp(): FunctionExpression { + return new FunctionExpression('unix_seconds_to_timestamp', [this]); + } + + /** + * @beta + * Creates an expression that converts this timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * @example + * ```typescript + * // Convert the 'timestamp' field to seconds since epoch. + * field("timestamp").timestampToUnixSeconds(); + * ``` + * + * @returns A new `Expression` representing the number of seconds since epoch. + */ + timestampToUnixSeconds(): FunctionExpression { + return new FunctionExpression('timestamp_to_unix_seconds', [this]); + } + + /** + * @beta + * Creates an expression that adds a specified amount of time to this timestamp expression. + * + * @example + * ```typescript + * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. + * field("timestamp").timestampAdd(field("unit"), field("amount")); + * ``` + * + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @returns A new `Expression` representing the resulting timestamp. + */ + timestampAdd(unit: Expression, amount: Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that adds a specified amount of time to this timestamp expression. + * + * @example + * ```typescript + * // Add 1 day to the 'timestamp' field. + * field("timestamp").timestampAdd("day", 1); + * ``` + * + * @param unit The unit of time to add (e.g., "day", "hour"). + * @param amount The amount of time to add. + * @returns A new `Expression` representing the resulting timestamp. + */ + timestampAdd( + unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', + amount: number, + ): FunctionExpression; + timestampAdd( + unit: + | Expression + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: Expression | number, + ): FunctionExpression { + return new FunctionExpression('timestamp_add', [ + this, + valueToDefaultExpr(unit), + valueToDefaultExpr(amount), + ]); + } + + /** + * @beta + * Creates an expression that subtracts a specified amount of time from this timestamp expression. + * + * @example + * ```typescript + * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. + * field("timestamp").timestampSubtract(field("unit"), field("amount")); + * ``` + * + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @returns A new `Expression` representing the resulting timestamp. + */ + timestampSubtract(unit: Expression, amount: Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that subtracts a specified amount of time from this timestamp expression. + * + * @example + * ```typescript + * // Subtract 1 day from the 'timestamp' field. + * field("timestamp").timestampSubtract("day", 1); + * ``` + * + * @param unit The unit of time to subtract (e.g., "day", "hour"). + * @param amount The amount of time to subtract. + * @returns A new `Expression` representing the resulting timestamp. + */ + timestampSubtract( + unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', + amount: number, + ): FunctionExpression; + timestampSubtract( + unit: + | Expression + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: Expression | number, + ): FunctionExpression { + return new FunctionExpression('timestamp_subtract', [ + this, + valueToDefaultExpr(unit), + valueToDefaultExpr(amount), + ]); + } + + /** + * @beta + * Creates an expression that returns the document ID from a path. + * + * @example + * ```typescript + * // Get the document ID from a path. + * field("__path__").documentId(); + * ``` + * + * @returns A new `Expression` representing the documentId operation. + */ + documentId(): FunctionExpression { + return new FunctionExpression('document_id', [this]); + } + + /** + * @beta + * Creates an expression that returns a substring of the results of this expression. + * + * @param position Index of the first character of the substring. + * @param length Length of the substring. If not provided, the substring will + * end at the end of the input. + */ + substring(position: number, length?: number): FunctionExpression; + + /** + * @beta + * Creates an expression that returns a substring of the results of this expression. + * + * @param position An expression returning the index of the first character of the substring. + * @param length An expression returning the length of the substring. If not provided the + * substring will end at the end of the input. + */ + substring(position: Expression, length?: Expression): FunctionExpression; + substring( + position: Expression | number, + length?: Expression | number, + ): FunctionExpression { + const positionExpr = valueToDefaultExpr(position); + if (length === undefined) { + return new FunctionExpression('substring', [this, positionExpr]); + } else { + return new FunctionExpression('substring', [ + this, + positionExpr, + valueToDefaultExpr(length), + ]); + } + } + + /** + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and returns the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. + * + * @example + * ```typescript + * // Return the value in the 'tags' field array at index `1`. + * field('tags').arrayGet(1); + * ``` + * + * @param index The index of the element to return. + * @returns A new Expression representing the 'arrayGet' operation. + */ + arrayGet(index: number): FunctionExpression; + + /** + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and returns the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. + * + * @example + * ```typescript + * // Return the value in the tags field array at index specified by field + * // 'favoriteTag'. + * field('tags').arrayGet(field('favoriteTag')); + * ``` + * + * @param indexExpr An Expression evaluating to the index of the element to return. + * @returns A new Expression representing the 'arrayGet' operation. + */ + arrayGet(indexExpr: Expression): FunctionExpression; + arrayGet(index: Expression | number): FunctionExpression { + return new FunctionExpression('array_get', [ + this, + valueToDefaultExpr(index), + ]); + } + + /** + * @beta + * Creates an expression that checks if a given expression produces an error. + * + * @example + * ```typescript + * // Check if the result of a calculation is an error + * field("title").arrayContains(1).isError(); + * ``` + * + * @returns A new `BooleanExpression` representing the 'isError' check. + */ + isError(): BooleanExpression { + return new FunctionExpression('is_error', [this]).asBoolean(); + } + + /** + * @beta + * Creates an expression that returns the result of the `catchExpr` argument + * if there is an error, else return the result of this expression. + * + * @example + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // the entire title field if the array is empty or the field is another type. + * field("title").arrayGet(0).ifError(field("title")); + * ``` + * + * @param catchExpr The catch expression that will be evaluated and + * returned if this expression produces an error. + * @returns A new `Expression` representing the 'ifError' operation. + */ + ifError(catchExpr: Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // "Default Title" + * field("title").arrayGet(0).ifError("Default Title"); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @returns A new `Expression` representing the 'ifError' operation. + */ + ifError(catchValue: unknown): FunctionExpression; + ifError(catchValue: unknown): FunctionExpression { + return new FunctionExpression('if_error', [ + this, + valueToDefaultExpr(catchValue), + ]); + } + + /** + * @beta + * Creates an expression that returns `true` if the result of this expression + * is absent. Otherwise, returns `false` even if the value is `null`. + * + * ```typescript + * // Check if the field `value` is absent. + * field("value").isAbsent(); + * ``` + * + * @returns A new `BooleanExpression` representing the 'isAbsent' check. + */ + isAbsent(): BooleanExpression { + return new FunctionExpression('is_absent', [this]).asBoolean(); + } + + /** + * @beta + * Creates an expression that removes a key from the map produced by evaluating this expression. + * + * ``` + * // Removes the key 'baz' from the input map. + * map({foo: 'bar', baz: true}).mapRemove('baz'); + * ``` + * + * @param key The name of the key to remove from the input map. + * @returns A new `FirestoreFunction` representing the 'mapRemove' operation. + */ + mapRemove(key: string): FunctionExpression; + /** + * @beta + * Creates an expression that removes a key from the map produced by evaluating this expression. + * + * ``` + * // Removes the key 'baz' from the input map. + * map({foo: 'bar', baz: true}).mapRemove(constant('baz')); + * ``` + * + * @param keyExpr An expression that produces the name of the key to remove from the input map. + * @returns A new `FirestoreFunction` representing the 'mapRemove' operation. + */ + mapRemove(keyExpr: Expression): FunctionExpression; + mapRemove(stringExpr: Expression | string): FunctionExpression { + return new FunctionExpression('map_remove', [ + this, + valueToDefaultExpr(stringExpr), + ]); + } + + /** + * @beta + * Creates an expression that merges multiple map values. + * + * ``` + * // Merges the map in the settings field with, a map literal, and a map in + * // that is conditionally returned by another expression + * field('settings').mapMerge({ enabled: true }, conditional(field('isAdmin'), { admin: true}, {}) + * ``` + * + * @param secondMap A required second map to merge. Represented as a literal or + * an expression that returns a map. + * @param otherMaps Optional additional maps to merge. Each map is represented + * as a literal or an expression that returns a map. + * + * @returns A new `FirestoreFunction` representing the 'mapMerge' operation. + */ + mapMerge( + secondMap: Record | Expression, + ...otherMaps: Array | Expression> + ): FunctionExpression { + const secondMapExpr = valueToDefaultExpr(secondMap); + const otherMapExprs = otherMaps.map(valueToDefaultExpr); + return new FunctionExpression('map_merge', [ + this, + secondMapExpr, + ...otherMapExprs, + ]); + } + + /** + * @beta + * Creates an expression that returns the value of this expression raised to the power of another expression. + * + * ```typescript + * // Raise the value of the 'base' field to the power of the 'exponent' field. + * field("base").pow(field("exponent")); + * ``` + * + * @param exponent The expression to raise this expression to the power of. + * @returns A new `Expression` representing the power operation. + */ + pow(exponent: Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that returns the value of this expression raised to the power of a constant value. + * + * ```typescript + * // Raise the value of the 'base' field to the power of 2. + * field("base").pow(2); + * ``` + * + * @param exponent The constant value to raise this expression to the power of. + * @returns A new `Expression` representing the power operation. + */ + pow(exponent: number): FunctionExpression; + pow(exponent: number | Expression): FunctionExpression { + return new FunctionExpression('pow', [this, valueToDefaultExpr(exponent)]); + } + + /** + * @beta + * Creates an expression that truncates the numeric value to an integer. + * + * @example + * ```typescript + * // Truncate the 'rating' field. + * field("rating").trunc(); + * ``` + * + * @returns A new `Expression` representing the truncated value. + */ + trunc(): FunctionExpression; + + /** + * @beta + * Creates an expression that truncates a numeric value to the specified number of decimal places. + * + * @example + * ```typescript + * // Truncate the value of the 'rating' field to two decimal places. + * field("rating").trunc(2); + * ``` + * + * @param decimalPlaces A constant specifying the truncation precision in decimal places. + * @returns A new `Expression` representing the truncated value. + */ + trunc(decimalPlaces: number): FunctionExpression; + + /** + * @beta + * Creates an expression that truncates a numeric value to the specified number of decimal places. + * + * @example + * ```typescript + * // Truncate the value of the 'rating' field to two decimal places. + * field("rating").trunc(constant(2)); + * ``` + * + * @param decimalPlaces An expression specifying the truncation precision in decimal places. + * @returns A new `Expression` representing the truncated value. + */ + trunc(decimalPlaces: Expression): FunctionExpression; + trunc(decimalPlaces?: number | Expression): FunctionExpression { + if (decimalPlaces === undefined) { + return new FunctionExpression('trunc', [this]); + } + return new FunctionExpression('trunc', [ + this, + valueToDefaultExpr(decimalPlaces), + ]); + } + + /** + * @beta + * Creates an expression that rounds a numeric value to the nearest whole number. + * + * ```typescript + * // Round the value of the 'price' field. + * field("price").round(); + * ``` + * + * @returns A new `Expression` representing the rounded value. + */ + round(): FunctionExpression; + /** + * @beta + * Creates an expression that rounds a numeric value to the specified number of decimal places. + * + * ```typescript + * // Round the value of the 'price' field to two decimal places. + * field("price").round(2); + * ``` + * + * @param decimalPlaces A constant specifying the rounding precision in decimal places. + * + * @returns A new `Expr` representing the rounded value. + */ + round(decimalPlaces: number): FunctionExpression; + /** + * @beta + * Creates an expression that rounds a numeric value to the specified number of decimal places. + * + * ```typescript + * // Round the value of the 'price' field to two decimal places. + * field("price").round(constant(2)); + * ``` + * + * @param decimalPlaces An expression specifying the rounding precision in decimal places. + * + * @returns A new `Expr` representing the rounded value. + */ + round(decimalPlaces: Expression): FunctionExpression; + round(decimalPlaces?: number | Expression): FunctionExpression { + if (decimalPlaces === undefined) { + return new FunctionExpression('round', [this]); + } else { + return new FunctionExpression('round', [ + this, + valueToDefaultExpr(decimalPlaces), + ]); + } + } + + /** + * @beta + * Creates an expression that returns the collection ID from a path. + * + * ```typescript + * // Get the collection ID from a path. + * field("__path__").collectionId(); + * ``` + * + * @returns A new `Expression` representing the collectionId operation. + */ + collectionId(): FunctionExpression { + return new FunctionExpression('collection_id', [this]); + } + + /** + * @beta + * Creates an expression that calculates the length of a string, array, map, vector, or bytes. + * + * ```typescript + * // Get the length of the 'name' field. + * field("name").length(); + * + * // Get the number of items in the 'cart' array. + * field("cart").length(); + * ``` + * + * @returns A new `Expression` representing the length of the string, array, map, vector, or bytes. + */ + length(): FunctionExpression { + return new FunctionExpression('length', [this]); + } + + /** + * @beta + * Creates an expression that computes the natural logarithm of a numeric value. + * + * ```typescript + * // Compute the natural logarithm of the 'value' field. + * field("value").ln(); + * ``` + * + * @returns A new `Expression` representing the natural logarithm of the numeric value. + */ + ln(): FunctionExpression { + return new FunctionExpression('ln', [this]); + } + + /** + * @beta + * Creates an expression that computes the square root of a numeric value. + * + * ```typescript + * // Compute the square root of the 'value' field. + * field("value").sqrt(); + * ``` + * + * @returns A new `Expression` representing the square root of the numeric value. + */ + sqrt(): FunctionExpression { + return new FunctionExpression('sqrt', [this]); + } + + /** + * @beta + * Creates an expression that reverses a string. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * field("myString").stringReverse(); + * ``` + * + * @returns A new `Expression` representing the reversed string. + */ + stringReverse(): FunctionExpression { + return new FunctionExpression('string_reverse', [this]); + } + + /** + * @beta + * Creates an expression that returns the `elseValue` argument if this expression results in an absent value, else + * return the result of the this expression evaluation. + * + * ```typescript + * // Returns the value of the optional field 'optional_field', or returns 'default_value' + * // if the field is absent. + * field("optional_field").ifAbsent("default_value") + * ``` + * + * @param elseValue The value that will be returned if this Expression evaluates to an absent value. + * @returns A new [Expression] representing the ifAbsent operation. + */ + ifAbsent(elseValue: unknown): Expression; + + /** + * @beta + * Creates an expression that returns the `elseValue` argument if this expression results in an absent value, else + * return the result of this expression evaluation. + * + * ```typescript + * // Returns the value of the optional field 'optional_field', or if that is + * // absent, then returns the value of the field ` + * field("optional_field").ifAbsent(field('default_field')) + * ``` + * + * @param elseExpression The Expression that will be evaluated if this Expression evaluates to an absent value. + * @returns A new [Expression] representing the ifAbsent operation. + */ + ifAbsent(elseExpression: unknown): Expression; + + ifAbsent(elseValueOrExpression: Expression | unknown): Expression { + return new FunctionExpression('if_absent', [ + this, + valueToDefaultExpr(elseValueOrExpression), + ]); + } + + /** + * @beta + * Creates an expression that joins the elements of an array into a string. + * + * ```typescript + * // Join the elements of the 'tags' field with the delimiter from the 'separator' field. + * field("tags").join(field("separator")) + * ``` + * + * @param delimiterExpression The expression that evaluates to the delimiter string. + * @returns A new Expression representing the join operation. + */ + join(delimiterExpression: Expression): Expression; + + /** + * @beta + * Creates an expression that joins the elements of an array field into a string. + * + * ```typescript + * // Join the elements of the 'tags' field with a comma and space. + * field("tags").join(", ") + * ``` + * + * @param delimiter The string to use as a delimiter. + * @returns A new Expression representing the join operation. + */ + join(delimiter: string): Expression; + + join(delimeterValueOrExpression: string | Expression): Expression { + return new FunctionExpression('join', [ + this, + valueToDefaultExpr(delimeterValueOrExpression), + ]); + } + + /** + * @beta + * Creates an expression that computes the base-10 logarithm of a numeric value. + * + * ```typescript + * // Compute the base-10 logarithm of the 'value' field. + * field("value").log10(); + * ``` + * + * @returns A new `Expr` representing the base-10 logarithm of the numeric value. + */ + log10(): FunctionExpression { + return new FunctionExpression('log10', [this]); + } + + /** + * @beta + * Creates an expression that computes the sum of the elements in an array. + * + * ```typescript + * // Compute the sum of the elements in the 'scores' field. + * field("scores").arraySum(); + * ``` + * + * @returns A new `Expr` representing the sum of the elements in the array. + */ + arraySum(): FunctionExpression { + return new FunctionExpression('sum', [this]); + } + + /** + * @beta + * Creates an expression that splits the result of this expression into an + * array of substrings based on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scoresCsv' field on delimiter ',' + * field('scoresCsv').split(',') + * ``` + * + * @returns A new `Expression` representing the split function. + */ + split(delimiter: string): FunctionExpression; + + /** + * @beta + * Creates an expression that splits the result of this expression into an + * array of substrings based on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format + * field('scores').split(conditional(field('format').equal('csv'), constant(','), constant(':')) + * ``` + * + * @returns A new `Expression` representing the split function. + */ + split(delimiter: Expression): FunctionExpression; + split(delimiter: string | Expression): FunctionExpression { + return new FunctionExpression('split', [ + this, + valueToDefaultExpr(delimiter), + ]); + } + + /** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the beginning of the day. + * field('createdAt').timestampTruncate('day') + * ``` + * + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @returns A new {Expression} representing the truncated timestamp. + */ + timestampTruncate( + granularity: firestore.Pipelines.TimeGranularity, + timezone?: string | Expression, + ): FunctionExpression; + + /** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'. + * field('createdAt').timestampTruncate(field('granularity')) + * ``` + * + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @returns A new {Expression} representing the truncated timestamp. + */ + timestampTruncate( + granularity: Expression, + timezone?: string | Expression, + ): FunctionExpression; + timestampTruncate( + granularity: firestore.Pipelines.TimeGranularity | Expression, + timezone?: string | Expression, + ): FunctionExpression { + const internalGranularity = isString(granularity) + ? granularity.toLowerCase() + : granularity; + + const args = [this, valueToDefaultExpr(internalGranularity)]; + if (timezone) { + args.push(valueToDefaultExpr(timezone)); + } + return new FunctionExpression('timestamp_trunc', args); + } + + /** + * @beta + * Creates an expression that returns the data type of this expression's result, as a string. + * + * @example + * ```typescript + * // Get the data type of the value in field 'title' + * field('title').type() + * ``` + * + * @returns A new {Expression} representing the data type. + */ + type(): FunctionExpression { + return new FunctionExpression('type', [this]); + } + + /** + * @beta + * Creates an expression that checks if the result of this expression is of the given type. + * + * @remarks Null or undefined fields evaluate to skip/error. Use `ifAbsent()` / `isAbsent()` to evaluate missing data. + * + * @example + * ```typescript + * // Check if the 'price' field is specifically an integer (not just 'number') + * field('price').isType('int64'); + * ``` + * + * @param type The type to check for. + * @returns A new `BooleanExpression` that evaluates to true if the expression's result is of the given type, false otherwise. + */ + isType(type: Type): BooleanExpression { + return new FunctionExpression('is_type', [ + this, + constant(type), + ]).asBoolean(); + } + + // TODO(new-expression): Add new expression method definitions above this line + + /** + * @beta + * Creates an `Ordering` that sorts documents in ascending order based on this expression. + * + * ```typescript + * // Sort documents by the 'name' field in ascending order + * pipeline().collection("users") + * .sort(field("name").ascending()); + * ``` + * + * @returns A new `Ordering` for ascending sorting. + */ + ascending(): Ordering { + return ascending(this); + } + + /** + * @beta + * Creates an `Ordering` that sorts documents in descending order based on this expression. + * + * ```typescript + * // Sort documents by the 'createdAt' field in descending order + * firestore.pipeline().collection("users") + * .sort(field("createdAt").descending()); + * ``` + * + * @returns A new `Ordering` for descending sorting. + */ + descending(): Ordering { + return descending(this); + } + + /** + * @beta + * Assigns an alias to this expression. + * + * Aliases are useful for renaming fields in the output of a stage or for giving meaningful + * names to calculated values. + * + * ```typescript + * // Calculate the total price and assign it the alias "totalPrice" and add it to the output. + * firestore.pipeline().collection("items") + * .addFields(field("price").multiply(field("quantity")).as("totalPrice")); + * ``` + * + * @param name The alias to assign to this expression. + * @returns A new `AliasedExpression` that wraps this + * expression and associates it with the provided alias. + */ + as(name: string): AliasedExpression { + return new AliasedExpression(this, name); + } +} + +/** + * @beta + * A class that represents an aggregate function. + */ +export class AggregateFunction implements AggregateFunction, HasUserData { + expressionType: firestore.Pipelines.ExpressionType = 'AggregateFunction'; + + /** + * @beta + * @internal + * @private + * Indicates if this expression was created from a literal value passed + * by the caller. + */ + _createdFromLiteral = false; + + /** + * @beta + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + this.params.forEach(expr => { + return expr._validateUserData(ignoreUndefinedProperties); + }); + } + + constructor( + private name: string, + private params: Expression[], + ) {} + + /** + * @beta + * Assigns an alias to this AggregateFunction. The alias specifies the name that + * the aggregated value will have in the output document. + * + * ```typescript + * // Calculate the average price of all items and assign it the alias "averagePrice". + * firestore.pipeline().collection("items") + * .aggregate(field("price").average().as("averagePrice")); + * ``` + * + * @param name The alias to assign to this AggregateFunction. + * @returns A new `AliasedAggregate` that wraps this + * AggregateFunction and associates it with the provided alias. + */ + as(name: string): AliasedAggregate { + return new AliasedAggregate(this, name); + } + + /** + * @beta + * @private + * @internal + */ + _toProto(serializer: Serializer): api.IValue { + return { + functionValue: { + name: this.name, + args: this.params.map(p => p._toProto(serializer)), + }, + }; + } + + _protoValueType = 'ProtoValue' as const; +} + +/** + * @beta + * An AggregateFunction with alias. + */ +export class AliasedAggregate implements AliasedAggregate, HasUserData { + constructor( + readonly _aggregate: AggregateFunction, + readonly _alias: string, + ) {} + + /** + * @beta + * @internal + * @private + * Indicates if this expression was created from a literal value passed + * by the caller. + */ + _createdFromLiteral = false; + + /** + * @beta + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + this._aggregate._validateUserData(ignoreUndefinedProperties); + } +} + +/** + * @beta + * Represents an expression that has been assigned an alias using the `.as()` method. + * + * This class wraps an existing `Expression` and associates it with a user-defined alias, + * allowing the expression's result to be referred to by name in the output + * of a Firestore pipeline query. + */ +export class AliasedExpression + implements firestore.Pipelines.Selectable, HasUserData +{ + expressionType: firestore.Pipelines.ExpressionType = 'AliasedExpression'; + selectable = true as const; + + /** + * @beta + * @internal + * @private + * Indicates if this expression was created from a literal value passed + * by the caller. + */ + _createdFromLiteral = false; + + constructor( + readonly _expr: Expression, + readonly _alias: string, + ) {} + + /** + * @beta + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + this._expr._validateUserData(ignoreUndefinedProperties); + } +} + +/** + * @beta + * @internal + */ +class ListOfExprs extends Expression { + expressionType: firestore.Pipelines.ExpressionType = 'ListOfExprs'; + + constructor(private exprs: Expression[]) { + super(); + } + + /** + * @beta + * @private + * @internal + */ + _toProto(serializer: Serializer): api.IValue { + return { + arrayValue: { + values: this.exprs.map(p => p._toProto(serializer)!), + }, + }; + } + + /** + * @beta + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + this.exprs.forEach(expr => { + return expr._validateUserData(ignoreUndefinedProperties); + }); + } +} + +/** + * @beta + * Represents a reference to a field in a Firestore document, or outputs of a `Pipeline` stage. + * + *

Field references are used to access document field values in expressions and to specify fields + * for sorting, filtering, and projecting data in Firestore pipelines. + * + *

You can create a `Field` instance using the static `field` method: + * + * ```typescript + * // Create a Field instance for the 'name' field + * const nameField = field("name"); + * + * // Create a Field instance for a nested field 'address.city' + * const cityField = field("address.city"); + * ``` + */ +export class Field + extends Expression + implements firestore.Pipelines.Selectable +{ + readonly expressionType: firestore.Pipelines.ExpressionType = 'Field'; + selectable = true as const; + + /** + * @beta + * @internal + * @private + * @hideconstructor + * @param fieldPath + */ + constructor(private fieldPath: FieldPath) { + super(); + } + + get fieldName(): string { + return this.fieldPath.formattedName; + } + + get _alias(): string { + return this.fieldName; + } + + get _expr(): Expression { + return this; + } + + /** + * @beta + * @private + * @internal + */ + _toProto(_: Serializer): api.IValue { + return { + fieldReferenceValue: this.fieldPath.formattedName, + }; + } + + /** + * @beta + * @private + * @internal + */ + _validateUserData(_: boolean): void {} +} + +/** + * @beta + * Creates a `Field` instance representing the field at the given path. + * + * The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field + * (e.g., "address.city"). + * + * ```typescript + * // Create a Field instance for the 'title' field + * const titleField = field("title"); + * + * // Create a Field instance for a nested field 'author.firstName' + * const authorFirstNameField = field("author.firstName"); + * ``` + * + * @param field The path to the field. + * @returns A new `Field` instance representing the specified field. + */ +export function field(field: string | firestore.FieldPath): Field { + if (typeof field === 'string') { + if ('__name__' === field) { + return new Field(FieldPath.documentId()); + } + return new Field(FieldPath.fromArgument(field)); + } else { + return new Field(field as unknown as FieldPath); + } +} + +/** + * @beta + * @internal + * Represents a constant value that can be used in a Firestore pipeline expression. + * + * You can create a `Constant` instance using the static `field` method: + * + * ```typescript + * // Create a Constant instance for the number 10 + * const ten = constant(10); + * + * // Create a Constant instance for the string "hello" + * const hello = constant("hello"); + * ``` + */ +export class Constant extends Expression { + readonly expressionType: firestore.Pipelines.ExpressionType = 'Constant'; + + private protoValue?: api.IValue; + + /** + * @beta + * @private + * @internal + * @hideconstructor + * @param value The value of the constant. + */ + constructor(private value: unknown) { + super(); + } + + /** + * @beta + * @private + * @internal + */ + static _fromProto(value: api.IValue): Constant { + const result = new Constant(value); + result.protoValue = value; + return result; + } + + /** + * @beta + * @private + * @internal + */ + _toProto(serializer: Serializer): api.IValue { + if (isFirestoreValue(this.value)) { + return this.value; + } + + return serializer.encodeValue(this.value)!; + } + + /** + * @beta + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + validateUserInput('value', this.value, 'constant value', { + allowUndefined: ignoreUndefinedProperties, + allowDeletes: 'none', + allowTransforms: false, + }); + } +} + +/** + * @beta + * Creates an 'Expression' instance for a number value. + * + * @param value The number value. + * @returns A new `Expression` instance. + */ +export function constant(value: number): Expression; + +/** + * @beta + * Creates an 'Expression' instance for a string value. + * + * @param value The string value. + * @returns A new `Expression` instance. + */ +export function constant(value: string): Expression; + +/** + * @beta + * Creates an 'Expression' instance for a boolean value. + * + * @param value The boolean value. + * @returns A new `Expression` instance. + */ +export function constant(value: boolean): BooleanExpression; + +/** + * @beta + * Creates an 'Expression' instance for a null value. + * + * @param value The null value. + * @returns A new `Expression` instance. + */ +export function constant(value: null): Expression; + +/** + * @beta + * Creates an 'Expression' instance for a GeoPoint value. + * + * @param value The GeoPoint value. + * @returns A new `Expression` instance. + */ +export function constant(value: firestore.GeoPoint): Expression; + +/** + * @beta + * Creates an 'Expression' instance for a Timestamp value. + * + * @param value The Timestamp value. + * @returns A new `Expression` instance. + */ +export function constant(value: firestore.Timestamp): Expression; + +/** + * @beta + * Creates an 'Expression' instance for a Date value. + * + * @param value The Date value. + * @returns A new `Expression` instance. + */ +export function constant(value: Date): Expression; + +/** + * @beta + * Creates an 'Expression' instance for a Buffer | Uint8Array value. + * + * @param value The Buffer | Uint8Array value. + * @returns A new `Expression` instance. + */ +export function constant(value: Buffer | Uint8Array): Expression; + +/** + * @beta + * Creates an 'Expression' instance for a DocumentReference value. + * + * @param value The DocumentReference value. + * @returns A new `Expression` instance. + */ +export function constant(value: firestore.DocumentReference): Expression; + +/** + * @beta + * Creates an 'Expression' instance for a Firestore proto value. + * For internal use only. + * @private + * @internal + * @param value The Firestore proto value. + * @returns A new `Expression` instance. + */ +export function constant(value: api.IValue): Expression; + +/** + * @beta + * Creates an 'Expression' instance for a VectorValue value. + * + * @param value The VectorValue value. + * @returns A new `Expression` instance. + */ +export function constant(value: firestore.VectorValue): Expression; + +/** + * @beta + * @internal + * @private + * @param value + */ +export function constant(value: unknown): Expression; + +export function constant(value: unknown): Expression { + return _constant(value); +} + +export function _constant(value: unknown): Constant | BooleanExpression { + const c = new Constant(value); + if (typeof value === 'boolean') { + return new BooleanConstant(c); + } else { + return c; + } +} + +/** + * @beta + * Internal only + * @internal + * @private + */ +export class MapValue extends Expression { + constructor(private plainObject: Map) { + super(); + } + + expressionType: firestore.Pipelines.ExpressionType = 'Constant'; + + _toProto(serializer: Serializer): api.IValue { + return serializer.encodeValue(this.plainObject); + } + + /** + * @beta + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + this.plainObject.forEach(expr => { + return expr._validateUserData(ignoreUndefinedProperties); + }); + } +} + +/** + * @beta + * This class defines the base class for Firestore `Pipeline` functions, which can be evaluated within pipeline + * execution. + * + * Typically, you would not use this class or its children directly. Use either the functions like `and`, `equal`, + * or the methods on `Expression` ({@link Expression#equal}, {@link Expression#lessThan}, etc.) to construct new Function instances. + */ +export class FunctionExpression extends Expression { + readonly expressionType: firestore.Pipelines.ExpressionType = 'Function'; + + constructor( + public _methodName: string, + private params: Expression[], + ) { + super(); + } + + /** + * @beta + * @private + * @internal + */ + _toProto(serializer: Serializer): api.IValue { + return { + functionValue: { + name: this._methodName, + args: this.params.map(p => cast(p)._toProto(serializer)), + }, + }; + } + + /** + * @beta + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + this.params.forEach(expr => { + return expr._validateUserData(ignoreUndefinedProperties); + }); + } +} + +/** + * @beta + * This class defines the base class for Firestore `Pipeline` functions, which can be evaluated within pipeline + * execution. + * + * Typically, you would not use this class or its children directly. Use either the functions like `and`, `equal`, + * or the methods on `Expression` ({@link Expression#equal}, {@link Expression#lessThan}, etc.) to construct new Function instances. + */ +class MapFunctionExpr extends FunctionExpression { + readonly expressionType: firestore.Pipelines.ExpressionType = 'Function'; + + constructor(private map: Record) { + super('map', []); + } + + /** + * @beta + * @private + * @internal + */ + _toProto(serializer: Serializer): api.IValue { + const args: api.IValue[] = []; + for (const key in this.map) { + if (Object.prototype.hasOwnProperty.call(this.map, key)) { + if (this.map[key]) { + args.push(constant(key)._toProto(serializer)); + args.push(this.map[key]!._toProto(serializer)); + } + } + } + return { + functionValue: { + name: this._methodName, + args: args, + }, + }; + } + + /** + * @beta + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + validateUserInput('value', this.map, 'map value', { + allowUndefined: ignoreUndefinedProperties, + allowTransforms: false, + allowDeletes: 'none', + }); + } +} + +/** + * @beta + * This class defines the base class for Firestore `Pipeline` functions, which can be evaluated within pipeline + * execution. + * + * Typically, you would not use this class or its children directly. Use either the functions like `and`, `equal`, + * or the methods on `Expression` ({@link Expression#equal}, {@link Expression#lessThan}, etc.) to construct new Function instances. + */ +class ArrayFunctionExpr extends FunctionExpression { + readonly expressionType: firestore.Pipelines.ExpressionType = 'Function'; + + constructor(private values: Array) { + super('array', []); + } + + /** + * @beta + * @private + * @internal + */ + _toProto(serializer: Serializer): api.IValue { + return { + functionValue: { + name: this._methodName, + args: this.values + .filter(v => !!v) + .map(value => value!._toProto(serializer)), + }, + }; + } + + /** + * @beta + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + validateUserInput('value', this.values, 'array value', { + allowUndefined: ignoreUndefinedProperties, + allowTransforms: false, + allowDeletes: 'none', + }); + } +} + +/** + * @beta + * An expression that evaluates to a boolean value. + * + * This expression type is useful for filter conditions. + * + */ +export abstract class BooleanExpression + extends Expression + implements firestore.Pipelines.BooleanExpression +{ + abstract get _expr(): Expression; + + /** + * @beta + * Creates an aggregation that finds the count of input documents satisfying + * this boolean expression. + * + * ```typescript + * // Find the count of documents with a score greater than 90 + * field("score").greaterThan(90).countIf().as("highestScore"); + * ``` + * + * @returns A new `AggregateFunction` representing the 'countIf' aggregation. + */ + countIf(): AggregateFunction { + return new AggregateFunction('count_if', [this]); + } + + /** + * @beta + * Creates an expression that negates this boolean expression. + * + * ```typescript + * // Find documents where the 'tags' field does not contain 'completed' + * field("tags").arrayContains("completed").not(); + * ``` + * + * @returns A new `Expression` representing the negated filter condition. + */ + not(): BooleanExpression { + return new FunctionExpression('not', [this]).asBoolean(); + } + + /** + * @beta + * Creates a conditional expression that evaluates to the 'then' expression + * if `this` expression evaluates to `true`, + * or evaluates to the 'else' expression if `this` expressions evaluates `false`. + * + * ```typescript + * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". + * field("age").greaterThanOrEqual(18).conditional(constant("Adult"), constant("Minor")); + * ``` + * + * @param thenExpr The expression to evaluate if the condition is true. + * @param elseExpr The expression to evaluate if the condition is false. + * @returns A new `Expr` representing the conditional expression. + */ + conditional(thenExpr: Expression, elseExpr: Expression): FunctionExpression { + return new FunctionExpression('conditional', [this, thenExpr, elseExpr]); + } + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * ```typescript + * // Create an expression that protects against a divide by zero error + * // but always returns a boolean expression. + * constant(50).divide('length').gt(1).ifError(constant(false)); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @returns A new `Expr` representing the 'ifError' operation. + */ + ifError(catchValue: BooleanExpression): BooleanExpression; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * ```typescript + * // Create an expression that protects against a divide by zero error + * // but always returns a boolean expression. + * constant(50).divide('length').gt(1).ifError(false); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @returns A new `Expr` representing the 'ifError' operation. + */ + ifError(catchValue: boolean): BooleanExpression; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * ```typescript + * // Create an expression that protects against a divide by zero error. + * constant(50).divide('length').gt(1).ifError(constant(0)); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @returns A new `Expr` representing the 'ifError' operation. + */ + ifError(catchValue: Expression): FunctionExpression; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * ```typescript + * // Create an expression that protects against a divide by zero error. + * constant(50).divide('length').gt(1).ifError(0); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @returns A new `Expr` representing the 'ifError' operation. + */ + ifError(catchValue: unknown): FunctionExpression; + ifError(catchValue: unknown): unknown { + const normalizedCatchValue = valueToDefaultExpr(catchValue); + const expr = new FunctionExpression('if_error', [ + this, + normalizedCatchValue, + ]); + + return normalizedCatchValue instanceof BooleanExpression + ? expr.asBoolean() + : expr; + } + + _toProto(serializer: Serializer): api.IValue { + return this._expr._toProto(serializer); + } + + _validateUserData(ignoreUndefinedProperties: boolean): void { + this._expr._validateUserData(ignoreUndefinedProperties); + } +} + +export class BooleanFunctionExpression extends BooleanExpression { + readonly expressionType: firestore.Pipelines.ExpressionType = 'Function'; + constructor(readonly _expr: FunctionExpression) { + super(); + } +} + +export class BooleanConstant extends BooleanExpression { + readonly expressionType: firestore.Pipelines.ExpressionType = 'Constant'; + constructor(readonly _expr: Constant) { + super(); + } +} + +export class BooleanField extends BooleanExpression { + readonly expressionType: firestore.Pipelines.ExpressionType = 'Field'; + constructor(readonly _expr: Field) { + super(); + } +} + +/** + * @beta + * Creates an aggregation that counts the number of stage inputs where the provided + * boolean expression evaluates to true. + * + * ```typescript + * // Count the number of documents where 'is_active' field equals true + * countIf(field("is_active").equal(true)).as("numActiveDocuments"); + * ``` + * + * @param booleanExpr The boolean expression to evaluate on each input. + * @returns A new `AggregateFunction` representing the 'countIf' aggregation. + */ +export function countIf(booleanExpr: BooleanExpression): AggregateFunction { + return new AggregateFunction('count_if', [cast(booleanExpr)]); +} + +/** + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. + * + * ```typescript + * // Return the value in the tags field array at index 1. + * arrayGet('tags', 1); + * ``` + * + * @param arrayField The name of the array field. + * @param index The index of the element to return. + * @returns A new Expression representing the 'arrayGet' operation. + */ +export function arrayGet(arrayField: string, index: number): FunctionExpression; + +/** + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. + * + * ```typescript + * // Return the value in the tags field array at index specified by field + * // 'favoriteTag'. + * arrayGet('tags', field('favoriteTag')); + * ``` + * + * @param arrayField The name of the array field. + * @param indexExpr An Expression evaluating to the index of the element to return. + * @returns A new Expression representing the 'arrayGet' operation. + */ +export function arrayGet( + arrayField: string, + indexExpr: Expression, +): FunctionExpression; + +/** + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. + * + * ```typescript + * // Return the value in the tags field array at index 1. + * arrayGet(field('tags'), 1); + * ``` + * + * @param arrayExpression An Expression evaluating to an array. + * @param index The index of the element to return. + * @returns A new Expression representing the 'arrayGet' operation. + */ +export function arrayGet( + arrayExpression: Expression, + index: number, +): FunctionExpression; + +/** + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. + * + * ```typescript + * // Return the value in the tags field array at index specified by field + * // 'favoriteTag'. + * arrayGet(field('tags'), field('favoriteTag')); + * ``` + * + * @param arrayExpression An Expression evaluating to an array. + * @param indexExpr An Expression evaluating to the index of the element to return. + * @returns A new Expression representing the 'arrayGet' operation. + */ +export function arrayGet( + arrayExpression: Expression, + indexExpr: Expression, +): FunctionExpression; +export function arrayGet( + array: Expression | string, + index: Expression | number, +): FunctionExpression { + return fieldOrExpression(array).arrayGet(valueToDefaultExpr(index)); +} + +/** + * @beta + * Creates an expression that checks if a given expression produces an error. + * + * ```typescript + * // Check if the result of a calculation is an error + * isError(field("title").arrayContains(1)); + * ``` + * + * @param value The expression to check. + * @returns A new `Expression` representing the 'isError' check. + */ +export function isError(value: Expression): BooleanExpression { + const expr: Expression = cast(value); + return expr.isError(); +} + +/** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of the `try` argument evaluation. + * + * This overload is useful when a BooleanExpression is required. + * + * ```typescript + * // Create an expression that protects against a divide by zero error + * // but always returns a boolean expression. + * ifError(constant(50).divide('length').gt(1), constant(false)); + * ``` + * + * @param tryExpr The try expression. + * @param catchExpr The catch expression that will be evaluated and + * returned if the tryExpr produces an error. + * @returns A new `Expr` representing the 'ifError' operation. + */ +export function ifError( + tryExpr: BooleanExpression, + catchExpr: BooleanExpression, +): BooleanExpression; + +/** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of the `try` argument evaluation. + * + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // the entire title field if the array is empty or the field is another type. + * ifError(field("title").arrayGet(0), field("title")); + * ``` + * + * @param tryExpr The try expression. + * @param catchExpr The catch expression that will be evaluated and + * returned if the tryExpr produces an error. + * @returns A new `Expression` representing the 'ifError' operation. + */ +export function ifError( + tryExpr: Expression, + catchExpr: Expression, +): FunctionExpression; + +/** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of the `try` argument evaluation. + * + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // "Default Title" + * ifError(field("title").arrayGet(0), "Default Title"); + * ``` + * + * @param tryExpr The try expression. + * @param catchValue The value that will be returned if the tryExpr produces an + * error. + * @returns A new `Expression` representing the 'ifError' operation. + */ +export function ifError( + tryExpr: Expression, + catchValue: unknown, +): FunctionExpression; + +export function ifError( + tryExpr: Expression, + catchValue: unknown, +): FunctionExpression | BooleanExpression { + if ( + tryExpr instanceof BooleanExpression && + catchValue instanceof BooleanExpression + ) { + return tryExpr.ifError(catchValue).asBoolean(); + } else { + return tryExpr.ifError(valueToDefaultExpr(catchValue)); + } +} + +/** + * @beta + * Creates an expression that returns `true` if a value is absent. Otherwise, + * returns `false` even if the value is `null`. + * + * ```typescript + * // Check if the field `value` is absent. + * isAbsent(field("value")); + * ``` + * + * @param value The expression to check. + * @returns A new `Expression` representing the 'isAbsent' check. + */ +export function isAbsent(value: Expression): BooleanExpression; + +/** + * @beta + * Creates an expression that returns `true` if a field is absent. Otherwise, + * returns `false` even if the field value is `null`. + * + * ```typescript + * // Check if the field `value` is absent. + * isAbsent("value"); + * ``` + * + * @param field The field to check. + * @returns A new `Expression` representing the 'isAbsent' check. + */ +export function isAbsent(field: string): BooleanExpression; +export function isAbsent(value: Expression | string): BooleanExpression { + return fieldOrExpression(value).isAbsent(); +} + +/** + * @beta + * Creates an expression that removes a key from the map at the specified field name. + * + * ``` + * // Removes the key 'city' field from the map in the address field of the input document. + * mapRemove('address', 'city'); + * ``` + * + * @param mapField The name of a field containing a map value. + * @param key The name of the key to remove from the input map. + */ +export function mapRemove(mapField: string, key: string): FunctionExpression; +/** + * @beta + * Creates an expression that removes a key from the map produced by evaluating an expression. + * + * ``` + * // Removes the key 'baz' from the input map. + * mapRemove(map({foo: 'bar', baz: true}), 'baz'); + * ``` + * + * @param mapExpr An expression return a map value. + * @param key The name of the key to remove from the input map. + */ +export function mapRemove(mapExpr: Expression, key: string): FunctionExpression; +/** + * @beta + * Creates an expression that removes a key from the map at the specified field name. + * + * ``` + * // Removes the key 'city' field from the map in the address field of the input document. + * mapRemove('address', constant('city')); + * ``` + * + * @param mapField The name of a field containing a map value. + * @param keyExpr An expression that produces the name of the key to remove from the input map. + */ +export function mapRemove( + mapField: string, + keyExpr: Expression, +): FunctionExpression; +/** + * @beta + * Creates an expression that removes a key from the map produced by evaluating an expression. + * + * ``` + * // Removes the key 'baz' from the input map. + * mapRemove(map({foo: 'bar', baz: true}), constant('baz')); + * ``` + * + * @param mapExpr An expression return a map value. + * @param keyExpr An expression that produces the name of the key to remove from the input map. + */ +export function mapRemove( + mapExpr: Expression, + keyExpr: Expression, +): FunctionExpression; + +export function mapRemove( + mapExpr: Expression | string, + stringExpr: Expression | string, +): FunctionExpression { + return fieldOrExpression(mapExpr).mapRemove(valueToDefaultExpr(stringExpr)); +} + +/** + * @beta + * Creates an expression that merges multiple map values. + * + * ``` + * // Merges the map in the settings field with, a map literal, and a map in + * // that is conditionally returned by another expression + * mapMerge('settings', { enabled: true }, conditional(field('isAdmin'), { admin: true}, {}) + * ``` + * + * @param mapField Name of a field containing a map value that will be merged. + * @param secondMap A required second map to merge. Represented as a literal or + * an expression that returns a map. + * @param otherMaps Optional additional maps to merge. Each map is represented + * as a literal or an expression that returns a map. + */ +export function mapMerge( + mapField: string, + secondMap: Record | Expression, + ...otherMaps: Array | Expression> +): FunctionExpression; + +/** + * @beta + * Creates an expression that merges multiple map values. + * + * ``` + * // Merges the map in the settings field with, a map literal, and a map in + * // that is conditionally returned by another expression + * mapMerge(field('settings'), { enabled: true }, conditional(field('isAdmin'), { admin: true}, {}) + * ``` + * + * @param firstMap An expression or literal map value that will be merged. + * @param secondMap A required second map to merge. Represented as a literal or + * an expression that returns a map. + * @param otherMaps Optional additional maps to merge. Each map is represented + * as a literal or an expression that returns a map. + */ +export function mapMerge( + firstMap: Record | Expression, + secondMap: Record | Expression, + ...otherMaps: Array | Expression> +): FunctionExpression; + +export function mapMerge( + firstMap: string | Record | Expression, + secondMap: Record | Expression, + ...otherMaps: Array | Expression> +): FunctionExpression { + const secondMapExpr = valueToDefaultExpr(secondMap); + const otherMapExprs = otherMaps.map(valueToDefaultExpr); + return fieldOrExpression(firstMap).mapMerge(secondMapExpr, ...otherMapExprs); +} + +/** + * @beta + * + * Creates an expression that returns the document ID from a path. + * + * ```typescript + * // Get the document ID from a path. + * documentId(myDocumentReference); + * ``` + * + * @returns A new `Expr` representing the documentId operation. + */ +export function documentId( + documentPath: string | firestore.DocumentReference, +): FunctionExpression; + +/** + * @beta + * Creates an expression that returns the document ID from a path. + * + * ```typescript + * // Get the document ID from a path. + * documentId(field("__path__")); + * ``` + * + * @returns A new `Expression` representing the documentId operation. + */ +export function documentId(documentPathExpr: Expression): FunctionExpression; +export function documentId( + documentPath: Expression | string | firestore.DocumentReference, +): FunctionExpression { + const documentPathExpr = valueToDefaultExpr(documentPath); + return documentPathExpr.documentId(); +} + +/** + * @beta + * Creates an expression that returns a substring of a string or byte array. + * + * @param field The name of a field containing a string or byte array to compute the substring from. + * @param position Index of the first character of the substring. + * @param length Length of the substring. + */ +export function substring( + field: string, + position: number, + length?: number, +): FunctionExpression; + +/** + * @beta + * Creates an expression that returns a substring of a string or byte array. + * + * @param input An expression returning a string or byte array to compute the substring from. + * @param position Index of the first character of the substring. + * @param length Length of the substring. + */ +export function substring( + input: Expression, + position: number, + length?: number, +): FunctionExpression; + +/** + * @beta + * Creates an expression that returns a substring of a string or byte array. + * + * @param field The name of a field containing a string or byte array to compute the substring from. + * @param position An expression that returns the index of the first character of the substring. + * @param length An expression that returns the length of the substring. + */ +export function substring( + field: string, + position: Expression, + length?: Expression, +): FunctionExpression; + +/** + * @beta + * Creates an expression that returns a substring of a string or byte array. + * + * @param input An expression returning a string or byte array to compute the substring from. + * @param position An expression that returns the index of the first character of the substring. + * @param length An expression that returns the length of the substring. + */ +export function substring( + input: Expression, + position: Expression, + length?: Expression, +): FunctionExpression; + +export function substring( + field: Expression | string, + position: Expression | number, + length?: Expression | number, +): FunctionExpression { + const fieldExpr = fieldOrExpression(field); + const positionExpr = valueToDefaultExpr(position); + const lengthExpr = + length === undefined ? undefined : valueToDefaultExpr(length); + return fieldExpr.substring(positionExpr, lengthExpr); +} + +/** + * @beta + * Creates an expression that adds the result of two expressions together. + * + * ```typescript + * // Add the value of the 'quantity' field and the 'reserve' field. + * add(field("quantity"), field("reserve")); + * ``` + * + * @param first The first expression to add. + * @param second The second expression or literal to add. + * @returns A new `Expression` representing the addition operation. + */ +export function add( + first: Expression, + second: Expression | unknown, +): FunctionExpression; + +/** + * @beta + * Creates an expression that adds a field's value to the result of an expression. + * + * ```typescript + * // Add the value of the 'quantity' field and the 'reserve' field. + * add("quantity", field("reserve")); + * ``` + * + * @param fieldName The name of the field containing the value to add. + * @param second The second expression or literal to add. + * @returns A new `Expression` representing the addition operation. + */ +export function add( + fieldName: string, + second: Expression | unknown, +): FunctionExpression; + +export function add( + first: Expression | string, + second: Expression | unknown, +): FunctionExpression { + return fieldOrExpression(first).add(valueToDefaultExpr(second)); +} + +/** + * @beta + * Creates an expression that subtracts two expressions. + * + * ```typescript + * // Subtract the 'discount' field from the 'price' field + * subtract(field("price"), field("discount")); + * ``` + * + * @param minuend The expression to subtract from. + * @param subtrahend The expression to subtract. + * @returns A new `Expression` representing the subtraction operation. + */ +export function subtract( + minuend: Expression, + subtrahend: Expression, +): FunctionExpression; + +/** + * @beta + * Creates an expression that subtracts a constant value from an expression. + * + * ```typescript + * // Subtract the constant value 2 from the 'value' field + * subtract(field("value"), 2); + * ``` + * + * @param minuend The expression to subtract from. + * @param subtrahend The constant value to subtract. + * @returns A new `Expression` representing the subtraction operation. + */ +export function subtract( + minuend: Expression, + subtrahend: unknown, +): FunctionExpression; + +/** + * @beta + * Creates an expression that subtracts an expression from a field's value. + * + * ```typescript + * // Subtract the 'discount' field from the 'price' field + * subtract("price", field("discount")); + * ``` + * + * @param minuendFieldName The field name to subtract from. + * @param subtrahend The expression to subtract. + * @returns A new `Expression` representing the subtraction operation. + */ +export function subtract( + minuendFieldName: string, + subtrahend: Expression, +): FunctionExpression; + +/** + * @beta + * Creates an expression that subtracts a constant value from a field's value. + * + * ```typescript + * // Subtract 20 from the value of the 'total' field + * subtract("total", 20); + * ``` + * + * @param minuendFieldName The field name to subtract from. + * @param subtrahend The constant value to subtract. + * @returns A new `Expression` representing the subtraction operation. + */ +export function subtract( + minuendFieldName: string, + subtrahend: unknown, +): FunctionExpression; +export function subtract( + left: Expression | string, + right: Expression | unknown, +): FunctionExpression { + const normalizedLeft = fieldOrExpression(left); + const normalizedRight = valueToDefaultExpr(right); + return normalizedLeft.subtract(normalizedRight); +} + +/** + * @beta + * Creates an expression that multiplies the result of two expressions together. + * + * ```typescript + * // Multiply the 'quantity' field by the 'price' field + * multiply(field("quantity"), field("price")); + * ``` + * + * @param first The first expression to multiply. + * @param second The second expression or literal to multiply. + * @returns A new `Expression` representing the multiplication operation. + */ +export function multiply( + first: Expression, + second: Expression | unknown, +): FunctionExpression; + +/** + * @beta + * Creates an expression that multiplies a field's value by the result of an expression. + * + * ```typescript + * // Multiply the 'quantity' field by the 'price' field + * multiply("quantity", field("price")); + * ``` + * + * @param fieldName The name of the field containing the value to multiply. + * @param second The second expression or literal to multiply. + * @returns A new `Expression` representing the multiplication operation. + */ +export function multiply( + fieldName: string, + second: Expression | unknown, +): FunctionExpression; + +export function multiply( + first: Expression | string, + second: Expression | unknown, +): FunctionExpression { + return fieldOrExpression(first).multiply(valueToDefaultExpr(second)); +} + +/** + * @beta + * Creates an expression that divides two expressions. + * + * ```typescript + * // Divide the 'total' field by the 'count' field + * divide(field("total"), field("count")); + * ``` + * + * @param dividend The expression to be divided. + * @param divisort The expression to divide by. + * @returns A new `Expression` representing the division operation. + */ +export function divide( + dividend: Expression, + divisort: Expression, +): FunctionExpression; + +/** + * @beta + * Creates an expression that divides an expression by a constant value. + * + * ```typescript + * // Divide the 'value' field by 10 + * divide(field("value"), 10); + * ``` + * + * @param dividend The expression to be divided. + * @param divisor The constant value to divide by. + * @returns A new `Expression` representing the division operation. + */ +export function divide( + dividend: Expression, + divisor: unknown, +): FunctionExpression; + +/** + * @beta + * Creates an expression that divides a field's value by an expression. + * + * ```typescript + * // Divide the 'total' field by the 'count' field + * divide("total", field("count")); + * ``` + * + * @param dividend The field name to be divided. + * @param divisor The expression to divide by. + * @returns A new `Expression` representing the division operation. + */ +export function divide( + dividend: string, + divisor: Expression, +): FunctionExpression; + +/** + * @beta + * Creates an expression that divides a field's value by a constant value. + * + * ```typescript + * // Divide the 'value' field by 10 + * divide("value", 10); + * ``` + * + * @param dividend The field name to be divided. + * @param divisor The constant value to divide by. + * @returns A new `Expression` representing the division operation. + */ +export function divide(dividend: string, divisor: unknown): FunctionExpression; +export function divide( + dividend: Expression | string, + divisor: Expression | unknown, +): FunctionExpression { + const normalizedLeft = fieldOrExpression(dividend); + const normalizedRight = valueToDefaultExpr(divisor); + return normalizedLeft.divide(normalizedRight); +} + +/** + * @beta + * Creates an expression that calculates the modulo (remainder) of dividing two expressions. + * + * ```typescript + * // Calculate the remainder of dividing 'field1' by 'field2'. + * mod(field("field1"), field("field2")); + * ``` + * + * @param left The dividend expression. + * @param right The divisor expression. + * @returns A new `Expression` representing the modulo operation. + */ +export function mod(left: Expression, right: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that calculates the modulo (remainder) of dividing an expression by a constant. + * + * ```typescript + * // Calculate the remainder of dividing 'field1' by 5. + * mod(field("field1"), 5); + * ``` + * + * @param expression The dividend expression. + * @param value The divisor constant. + * @returns A new `Expression` representing the modulo operation. + */ +export function mod(expression: Expression, value: unknown): FunctionExpression; + +/** + * @beta + * Creates an expression that calculates the modulo (remainder) of dividing a field's value by an expression. + * + * ```typescript + * // Calculate the remainder of dividing 'field1' by 'field2'. + * mod("field1", field("field2")); + * ``` + * + * @param fieldName The dividend field name. + * @param expression The divisor expression. + * @returns A new `Expression` representing the modulo operation. + */ +export function mod( + fieldName: string, + expression: Expression, +): FunctionExpression; + +/** + * @beta + * Creates an expression that calculates the modulo (remainder) of dividing a field's value by a constant. + * + * ```typescript + * // Calculate the remainder of dividing 'field1' by 5. + * mod("field1", 5); + * ``` + * + * @param fieldName The dividend field name. + * @param value The divisor constant. + * @returns A new `Expression` representing the modulo operation. + */ +export function mod(fieldName: string, value: unknown): FunctionExpression; +export function mod( + left: Expression | string, + right: Expression | unknown, +): FunctionExpression { + const normalizedLeft = fieldOrExpression(left); + const normalizedRight = valueToDefaultExpr(right); + return normalizedLeft.mod(normalizedRight); +} + +/** + * @beta + * Creates an expression that creates a Firestore map value from an input object. + * + * ```typescript + * // Create a map from the input object and reference the 'baz' field value from the input document. + * map({foo: 'bar', baz: field('baz')}).as('data'); + * ``` + * + * @param elements The input map to evaluate in the expression. + * @returns A new `Expression` representing the map function. + */ +export function map(elements: Record): FunctionExpression { + const result: Record = {}; + + for (const key in elements) { + if (Object.prototype.hasOwnProperty.call(elements, key)) { + result[key] = + elements[key] !== undefined + ? valueToDefaultExpr(elements[key]) + : undefined; + } + } + return new MapFunctionExpr(result); +} + +/** + * @beta + * Internal use only + * Converts a plainObject to a mapValue in the proto representation, + * rather than a functionValue+map that is the result of the map(...) function. + * This behaves different from constant(plainObject) because it + * traverses the input object, converts values in the object to expressions, + * and calls _readUserData on each of these expressions. + * @private + * @internal + * @param plainObject + */ +export function _mapValue(plainObject: Record): MapValue { + const result: Map = new Map(); + for (const key in plainObject) { + if (Object.prototype.hasOwnProperty.call(plainObject, key)) { + const value = plainObject[key]; + result.set(key, valueToDefaultExpr(value)); + } + } + return new MapValue(result); +} + +/** + * @beta + * Creates an expression that creates a Firestore array value from an input array. + * + * ```typescript + * // Create an array value from the input array and reference the 'baz' field value from the input document. + * array(['bar', field('baz')]).as('foo'); + * ``` + * + * @param elements The input array to evaluate in the expression. + * @returns A new `Expression` representing the array function. + */ +export function array(elements: unknown[]): FunctionExpression { + return new ArrayFunctionExpr( + elements.map(element => { + return element !== undefined ? valueToDefaultExpr(element) : undefined; + }), + ); +} + +/** + * @beta + * Creates an expression that checks if two expressions are equal. + * + * ```typescript + * // Check if the 'age' field is equal to an expression + * equal(field("age"), field("minAge").add(10)); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @returns A new `Expression` representing the equality comparison. + */ +export function equal(left: Expression, right: Expression): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if an expression is equal to a constant value. + * + * ```typescript + * // Check if the 'age' field is equal to 21 + * equal(field("age"), 21); + * ``` + * + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the equality comparison. + */ +export function equal( + expression: Expression, + value: unknown, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value is equal to an expression. + * + * ```typescript + * // Check if the 'age' field is equal to the 'limit' field + * equal("age", field("limit")); + * ``` + * + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @returns A new `Expression` representing the equality comparison. + */ +export function equal( + fieldName: string, + expression: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value is equal to a constant value. + * + * ```typescript + * // Check if the 'city' field is equal to string constant "London" + * equal("city", "London"); + * ``` + * + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the equality comparison. + */ +export function equal(fieldName: string, value: unknown): BooleanExpression; +export function equal( + left: Expression | string, + right: unknown, +): BooleanExpression { + const leftExpr = fieldOrExpression(left); + const rightExpr = valueToDefaultExpr(right); + return leftExpr.equal(rightExpr); +} + +/** + * @beta + * Creates an expression that checks if two expressions are not equal. + * + * ```typescript + * // Check if the 'status' field is not equal to field 'finalState' + * notEqual(field("status"), field("finalState")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @returns A new `Expression` representing the inequality comparison. + */ +export function notEqual( + left: Expression, + right: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if an expression is not equal to a constant value. + * + * ```typescript + * // Check if the 'status' field is not equal to "completed" + * notEqual(field("status"), "completed"); + * ``` + * + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the inequality comparison. + */ +export function notEqual( + expression: Expression, + value: unknown, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value is not equal to an expression. + * + * ```typescript + * // Check if the 'status' field is not equal to the value of 'expectedStatus' + * notEqual("status", field("expectedStatus")); + * ``` + * + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @returns A new `Expression` representing the inequality comparison. + */ +export function notEqual( + fieldName: string, + expression: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value is not equal to a constant value. + * + * ```typescript + * // Check if the 'country' field is not equal to "USA" + * notEqual("country", "USA"); + * ``` + * + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the inequality comparison. + */ +export function notEqual(fieldName: string, value: unknown): BooleanExpression; +export function notEqual( + left: Expression | string, + right: unknown, +): BooleanExpression { + const leftExpr = fieldOrExpression(left); + const rightExpr = valueToDefaultExpr(right); + return leftExpr.notEqual(rightExpr); +} + +/** + * @beta + * Creates an expression that checks if the first expression is less than the second expression. + * + * ```typescript + * // Check if the 'age' field is less than 30 + * lessThan(field("age"), field("limit")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @returns A new `Expression` representing the less than comparison. + */ +export function lessThan( + left: Expression, + right: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if an expression is less than a constant value. + * + * ```typescript + * // Check if the 'age' field is less than 30 + * lessThan(field("age"), 30); + * ``` + * + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the less than comparison. + */ +export function lessThan( + expression: Expression, + value: unknown, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value is less than an expression. + * + * ```typescript + * // Check if the 'age' field is less than the 'limit' field + * lessThan("age", field("limit")); + * ``` + * + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @returns A new `Expression` representing the less than comparison. + */ +export function lessThan( + fieldName: string, + expression: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value is less than a constant value. + * + * ```typescript + * // Check if the 'price' field is less than 50 + * lessThan("price", 50); + * ``` + * + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the less than comparison. + */ +export function lessThan(fieldName: string, value: unknown): BooleanExpression; +export function lessThan( + left: Expression | string, + right: unknown, +): BooleanExpression { + const leftExpr = fieldOrExpression(left); + const rightExpr = valueToDefaultExpr(right); + return leftExpr.lessThan(rightExpr); +} + +/** + * @beta + * Creates an expression that checks if the first expression is less than or equal to the second + * expression. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * lessThanOrEqual(field("quantity"), field("limit")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @returns A new `Expression` representing the less than or equal to comparison. + */ +export function lessThanOrEqual( + left: Expression, + right: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if an expression is less than or equal to a constant value. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * lessThanOrEqual(field("quantity"), 20); + * ``` + * + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the less than or equal to comparison. + */ +export function lessThanOrEqual( + expression: Expression, + value: unknown, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value is less than or equal to an expression. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to the 'limit' field + * lessThanOrEqual("quantity", field("limit")); + * ``` + * + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @returns A new `Expression` representing the less than or equal to comparison. + */ +export function lessThanOrEqual( + fieldName: string, + expression: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value is less than or equal to a constant value. + * + * ```typescript + * // Check if the 'score' field is less than or equal to 70 + * lessThanOrEqual("score", 70); + * ``` + * + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the less than or equal to comparison. + */ +export function lessThanOrEqual( + fieldName: string, + value: unknown, +): BooleanExpression; +export function lessThanOrEqual( + left: Expression | string, + right: unknown, +): BooleanExpression { + const leftExpr = fieldOrExpression(left); + const rightExpr = valueToDefaultExpr(right); + return leftExpr.lessThanOrEqual(rightExpr); +} + +/** + * @beta + * Creates an expression that checks if the first expression is greater than the second + * expression. + * + * ```typescript + * // Check if the 'age' field is greater than 18 + * greaterThan(field("age"), Constant(9).add(9)); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @returns A new `Expression` representing the greater than comparison. + */ +export function greaterThan( + left: Expression, + right: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if an expression is greater than a constant value. + * + * ```typescript + * // Check if the 'age' field is greater than 18 + * greaterThan(field("age"), 18); + * ``` + * + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the greater than comparison. + */ +export function greaterThan( + expression: Expression, + value: unknown, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value is greater than an expression. + * + * ```typescript + * // Check if the value of field 'age' is greater than the value of field 'limit' + * greaterThan("age", field("limit")); + * ``` + * + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @returns A new `Expression` representing the greater than comparison. + */ +export function greaterThan( + fieldName: string, + expression: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value is greater than a constant value. + * + * ```typescript + * // Check if the 'price' field is greater than 100 + * greaterThan("price", 100); + * ``` + * + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the greater than comparison. + */ +export function greaterThan( + fieldName: string, + value: unknown, +): BooleanExpression; +export function greaterThan( + left: Expression | string, + right: unknown, +): BooleanExpression { + const leftExpr = fieldOrExpression(left); + const rightExpr = valueToDefaultExpr(right); + return leftExpr.greaterThan(rightExpr); +} + +/** + * @beta + * Creates an expression that checks if the first expression is greater than or equal to the + * second expression. + * + * ```typescript + * // Check if the 'quantity' field is greater than or equal to the field "threshold" + * greaterThanOrEqual(field("quantity"), field("threshold")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @returns A new `Expression` representing the greater than or equal to comparison. + */ +export function greaterThanOrEqual( + left: Expression, + right: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if an expression is greater than or equal to a constant + * value. + * + * ```typescript + * // Check if the 'quantity' field is greater than or equal to 10 + * greaterThanOrEqual(field("quantity"), 10); + * ``` + * + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the greater than or equal to comparison. + */ +export function greaterThanOrEqual( + expression: Expression, + value: unknown, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value is greater than or equal to an expression. + * + * ```typescript + * // Check if the value of field 'age' is greater than or equal to the value of field 'limit' + * greaterThanOrEqual("age", field("limit")); + * ``` + * + * @param fieldName The field name to compare. + * @param value The expression to compare to. + * @returns A new `Expression` representing the greater than or equal to comparison. + */ +export function greaterThanOrEqual( + fieldName: string, + value: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value is greater than or equal to a constant + * value. + * + * ```typescript + * // Check if the 'score' field is greater than or equal to 80 + * greaterThanOrEqual("score", 80); + * ``` + * + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the greater than or equal to comparison. + */ +export function greaterThanOrEqual( + fieldName: string, + value: unknown, +): BooleanExpression; +export function greaterThanOrEqual( + left: Expression | string, + right: unknown, +): BooleanExpression { + const leftExpr = fieldOrExpression(left); + const rightExpr = valueToDefaultExpr(right); + return leftExpr.greaterThanOrEqual(rightExpr); +} + +/** + * @beta + * + * Creates an expression that concatenates an array expression with other arrays. + * + * ```typescript + * // Combine the 'items' array with two new item arrays + * arrayConcat(field("items"), [field("newItems"), field("otherItems")]); + * ``` + * + * @param firstArray The first array expression to concatenate to. + * @param secondArray The second array expression or array literal to concatenate to. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @returns A new `Expr` representing the concatenated array. + */ +export function arrayConcat( + firstArray: Expression, + secondArray: Expression | unknown[], + ...otherArrays: Array +): FunctionExpression; + +/** + * @beta + * + * Creates an expression that concatenates a field's array value with other arrays. + * + * ```typescript + * // Combine the 'items' array with two new item arrays + * arrayConcat("items", [field("newItems"), field("otherItems")]); + * ``` + * + * @param firstArrayField The first array to concatenate to. + * @param secondArray The second array expression or array literal to concatenate to. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @returns A new `Expr` representing the concatenated array. + */ +export function arrayConcat( + firstArrayField: string, + secondArray: Expression | unknown[], + ...otherArrays: Array +): FunctionExpression; + +export function arrayConcat( + firstArray: Expression | string, + secondArray: Expression | unknown[], + ...otherArrays: Array +): FunctionExpression { + const exprValues = otherArrays.map(element => valueToDefaultExpr(element)); + return fieldOrExpression(firstArray).arrayConcat( + fieldOrExpression(secondArray), + ...exprValues, + ); +} + +/** + * @beta + * Creates an expression that checks if an array expression contains a specific element. + * + * ```typescript + * // Check if the 'colors' array contains the value of field 'selectedColor' + * arrayContains(field("colors"), field("selectedColor")); + * ``` + * + * @param array The array expression to check. + * @param element The element to search for in the array. + * @returns A new `Expression` representing the 'array_contains' comparison. + */ +export function arrayContains( + array: Expression, + element: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if an array expression contains a specific element. + * + * ```typescript + * // Check if the 'colors' array contains "red" + * arrayContains(field("colors"), "red"); + * ``` + * + * @param array The array expression to check. + * @param element The element to search for in the array. + * @returns A new `Expression` representing the 'array_contains' comparison. + */ +export function arrayContains( + array: Expression, + element: unknown, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's array value contains a specific element. + * + * ```typescript + * // Check if the 'colors' array contains the value of field 'selectedColor' + * arrayContains("colors", field("selectedColor")); + * ``` + * + * @param fieldName The field name to check. + * @param element The element to search for in the array. + * @returns A new `Expression` representing the 'array_contains' comparison. + */ +export function arrayContains( + fieldName: string, + element: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's array value contains a specific value. + * + * ```typescript + * // Check if the 'colors' array contains "red" + * arrayContains("colors", "red"); + * ``` + * + * @param fieldName The field name to check. + * @param element The element to search for in the array. + * @returns A new `Expression` representing the 'array_contains' comparison. + */ +export function arrayContains( + fieldName: string, + element: unknown, +): BooleanExpression; +export function arrayContains( + array: Expression | string, + element: unknown, +): BooleanExpression { + const arrayExpr = fieldOrExpression(array); + const elementExpr = valueToDefaultExpr(element); + return arrayExpr.arrayContains(elementExpr); +} + +/** + * @beta + * Creates an expression that checks if an array expression contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "Science" + * arrayContainsAny(field("categories"), [field("cate1"), "Science"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @returns A new `Expression` representing the 'array_contains_any' comparison. + */ +export function arrayContainsAny( + array: Expression, + values: Array, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's array value contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * arrayContainsAny("categories", [field("cate1"), "Science"]); + * ``` + * + * @param fieldName The field name to check. + * @param values The elements to check for in the array. + * @returns A new `Expression` representing the 'array_contains_any' comparison. + */ +export function arrayContainsAny( + fieldName: string, + values: Array, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if an array expression contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "Science" + * arrayContainsAny(field("categories"), array([field("cate1"), "Science"])); + * ``` + * + * @param array The array expression to check. + * @param values An expression that evaluates to an array, whose elements to check for in the array. + * @returns A new `Expression` representing the 'array_contains_any' comparison. + */ +export function arrayContainsAny( + array: Expression, + values: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's array value contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * arrayContainsAny("categories", array([field("cate1"), "Science"])); + * ``` + * + * @param fieldName The field name to check. + * @param values An expression that evaluates to an array, whose elements to check for in the array field. + * @returns A new `Expression` representing the 'array_contains_any' comparison. + */ +export function arrayContainsAny( + fieldName: string, + values: Expression, +): BooleanExpression; +export function arrayContainsAny( + array: Expression | string, + values: unknown[] | Expression, +): BooleanExpression { + if (Array.isArray(values)) { + return fieldOrExpression(array).arrayContainsAny(values); + } else { + return fieldOrExpression(array).arrayContainsAny(values); + } +} + +/** + * @beta + * Creates an expression that checks if an array expression contains all the specified elements. + * + * ```typescript + * // Check if the "tags" array contains all of the values: "SciFi", "Adventure", and the value from field "tag1" + * arrayContainsAll(field("tags"), [field("tag1"), constant("SciFi"), "Adventure"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @returns A new `Expression` representing the 'array_contains_all' comparison. + */ +export function arrayContainsAll( + array: Expression, + values: Array, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's array value contains all the specified values or + * expressions. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1', the value "SciFi", and "Adventure" + * arrayContainsAll("tags", [field("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param fieldName The field name to check. + * @param values The elements to check for in the array. + * @returns A new `Expression` representing the 'array_contains_all' comparison. + */ +export function arrayContainsAll( + fieldName: string, + values: Array, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if an array expression contains all the specified elements. + * + * ```typescript + * // Check if the "tags" array contains all of the values: "SciFi", "Adventure", and the value from field "tag1" + * arrayContainsAll(field("tags"), [field("tag1"), constant("SciFi"), "Adventure"]); + * ``` + * + * @param array The array expression to check. + * @param arrayExpression The elements to check for in the array. + * @returns A new `Expression` representing the 'array_contains_all' comparison. + */ +export function arrayContainsAll( + array: Expression, + arrayExpression: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's array value contains all the specified values or + * expressions. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1', the value "SciFi", and "Adventure" + * arrayContainsAll("tags", [field("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param fieldName The field name to check. + * @param arrayExpression The elements to check for in the array. + * @returns A new `Expression` representing the 'array_contains_all' comparison. + */ +export function arrayContainsAll( + fieldName: string, + arrayExpression: Expression, +): BooleanExpression; +export function arrayContainsAll( + array: Expression | string, + values: unknown[] | Expression, +): BooleanExpression { + if (Array.isArray(values)) { + return fieldOrExpression(array).arrayContainsAll(values); + } else { + return fieldOrExpression(array).arrayContainsAll(values); + } +} + +/** + * @beta + * Creates an expression that calculates the length of an array in a specified field. + * + * ```typescript + * // Get the number of items in field 'cart' + * arrayLength('cart'); + * ``` + * + * @param fieldName The name of the field containing an array to calculate the length of. + * @returns A new `Expression` representing the length of the array. + */ +export function arrayLength(fieldName: string): FunctionExpression; + +/** + * @beta + * Creates an expression that calculates the length of an array expression. + * + * ```typescript + * // Get the number of items in the 'cart' array + * arrayLength(field("cart")); + * ``` + * + * @param array The array expression to calculate the length of. + * @returns A new `Expression` representing the length of the array. + */ +export function arrayLength(array: Expression): FunctionExpression; +export function arrayLength(array: Expression | string): FunctionExpression { + return fieldOrExpression(array).arrayLength(); +} + +/** + * @beta + * Creates an expression that checks if an expression, when evaluated, is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * equalAny(field("category"), [constant("Electronics"), field("primaryType")]); + * ``` + * + * @param expression The expression whose results to compare. + * @param values The values to check against. + * @returns A new `Expression` representing the 'IN' comparison. + */ +export function equalAny( + expression: Expression, + values: Array, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if an expression is equal to any of the provided values. + * + * ```typescript + * // Check if the 'category' field is set to a value in the disabledCategories field + * equalAny(field("category"), field('disabledCategories')); + * ``` + * + * @param expression The expression whose results to compare. + * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input. + * @returns A new `Expression` representing the 'IN' comparison. + */ +export function equalAny( + expression: Expression, + arrayExpression: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * equalAny("category", [constant("Electronics"), field("primaryType")]); + * ``` + * + * @param fieldName The field to compare. + * @param values The values to check against. + * @returns A new `Expression` representing the 'IN' comparison. + */ +export function equalAny( + fieldName: string, + values: Array, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * equalAny("category", ["Electronics", field("primaryType")]); + * ``` + * + * @param fieldName The field to compare. + * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input field. + * @returns A new `Expression` representing the 'IN' comparison. + */ +export function equalAny( + fieldName: string, + arrayExpression: Expression, +): BooleanExpression; +export function equalAny( + element: Expression | string, + values: unknown[] | Expression, +): BooleanExpression { + if (Array.isArray(values)) { + return fieldOrExpression(element).equalAny(values); + } else { + return fieldOrExpression(element).equalAny(values); + } +} + +/** + * @beta + * Creates an expression that checks if an expression is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notEqualAny(field("status"), ["pending", field("rejectedStatus")]); + * ``` + * + * @param element The expression to compare. + * @param values The values to check against. + * @returns A new `Expression` representing the 'NOT IN' comparison. + */ +export function notEqualAny( + element: Expression, + values: Array, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notEqualAny("status", [constant("pending"), field("rejectedStatus")]); + * ``` + * + * @param fieldName The field name to compare. + * @param values The values to check against. + * @returns A new `Expression` representing the 'NOT IN' comparison. + */ +export function notEqualAny( + fieldName: string, + values: Array, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if an expression is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of the field 'rejectedStatus' + * notEqualAny(field("status"), ["pending", field("rejectedStatus")]); + * ``` + * + * @param element The expression to compare. + * @param arrayExpression The values to check against. + * @returns A new `Expression` representing the 'NOT IN' comparison. + */ +export function notEqualAny( + element: Expression, + arrayExpression: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value is not equal to any of the values in the evaluated expression. + * + * ```typescript + * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' + * notEqualAny("status", field("rejectedStatuses")); + * ``` + * + * @param fieldName The field name to compare. + * @param arrayExpression The values to check against. + * @returns A new `Expression` representing the 'NOT IN' comparison. + */ +export function notEqualAny( + fieldName: string, + arrayExpression: Expression, +): BooleanExpression; + +export function notEqualAny( + element: Expression | string, + values: unknown[] | Expression, +): BooleanExpression { + if (Array.isArray(values)) { + return fieldOrExpression(element).notEqualAny(values); + } else { + return fieldOrExpression(element).notEqualAny(values); + } +} + +/** + * @beta + * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple BooleanExprs. + * + * ```typescript + * // Check if only one of the conditions is true: 'age' greater than 18, 'city' is "London", + * // or 'status' is "active". + * const condition = xor( + * greaterThan("age", 18), + * equal("city", "London"), + * equal("status", "active")); + * ``` + * + * @param first The first condition. + * @param second The second condition. + * @param additionalConditions Additional conditions to 'XOR' together. + * @returns A new `Expression` representing the logical 'XOR' operation. + */ +export function xor( + first: BooleanExpression, + second: BooleanExpression, + ...additionalConditions: BooleanExpression[] +): BooleanExpression { + return new FunctionExpression('xor', [ + first, + second, + ...additionalConditions, + ]).asBoolean(); +} + +/** + * @beta + * Creates a conditional expression that evaluates to a 'then' expression if a condition is true + * and an 'else' expression if the condition is false. + * + * ```typescript + * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". + * conditional( + * greaterThan("age", 18), constant("Adult"), constant("Minor")); + * ``` + * + * @param condition The condition to evaluate. + * @param thenExpr The expression to evaluate if the condition is true. + * @param elseExpr The expression to evaluate if the condition is false. + * @returns A new `Expression` representing the conditional expression. + */ +export function conditional( + condition: BooleanExpression, + thenExpr: Expression, + elseExpr: Expression, +): FunctionExpression { + return new FunctionExpression('conditional', [ + condition, + cast(thenExpr), + cast(elseExpr), + ]); +} + +/** + * @beta + * Creates an expression that negates a filter condition. + * + * ```typescript + * // Find documents where the 'completed' field is NOT true + * not(equal("completed", true)); + * ``` + * + * @param booleanExpr The filter condition to negate. + * @returns A new `Expression` representing the negated filter condition. + */ +export function not(booleanExpr: BooleanExpression): BooleanExpression { + return booleanExpr.not(); +} + +/** + * @beta + * Creates an expression that returns the largest value between multiple input + * expressions or literal values. Based on Firestore's value type ordering. + * + * ```typescript + * // Returns the largest value between the 'field1' field, the 'field2' field, + * // and 1000 + * logicalMaximum(field("field1"), field("field2"), 1000); + * ``` + * + * @param first The first operand expression. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @returns A new `Expression` representing the logical max operation. + */ +export function logicalMaximum( + first: Expression, + second: Expression | unknown, + ...others: Array +): FunctionExpression; + +/** + * @beta + * Creates an expression that returns the largest value between multiple input + * expressions or literal values. Based on Firestore's value type ordering. + * + * ```typescript + * // Returns the largest value between the 'field1' field, the 'field2' field, + * // and 1000. + * logicalMaximum("field1", field("field2"), 1000); + * ``` + * + * @param fieldName The first operand field name. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @returns A new `Expression` representing the logical max operation. + */ +export function logicalMaximum( + fieldName: string, + second: Expression | unknown, + ...others: Array +): FunctionExpression; + +export function logicalMaximum( + first: Expression | string, + second: Expression | unknown, + ...others: Array +): FunctionExpression { + return fieldOrExpression(first).logicalMaximum( + valueToDefaultExpr(second), + ...others.map(value => valueToDefaultExpr(value)), + ); +} + +/** + * @beta + * Creates an expression that returns the smallest value between multiple input + * expressions and literal values. Based on Firestore's value type ordering. + * + * ```typescript + * // Returns the smallest value between the 'field1' field, the 'field2' field, + * // and 1000. + * logicalMinimum(field("field1"), field("field2"), 1000); + * ``` + * + * @param first The first operand expression. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @returns A new `Expression` representing the logical min operation. + */ +export function logicalMinimum( + first: Expression, + second: Expression | unknown, + ...others: Array +): FunctionExpression; + +/** + * @beta + * Creates an expression that returns the smallest value between a field's value + * and other input expressions or literal values. + * Based on Firestore's value type ordering. + * + * ```typescript + * // Returns the smallest value between the 'field1' field, the 'field2' field, + * // and 1000. + * logicalMinimum("field1", field("field2"), 1000); + * ``` + * + * @param fieldName The first operand field name. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @returns A new `Expression` representing the logical min operation. + */ +export function logicalMinimum( + fieldName: string, + second: Expression | unknown, + ...others: Array +): FunctionExpression; + +export function logicalMinimum( + first: Expression | string, + second: Expression | unknown, + ...others: Array +): FunctionExpression { + return fieldOrExpression(first).logicalMinimum( + valueToDefaultExpr(second), + ...others.map(value => valueToDefaultExpr(value)), + ); +} + +/** + * @beta + * Creates an expression that checks if a field exists. + * + * ```typescript + * // Check if the document has a field named "phoneNumber" + * exists(field("phoneNumber")); + * ``` + * + * @param value An expression evaluates to the name of the field to check. + * @returns A new `Expression` representing the 'exists' check. + */ +export function exists(value: Expression): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field exists. + * + * ```typescript + * // Check if the document has a field named "phoneNumber" + * exists("phoneNumber"); + * ``` + * + * @param fieldName The field name to check. + * @returns A new `Expression` representing the 'exists' check. + */ +export function exists(fieldName: string): BooleanExpression; +export function exists(valueOrField: Expression | string): BooleanExpression { + return fieldOrExpression(valueOrField).exists(); +} + +/** + * @beta + * Creates an expression that reverses a string. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * reverse(field("myString")); + * ``` + * + * @param stringExpression An expression evaluating to a string value, which will be reversed. + * @returns A new `Expression` representing the reversed string. + */ +export function reverse(stringExpression: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that reverses a string value in the specified field. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * reverse("myString"); + * ``` + * + * @param field The name of the field representing the string to reverse. + * @returns A new `Expression` representing the reversed string. + */ +export function reverse(field: string): FunctionExpression; +export function reverse(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).reverse(); +} + +/** + * @beta + * Creates an expression that reverses an array. + * + * ```typescript + * // Reverse the value of the 'myArray' field. + * arrayReverse("myArray"); + * ``` + * + * @param fieldName The name of the field to reverse. + * @returns A new `Expression` representing the reversed array. + */ +export function arrayReverse(fieldName: string): FunctionExpression; + +/** + * @beta + * Creates an expression that reverses an array. + * + * ```typescript + * // Reverse the value of the 'myArray' field. + * arrayReverse(field("myArray")); + * ``` + * + * @param arrayExpression An expression evaluating to an array value, which will be reversed. + * @returns A new `Expression` representing the reversed array. + */ +export function arrayReverse(arrayExpression: Expression): FunctionExpression; +export function arrayReverse(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).arrayReverse(); +} + +/** + * @beta + * Creates an expression that calculates the byte length of a string in UTF-8, or just the length of a Blob. + * + * ```typescript + * // Calculate the length of the 'myString' field in bytes. + * byteLength(field("myString")); + * ``` + * + * @param expr The expression representing the string. + * @returns A new `Expression` representing the length of the string in bytes. + */ +export function byteLength(expr: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that calculates the length of a string represented by a field in UTF-8 bytes, or just the length of a Blob. + * + * ```typescript + * // Calculate the length of the 'myString' field in bytes. + * byteLength("myString"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @returns A new `Expression` representing the length of the string in bytes. + */ +export function byteLength(fieldName: string): FunctionExpression; +export function byteLength(expr: Expression | string): FunctionExpression { + const normalizedExpr = fieldOrExpression(expr); + return normalizedExpr.byteLength(); +} + +/** + * @beta + * Creates an expression that computes e to the power of the expression's result. + * + * ```typescript + * // Compute e to the power of 2. + * exp(constant(2)); + * ``` + * + * @returns A new `Expression` representing the exp of the numeric value. + */ +export function exp(expression: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that computes e to the power of the expression's result. + * + * ```typescript + * // Compute e to the power of the 'value' field. + * exp('value'); + * ``` + * + * @returns A new `Expression` representing the exp of the numeric value. + */ +export function exp(fieldName: string): FunctionExpression; + +export function exp( + expressionOrFieldName: Expression | string, +): FunctionExpression { + return fieldOrExpression(expressionOrFieldName).exp(); +} + +/** + * @beta + * Creates an expression that computes the ceiling of a numeric value. + * + * ```typescript + * // Compute the ceiling of the 'price' field. + * ceil("price"); + * ``` + * + * @param fieldName The name of the field to compute the ceiling of. + * @returns A new `Expression` representing the ceiling of the numeric value. + */ +export function ceil(fieldName: string): FunctionExpression; + +/** + * @beta + * Creates an expression that computes the ceiling of a numeric value. + * + * ```typescript + * // Compute the ceiling of the 'price' field. + * ceil(field("price")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the ceiling will be computed for. + * @returns A new `Expression` representing the ceiling of the numeric value. + */ +export function ceil(expression: Expression): FunctionExpression; +export function ceil(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).ceil(); +} + +/** + * @beta + * Creates an expression that computes the floor of a numeric value. + * + * @param expr The expression to compute the floor of. + * @returns A new `Expression` representing the floor of the numeric value. + */ +export function floor(expr: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that computes the floor of a numeric value. + * + * @param fieldName The name of the field to compute the floor of. + * @returns A new `Expression` representing the floor of the numeric value. + */ +export function floor(fieldName: string): FunctionExpression; +export function floor(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).floor(); +} + +/** + * @beta + * Creates an aggregation that counts the number of distinct values of a field. + * + * @param expr The expression or field to count distinct values of. + * @returns A new `AggregateFunction` representing the 'count_distinct' aggregation. + */ +export function countDistinct(expr: Expression | string): AggregateFunction { + return fieldOrExpression(expr).countDistinct(); +} + +/** + * @beta + * Creates an expression that calculates the character length of a string field in UTF8. + * + * ```typescript + * // Get the character length of the 'name' field in UTF-8. + * strLength("name"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @returns A new `Expression` representing the length of the string. + */ +export function charLength(fieldName: string): FunctionExpression; + +/** + * @beta + * Creates an expression that calculates the character length of a string expression in UTF-8. + * + * ```typescript + * // Get the character length of the 'name' field in UTF-8. + * strLength(field("name")); + * ``` + * + * @param stringExpression The expression representing the string to calculate the length of. + * @returns A new `Expression` representing the length of the string. + */ +export function charLength(stringExpression: Expression): FunctionExpression; +export function charLength(value: Expression | string): FunctionExpression { + const valueExpr = fieldOrExpression(value); + return valueExpr.charLength(); +} + +/** + * @beta + * Creates an expression that performs a case-sensitive wildcard string comparison against a + * field. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like("title", "%guide%"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @returns A new `Expression` representing the 'like' comparison. + */ +export function like(fieldName: string, pattern: string): BooleanExpression; + +/** + * @beta + * Creates an expression that performs a case-sensitive wildcard string comparison against a + * field. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like("title", field("pattern")); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @returns A new `Expression` representing the 'like' comparison. + */ +export function like(fieldName: string, pattern: Expression): BooleanExpression; + +/** + * @beta + * Creates an expression that performs a case-sensitive wildcard string comparison. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like(field("title"), "%guide%"); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @returns A new `Expression` representing the 'like' comparison. + */ +export function like( + stringExpression: Expression, + pattern: string, +): BooleanExpression; + +/** + * @beta + * Creates an expression that performs a case-sensitive wildcard string comparison. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like(field("title"), field("pattern")); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @returns A new `Expression` representing the 'like' comparison. + */ +export function like( + stringExpression: Expression, + pattern: Expression, +): BooleanExpression; +export function like( + left: Expression | string, + pattern: Expression | string, +): BooleanExpression { + const leftExpr = fieldOrExpression(left); + const patternExpr = valueToDefaultExpr(pattern); + return leftExpr.like(patternExpr); +} + +/** + * @beta + * Creates an expression that checks if a string field contains a specified regular expression as + * a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains("description", "(?i)example"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The regular expression to use for the search. + * @returns A new `Expression` representing the 'contains' comparison. + */ +export function regexContains( + fieldName: string, + pattern: string, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a string field contains a specified regular expression as + * a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains("description", field("pattern")); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The regular expression to use for the search. + * @returns A new `Expression` representing the 'contains' comparison. + */ +export function regexContains( + fieldName: string, + pattern: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a string expression contains a specified regular + * expression as a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains(field("description"), "(?i)example"); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param pattern The regular expression to use for the search. + * @returns A new `Expression` representing the 'contains' comparison. + */ +export function regexContains( + stringExpression: Expression, + pattern: string, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a string expression contains a specified regular + * expression as a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains(field("description"), field("pattern")); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param pattern The regular expression to use for the search. + * @returns A new `Expression` representing the 'contains' comparison. + */ +export function regexContains( + stringExpression: Expression, + pattern: Expression, +): BooleanExpression; +export function regexContains( + left: Expression | string, + pattern: Expression | string, +): BooleanExpression { + const leftExpr = fieldOrExpression(left); + const patternExpr = valueToDefaultExpr(pattern); + return leftExpr.regexContains(patternExpr); +} + +/** + * @beta + * + * Creates an expression that returns the first substring of a string field that matches a + * specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract the domain name from an email field + * regexFind("email", "@[A-Za-z0-9.-]+"); + * ``` + * + * @param fieldName The name of the field containing the string to search. + * @param pattern The regular expression to search for. + * @returns A new `Expression` representing the regular expression find function. + */ +export function regexFind( + fieldName: string, + pattern: string, +): FunctionExpression; + +/** + * @beta + * + * Creates an expression that returns the first substring of a string field that matches a + * specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract a substring from 'email' based on a pattern stored in another field + * regexFind("email", field("pattern")); + * ``` + * + * @param fieldName The name of the field containing the string to search. + * @param pattern The regular expression to search for. + * @returns A new `Expression` representing the regular expression find function. + */ +export function regexFind( + fieldName: string, + pattern: Expression, +): FunctionExpression; + +/** + * @beta + * + * Creates an expression that returns the first substring of a string expression that matches + * a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract the domain from a lower-cased email address + * regexFind(field("email"), "@[A-Za-z0-9.-]+"); + * ``` + * + * @param stringExpression The expression representing the string to search. + * @param pattern The regular expression to search for. + * @returns A new `Expression` representing the regular expression find function. + */ +export function regexFind( + stringExpression: Expression, + pattern: string, +): FunctionExpression; + +/** + * @beta + * + * Creates an expression that returns the first substring of a string expression that matches + * a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract a substring based on a dynamic pattern field + * regexFind(field("email"), field("pattern")); + * ``` + * + * @param stringExpression The expression representing the string to search. + * @param pattern The regular expression to search for. + * @returns A new `Expression` representing the regular expression find function. + */ +export function regexFind( + stringExpression: Expression, + pattern: Expression, +): FunctionExpression; +export function regexFind( + left: Expression | string, + pattern: Expression | string, +): FunctionExpression { + const leftExpr = fieldOrExpression(left); + const patternExpr = valueToDefaultExpr(pattern); + return leftExpr.regexFind(patternExpr); +} + +/** + * @beta + * + * Creates an expression that evaluates to a list of all substrings in a string field that + * match a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract all hashtags from a post content field + * regexFindAll("content", "#[A-Za-z0-9_]+"); + * ``` + * + * @param fieldName The name of the field containing the string to search. + * @param pattern The regular expression to search for. + * @returns A new `Expression` that evaluates to an array of matched substrings. + */ +export function regexFindAll( + fieldName: string, + pattern: string, +): FunctionExpression; + +/** + * @beta + * + * Creates an expression that evaluates to a list of all substrings in a string field that + * match a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract all matches from 'content' based on a pattern stored in another field + * regexFindAll("content", field("pattern")); + * ``` + * + * @param fieldName The name of the field containing the string to search. + * @param pattern The regular expression to search for. + * @returns A new `Expression` that evaluates to an array of matched substrings. + */ +export function regexFindAll( + fieldName: string, + pattern: Expression, +): FunctionExpression; + +/** + * @beta + * + * Creates an expression that evaluates to a list of all substrings in a string expression + * that match a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract all mentions from a lower-cased comment + * regexFindAll(field("comment"), "@[A-Za-z0-9_]+"); + * ``` + * + * @param stringExpression The expression representing the string to search. + * @param pattern The regular expression to search for. + * @returns A new `Expression` that evaluates to an array of matched substrings. + */ +export function regexFindAll( + stringExpression: Expression, + pattern: string, +): FunctionExpression; + +/** + * @beta + * + * Creates an expression that evaluates to a list of all substrings in a string expression + * that match a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract all matches based on a dynamic pattern expression + * regexFindAll(field("comment"), field("pattern")); + * ``` + * + * @param stringExpression The expression representing the string to search. + * @param pattern The regular expression to search for. + * @returns A new `Expression` that evaluates to an array of matched substrings. + */ +export function regexFindAll( + stringExpression: Expression, + pattern: Expression, +): FunctionExpression; +export function regexFindAll( + left: Expression | string, + pattern: Expression | string, +): FunctionExpression { + const leftExpr = fieldOrExpression(left); + const patternExpr = valueToDefaultExpr(pattern); + return leftExpr.regexFindAll(patternExpr); +} + +/** + * @beta + * Creates an expression that checks if a string field matches a specified regular expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch("email", "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The regular expression to use for the match. + * @returns A new `Expression` representing the regular expression match. + */ +export function regexMatch( + fieldName: string, + pattern: string, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a string field matches a specified regular expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch("email", field("pattern")); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The regular expression to use for the match. + * @returns A new `Expression` representing the regular expression match. + */ +export function regexMatch( + fieldName: string, + pattern: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a string expression matches a specified regular + * expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch(field("email"), "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * ``` + * + * @param stringExpression The expression representing the string to match against. + * @param pattern The regular expression to use for the match. + * @returns A new `Expression` representing the regular expression match. + */ +export function regexMatch( + stringExpression: Expression, + pattern: string, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a string expression matches a specified regular + * expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch(field("email"), field("pattern")); + * ``` + * + * @param stringExpression The expression representing the string to match against. + * @param pattern The regular expression to use for the match. + * @returns A new `Expression` representing the regular expression match. + */ +export function regexMatch( + stringExpression: Expression, + pattern: Expression, +): BooleanExpression; +export function regexMatch( + left: Expression | string, + pattern: Expression | string, +): BooleanExpression { + const leftExpr = fieldOrExpression(left); + const patternExpr = valueToDefaultExpr(pattern); + return leftExpr.regexMatch(patternExpr); +} + +/** + * @beta + * Creates an expression that checks if a string field contains a specified substring. + * + * ```typescript + * // Check if the 'description' field contains "example". + * stringContains("description", "example"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param substring The substring to search for. + * @returns A new `Expression` representing the 'contains' comparison. + */ +export function stringContains( + fieldName: string, + substring: string, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a string field contains a substring specified by an expression. + * + * ```typescript + * // Check if the 'description' field contains the value of the 'keyword' field. + * stringContains("description", field("keyword")); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param substring The expression representing the substring to search for. + * @returns A new `Expression` representing the 'contains' comparison. + */ +export function stringContains( + fieldName: string, + substring: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a string expression contains a specified substring. + * + * ```typescript + * // Check if the 'description' field contains "example". + * stringContains(field("description"), "example"); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param substring The substring to search for. + * @returns A new `Expression` representing the 'contains' comparison. + */ +export function stringContains( + stringExpression: Expression, + substring: string, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a string expression contains a substring specified by another expression. + * + * ```typescript + * // Check if the 'description' field contains the value of the 'keyword' field. + * stringContains(field("description"), field("keyword")); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param substring The expression representing the substring to search for. + * @returns A new `Expression` representing the 'contains' comparison. + */ +export function stringContains( + stringExpression: Expression, + substring: Expression, +): BooleanExpression; +export function stringContains( + left: Expression | string, + substring: Expression | string, +): BooleanExpression { + const leftExpr = fieldOrExpression(left); + const substringExpr = valueToDefaultExpr(substring); + return leftExpr.stringContains(substringExpr); +} + +/** + * @beta + * Creates an expression that checks if a field's value starts with a given prefix. + * + * ```typescript + * // Check if the 'name' field starts with "Mr." + * startsWith("name", "Mr."); + * ``` + * + * @param fieldName The field name to check. + * @param prefix The prefix to check for. + * @returns A new `Expression` representing the 'starts with' comparison. + */ +export function startsWith( + fieldName: string, + prefix: string, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value starts with a given prefix. + * + * ```typescript + * // Check if the 'fullName' field starts with the value of the 'firstName' field + * startsWith("fullName", field("firstName")); + * ``` + * + * @param fieldName The field name to check. + * @param prefix The expression representing the prefix. + * @returns A new `Expression` representing the 'starts with' comparison. + */ +export function startsWith( + fieldName: string, + prefix: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a string expression starts with a given prefix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." + * startsWith(field("fullName"), "Mr."); + * ``` + * + * @param stringExpression The expression to check. + * @param prefix The prefix to check for. + * @returns A new `Expression` representing the 'starts with' comparison. + */ +export function startsWith( + stringExpression: Expression, + prefix: string, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a string expression starts with a given prefix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." + * startsWith(field("fullName"), field("prefix")); + * ``` + * + * @param stringExpression The expression to check. + * @param prefix The prefix to check for. + * @returns A new `Expression` representing the 'starts with' comparison. + */ +export function startsWith( + stringExpression: Expression, + prefix: Expression, +): BooleanExpression; +export function startsWith( + expr: Expression | string, + prefix: Expression | string, +): BooleanExpression { + return fieldOrExpression(expr).startsWith(valueToDefaultExpr(prefix)); +} + +/** + * @beta + * Creates an expression that checks if a field's value ends with a given postfix. + * + * ```typescript + * // Check if the 'filename' field ends with ".txt" + * endsWith("filename", ".txt"); + * ``` + * + * @param fieldName The field name to check. + * @param suffix The postfix to check for. + * @returns A new `Expression` representing the 'ends with' comparison. + */ +export function endsWith(fieldName: string, suffix: string): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a field's value ends with a given postfix. + * + * ```typescript + * // Check if the 'url' field ends with the value of the 'extension' field + * endsWith("url", field("extension")); + * ``` + * + * @param fieldName The field name to check. + * @param suffix The expression representing the postfix. + * @returns A new `Expression` representing the 'ends with' comparison. + */ +export function endsWith( + fieldName: string, + suffix: Expression, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a string expression ends with a given postfix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." + * endsWith(field("fullName"), "Jr."); + * ``` + * + * @param stringExpression The expression to check. + * @param suffix The postfix to check for. + * @returns A new `Expression` representing the 'ends with' comparison. + */ +export function endsWith( + stringExpression: Expression, + suffix: string, +): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if a string expression ends with a given postfix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." + * endsWith(field("fullName"), constant("Jr.")); + * ``` + * + * @param stringExpression The expression to check. + * @param suffix The postfix to check for. + * @returns A new `Expression` representing the 'ends with' comparison. + */ +export function endsWith( + stringExpression: Expression, + suffix: Expression, +): BooleanExpression; +export function endsWith( + expr: Expression | string, + suffix: Expression | string, +): BooleanExpression { + return fieldOrExpression(expr).endsWith(valueToDefaultExpr(suffix)); +} + +/** + * @beta + * Creates an expression that converts a string field to lowercase. + * + * ```typescript + * // Convert the 'name' field to lowercase + * toLower("name"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @returns A new `Expression` representing the lowercase string. + */ +export function toLower(fieldName: string): FunctionExpression; + +/** + * @beta + * Creates an expression that converts a string expression to lowercase. + * + * ```typescript + * // Convert the 'name' field to lowercase + * toLower(field("name")); + * ``` + * + * @param stringExpression The expression representing the string to convert to lowercase. + * @returns A new `Expression` representing the lowercase string. + */ +export function toLower(stringExpression: Expression): FunctionExpression; +export function toLower(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).toLower(); +} + +/** + * @beta + * Creates an expression that converts a string field to uppercase. + * + * ```typescript + * // Convert the 'title' field to uppercase + * toUpper("title"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @returns A new `Expression` representing the uppercase string. + */ +export function toUpper(fieldName: string): FunctionExpression; + +/** + * @beta + * Creates an expression that converts a string expression to uppercase. + * + * ```typescript + * // Convert the 'title' field to uppercase + * toUppercase(field("title")); + * ``` + * + * @param stringExpression The expression representing the string to convert to uppercase. + * @returns A new `Expression` representing the uppercase string. + */ +export function toUpper(stringExpression: Expression): FunctionExpression; +export function toUpper(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).toUpper(); +} + +/** + * @beta + * + * Creates an expression that removes leading and trailing whitespace from a string or byte array. + * + * ```typescript + * // Trim whitespace from the 'userInput' field + * trim("userInput"); + * + * // Trim quotes from the 'userInput' field + * trim("userInput", '"'); + * ``` + * + * @param fieldName The name of the field containing the string or byte array. + * @param valueToTrim Optional This parameter is treated as a set of characters or bytes that will be + * trimmed from the input. If not specified, then whitespace will be trimmed. + * @returns A new `Expr` representing the trimmed string. + */ +export function trim( + fieldName: string, + valueToTrim?: string | Expression, +): FunctionExpression; + +/** + * @beta + * + * Creates an expression that removes leading and trailing characters from a string or byte array expression. + * + * ```typescript + * // Trim whitespace from the 'userInput' field + * trim(field("userInput")); + * + * // Trim quotes from the 'userInput' field + * trim(field("userInput"), '"'); + * ``` + * + * @param stringExpression The expression representing the string or byte array to trim. + * @param valueToTrim Optional This parameter is treated as a set of characters or bytes that will be + * trimmed from the input. If not specified, then whitespace will be trimmed. + * @returns A new `Expr` representing the trimmed string or byte array. + */ +export function trim( + stringExpression: Expression, + valueToTrim?: string | Expression, +): FunctionExpression; +export function trim( + expr: Expression | string, + valueToTrim?: string | Expression, +): FunctionExpression { + return fieldOrExpression(expr).trim(valueToTrim); +} + +/** + * @beta + * Creates an expression that concatenates string functions, fields or constants together. + * + * ```typescript + * // Combine the 'firstName', " ", and 'lastName' fields into a single string + * stringConcat("firstName", " ", field("lastName")); + * ``` + * + * @param fieldName The field name containing the initial string value. + * @param secondString An expression or string literal to concatenate. + * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. + * @returns A new `Expression` representing the concatenated string. + */ +export function stringConcat( + fieldName: string, + secondString: Expression | string, + ...otherStrings: Array +): FunctionExpression; + +/** + * @beta + * Creates an expression that concatenates string expressions together. + * + * ```typescript + * // Combine the 'firstName', " ", and 'lastName' fields into a single string + * stringConcat(field("firstName"), " ", field("lastName")); + * ``` + * + * @param firstString The initial string expression to concatenate to. + * @param secondString An expression or string literal to concatenate. + * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. + * @returns A new `Expression` representing the concatenated string. + */ +export function stringConcat( + firstString: Expression, + secondString: Expression | string, + ...otherStrings: Array +): FunctionExpression; +export function stringConcat( + first: string | Expression, + second: string | Expression, + ...elements: Array +): FunctionExpression { + return fieldOrExpression(first).stringConcat( + valueToDefaultExpr(second), + ...elements.map(valueToDefaultExpr), + ); +} + +/** + * @beta + * Accesses a value from a map (object) field using the provided key. + * + * ```typescript + * // Get the 'city' value from the 'address' map field + * mapGet("address", "city"); + * ``` + * + * @param fieldName The field name of the map field. + * @param subField The key to access in the map. + * @returns A new `Expression` representing the value associated with the given key in the map. + */ +export function mapGet(fieldName: string, subField: string): FunctionExpression; + +/** + * @beta + * Accesses a value from a map (object) expression using the provided key. + * + * ```typescript + * // Get the 'city' value from the 'address' map field + * mapGet(field("address"), "city"); + * ``` + * + * @param mapExpression The expression representing the map. + * @param subField The key to access in the map. + * @returns A new `Expression` representing the value associated with the given key in the map. + */ +export function mapGet( + mapExpression: Expression, + subField: string, +): FunctionExpression; +export function mapGet( + fieldOrExpr: string | Expression, + subField: string, +): FunctionExpression { + return fieldOrExpression(fieldOrExpr).mapGet(subField); +} + +/** + * @beta + * Creates an expression that returns a new map with the specified entries added or updated. + * + * @remarks + * This only performs shallow updates to the map. Setting a value to `null` + * will retain the key with a `null` value. To remove a key entirely, use `mapRemove`. + * + * @example + * ```typescript + * // Set the 'city' to 'San Francisco' in the 'address' map field + * mapSet("address", "city", "San Francisco"); + * ``` + * + * @param mapField The map field to set entries in. + * @param key The key to set. Must be a string or a constant string expression. + * @param value The value to set. + * @param moreKeyValues Additional key-value pairs to set. + * @returns A new `Expression` representing the map with the entries set. + */ +export function mapSet( + mapField: string, + key: string | Expression, + value: unknown, + ...moreKeyValues: unknown[] +): FunctionExpression; + +/** + * @beta + * Creates an expression that returns a new map with the specified entries added or updated. + * + * @remarks + * This only performs shallow updates to the map. Setting a value to `null` + * will retain the key with a `null` value. To remove a key entirely, use `mapRemove`. + * + * @example + * ```typescript + * // Set the 'city' to "San Francisco" + * mapSet(map({"state": "California"}), "city", "San Francisco"); + * ``` + * + * @param mapExpression The expression representing the map. + * @param key The key to set. Must be a string or a constant string expression. + * @param value The value to set. + * @param moreKeyValues Additional key-value pairs to set. + * @returns A new `Expression` representing the map with the entries set. + */ +export function mapSet( + mapExpression: Expression, + key: string | Expression, + value: unknown, + ...moreKeyValues: unknown[] +): FunctionExpression; +export function mapSet( + fieldOrExpr: string | Expression, + key: string | Expression, + value: unknown, + ...moreKeyValues: unknown[] +): FunctionExpression { + return fieldOrExpression(fieldOrExpr).mapSet(key, value, ...moreKeyValues); +} + +/** + * @beta + * Creates an expression that returns the keys of a map. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the keys of the 'address' map field + * mapKeys("address"); + * ``` + * + * @param mapField The map field to get the keys of. + * @returns A new `Expression` representing the keys of the map. + */ +export function mapKeys(mapField: string): FunctionExpression; + +/** + * @beta + * Creates an expression that returns the keys of a map. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the keys of the map expression + * mapKeys(map({"city": "San Francisco"})); + * ``` + * + * @param mapExpression The expression representing the map to get the keys of. + * @returns A new `Expression` representing the keys of the map. + */ +export function mapKeys(mapExpression: Expression): FunctionExpression; +export function mapKeys(fieldOrExpr: string | Expression): FunctionExpression { + return fieldOrExpression(fieldOrExpr).mapKeys(); +} + +/** + * @beta + * Creates an expression that returns the values of a map. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the values of the 'address' map field + * mapValues("address"); + * ``` + * + * @param mapField The map field to get the values of. + * @returns A new `Expression` representing the values of the map. + */ +export function mapValues(mapField: string): FunctionExpression; + +/** + * @beta + * Creates an expression that returns the values of a map. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the values of the map expression + * mapValues(map({"city": "San Francisco"})); + * ``` + * + * @param mapExpression The expression representing the map to get the values of. + * @returns A new `Expression` representing the values of the map. + */ +export function mapValues(mapExpression: Expression): FunctionExpression; +export function mapValues( + fieldOrExpr: string | Expression, +): FunctionExpression { + return fieldOrExpression(fieldOrExpr).mapValues(); +} + +/** + * @beta + * Creates an expression that returns the entries of a map as an array of maps, + * where each map contains a `"k"` property for the key and a `"v"` property for the value. + * For example: `[{ k: "key1", v: "value1" }, ...]`. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the entries of the 'address' map field + * mapEntries("address"); + * ``` + * + * @param mapField The map field to get the entries of. + * @returns A new `Expression` representing the entries of the map. + */ +export function mapEntries(mapField: string): FunctionExpression; + +/** + * @beta + * Creates an expression that returns the entries of a map as an array of maps, + * where each map contains a `"k"` property for the key and a `"v"` property for the value. + * For example: `[{ k: "key1", v: "value1" }, ...]`. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the entries of the map expression + * mapEntries(map({"city": "San Francisco"})); + * ``` + * + * @param mapExpression The expression representing the map to get the entries of. + * @returns A new `Expression` representing the entries of the map. + */ +export function mapEntries(mapExpression: Expression): FunctionExpression; +export function mapEntries( + fieldOrExpr: string | Expression, +): FunctionExpression { + return fieldOrExpression(fieldOrExpr).mapEntries(); +} + +/** + * @beta + * Creates an aggregation that counts the total number of stage inputs. + * + * ```typescript + * // Count the total number of input documents + * countAll().as("totalDocument"); + * ``` + * + * @returns A new `AggregateFunction` representing the 'countAll' aggregation. + */ +export function countAll(): AggregateFunction { + return new AggregateFunction('count', []); +} + +/** + * @beta + * Creates an aggregation that counts the number of stage inputs with valid evaluations of the + * provided expression. + * + * ```typescript + * // Count the number of items where the price is greater than 10 + * count(field("price").greaterThan(10)).as("expensiveItemCount"); + * ``` + * + * @param expression The expression to count. + * @returns A new `AggregateFunction` representing the 'count' aggregation. + */ +export function count(expression: Expression): AggregateFunction; + +/** + * @beta + * Creates an aggregation that counts the number of stage inputs where the input field exists. + * + * ```typescript + * // Count the total number of products + * count("productId").as("totalProducts"); + * ``` + * + * @param fieldName The name of the field to count. + * @returns A new `AggregateFunction` representing the 'count' aggregation. + */ +export function count(fieldName: string): AggregateFunction; +export function count(value: Expression | string): AggregateFunction { + return fieldOrExpression(value).count(); +} + +/** + * @beta + * Creates an aggregation that calculates the sum of values from an expression across multiple + * stage inputs. + * + * ```typescript + * // Calculate the total revenue from a set of orders + * sum(field("orderAmount")).as("totalRevenue"); + * ``` + * + * @param expression The expression to sum up. + * @returns A new `AggregateFunction` representing the 'sum' aggregation. + */ +export function sum(expression: Expression): AggregateFunction; + +/** + * @beta + * Creates an aggregation that calculates the sum of a field's values across multiple stage + * inputs. + * + * ```typescript + * // Calculate the total revenue from a set of orders + * sum("orderAmount").as("totalRevenue"); + * ``` + * + * @param fieldName The name of the field containing numeric values to sum up. + * @returns A new `AggregateFunction` representing the 'sum' aggregation. + */ +export function sum(fieldName: string): AggregateFunction; +export function sum(value: Expression | string): AggregateFunction { + return fieldOrExpression(value).sum(); +} + +/** + * @beta + * Creates an aggregation that calculates the average (mean) of values from an expression across + * multiple stage inputs. + * + * ```typescript + * // Calculate the average age of users + * average(field("age")).as("averageAge"); + * ``` + * + * @param expression The expression representing the values to average. + * @returns A new `AggregateFunction` representing the 'average' aggregation. + */ +export function average(expression: Expression): AggregateFunction; + +/** + * @beta + * Creates an aggregation that calculates the average (mean) of a field's values across multiple + * stage inputs. + * + * ```typescript + * // Calculate the average age of users + * average("age").as("averageAge"); + * ``` + * + * @param fieldName The name of the field containing numeric values to average. + * @returns A new `AggregateFunction` representing the 'average' aggregation. + */ +export function average(fieldName: string): AggregateFunction; +export function average(value: Expression | string): AggregateFunction { + return fieldOrExpression(value).average(); +} + +/** + * @beta + * Creates an aggregation that finds the minimum value of an expression across multiple stage + * inputs. + * + * ```typescript + * // Find the lowest price of all products + * minimum(field("price")).as("lowestPrice"); + * ``` + * + * @param expression The expression to find the minimum value of. + * @returns A new `AggregateFunction` representing the 'min' aggregation. + */ +export function minimum(expression: Expression): AggregateFunction; + +/** + * @beta + * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. + * + * ```typescript + * // Find the lowest price of all products + * minimum("price").as("lowestPrice"); + * ``` + * + * @param fieldName The name of the field to find the minimum value of. + * @returns A new `AggregateFunction` representing the 'min' aggregation. + */ +export function minimum(fieldName: string): AggregateFunction; +export function minimum(value: Expression | string): AggregateFunction { + return fieldOrExpression(value).minimum(); +} + +/** + * @beta + * Creates an aggregation that finds the maximum value of an expression across multiple stage + * inputs. + * + * ```typescript + * // Find the highest score in a leaderboard + * maximum(field("score")).as("highestScore"); + * ``` + * + * @param expression The expression to find the maximum value of. + * @returns A new `AggregateFunction` representing the 'max' aggregation. + */ +export function maximum(expression: Expression): AggregateFunction; + +/** + * @beta + * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. + * + * ```typescript + * // Find the highest score in a leaderboard + * maximum("score").as("highestScore"); + * ``` + * + * @param fieldName The name of the field to find the maximum value of. + * @returns A new `AggregateFunction` representing the 'max' aggregation. + */ +export function maximum(fieldName: string): AggregateFunction; +export function maximum(value: Expression | string): AggregateFunction { + return fieldOrExpression(value).maximum(); +} + +/** + * @beta + * Calculates the Cosine distance between a field's vector value and a literal vector value. + * + * ```typescript + * // Calculate the Cosine distance between the 'location' field and a target location + * cosineDistance("location", [37.7749, -122.4194]); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles) or {@link VectorValue} to compare against. + * @returns A new `Expression` representing the Cosine distance between the two vectors. + */ +export function cosineDistance( + fieldName: string, + vector: number[] | VectorValue, +): FunctionExpression; + +/** + * @beta + * Calculates the Cosine distance between a field's vector value and a vector expression. + * + * ```typescript + * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field + * cosineDistance("userVector", field("itemVector")); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vectorExpression The other vector (represented as an Expression) to compare against. + * @returns A new `Expression` representing the cosine distance between the two vectors. + */ +export function cosineDistance( + fieldName: string, + vectorExpression: Expression, +): FunctionExpression; + +/** + * @beta + * Calculates the Cosine distance between a vector expression and a vector literal. + * + * ```typescript + * // Calculate the cosine distance between the 'location' field and a target location + * cosineDistance(field("location"), [37.7749, -122.4194]); + * ``` + * + * @param vectorExpression The first vector (represented as an Expression) to compare against. + * @param vector The other vector (as an array of doubles or VectorValue) to compare against. + * @returns A new `Expression` representing the cosine distance between the two vectors. + */ +export function cosineDistance( + vectorExpression: Expression, + vector: number[] | VectorValue, +): FunctionExpression; + +/** + * @beta + * Calculates the Cosine distance between two vector expressions. + * + * ```typescript + * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field + * cosineDistance(field("userVector"), field("itemVector")); + * ``` + * + * @param vectorExpression The first vector (represented as an Expression) to compare against. + * @param otherVectorExpression The other vector (represented as an Expression) to compare against. + * @returns A new `Expression` representing the cosine distance between the two vectors. + */ +export function cosineDistance( + vectorExpression: Expression, + otherVectorExpression: Expression, +): FunctionExpression; +export function cosineDistance( + expr: Expression | string, + other: Expression | number[] | firestore.VectorValue, +): FunctionExpression { + const expr1 = fieldOrExpression(expr); + const expr2 = vectorToExpr(other); + return expr1.cosineDistance(expr2); +} + +/** + * @beta + * Calculates the dot product between a field's vector value and a double array. + * + * ```typescript + * // Calculate the dot product distance between a feature vector and a target vector + * dotProduct("features", [0.5, 0.8, 0.2]); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles or VectorValue) to calculate with. + * @returns A new `Expression` representing the dot product between the two vectors. + */ +export function dotProduct( + fieldName: string, + vector: number[] | VectorValue, +): FunctionExpression; + +/** + * @beta + * Calculates the dot product between a field's vector value and a vector expression. + * + * ```typescript + * // Calculate the dot product distance between two document vectors: 'docVector1' and 'docVector2' + * dotProduct("docVector1", field("docVector2")); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vectorExpression The other vector (represented as an Expression) to calculate with. + * @returns A new `Expression` representing the dot product between the two vectors. + */ +export function dotProduct( + fieldName: string, + vectorExpression: Expression, +): FunctionExpression; + +/** + * @beta + * Calculates the dot product between a vector expression and a double array. + * + * ```typescript + * // Calculate the dot product between a feature vector and a target vector + * dotProduct(field("features"), [0.5, 0.8, 0.2]); + * ``` + * + * @param vectorExpression The first vector (represented as an Expression) to calculate with. + * @param vector The other vector (as an array of doubles or VectorValue) to calculate with. + * @returns A new `Expression` representing the dot product between the two vectors. + */ +export function dotProduct( + vectorExpression: Expression, + vector: number[] | VectorValue, +): FunctionExpression; + +/** + * @beta + * Calculates the dot product between two vector expressions. + * + * ```typescript + * // Calculate the dot product between two document vectors: 'docVector1' and 'docVector2' + * dotProduct(field("docVector1"), field("docVector2")); + * ``` + * + * @param vectorExpression The first vector (represented as an Expression) to calculate with. + * @param otherVectorExpression The other vector (represented as an Expression) to calculate with. + * @returns A new `Expression` representing the dot product between the two vectors. + */ +export function dotProduct( + vectorExpression: Expression, + otherVectorExpression: Expression, +): FunctionExpression; +export function dotProduct( + expr: Expression | string, + other: Expression | number[] | VectorValue, +): FunctionExpression { + const expr1 = fieldOrExpression(expr); + const expr2 = vectorToExpr(other); + return expr1.dotProduct(expr2); +} + +/** + * @beta + * Calculates the Euclidean distance between a field's vector value and a double array. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * euclideanDistance("location", [37.7749, -122.4194]); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles or VectorValue) to compare against. + * @returns A new `Expression` representing the Euclidean distance between the two vectors. + */ +export function euclideanDistance( + fieldName: string, + vector: number[] | VectorValue, +): FunctionExpression; + +/** + * @beta + * Calculates the Euclidean distance between a field's vector value and a vector expression. + * + * ```typescript + * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' + * euclideanDistance("pointA", field("pointB")); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vectorExpression The other vector (represented as an Expression) to compare against. + * @returns A new `Expression` representing the Euclidean distance between the two vectors. + */ +export function euclideanDistance( + fieldName: string, + vectorExpression: Expression, +): FunctionExpression; + +/** + * @beta + * Calculates the Euclidean distance between a vector expression and a double array. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * + * euclideanDistance(field("location"), [37.7749, -122.4194]); + * ``` + * + * @param vectorExpression The first vector (represented as an Expression) to compare against. + * @param vector The other vector (as an array of doubles or VectorValue) to compare against. + * @returns A new `Expression` representing the Euclidean distance between the two vectors. + */ +export function euclideanDistance( + vectorExpression: Expression, + vector: number[] | VectorValue, +): FunctionExpression; + +/** + * @beta + * Calculates the Euclidean distance between two vector expressions. + * + * ```typescript + * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' + * euclideanDistance(field("pointA"), field("pointB")); + * ``` + * + * @param vectorExpression The first vector (represented as an Expression) to compare against. + * @param otherVectorExpression The other vector (represented as an Expression) to compare against. + * @returns A new `Expression` representing the Euclidean distance between the two vectors. + */ +export function euclideanDistance( + vectorExpression: Expression, + otherVectorExpression: Expression, +): FunctionExpression; +export function euclideanDistance( + expr: Expression | string, + other: Expression | number[] | VectorValue, +): FunctionExpression { + const expr1 = fieldOrExpression(expr); + const expr2 = vectorToExpr(other); + return expr1.euclideanDistance(expr2); +} + +/** + * @beta + * Creates an expression that calculates the length of a Firestore Vector. + * + * ```typescript + * // Get the vector length (dimension) of the field 'embedding'. + * vectorLength(field("embedding")); + * ``` + * + * @param vectorExpression The expression representing the Firestore Vector. + * @returns A new `Expression` representing the length of the array. + */ +export function vectorLength(vectorExpression: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that calculates the length of a Firestore Vector represented by a field. + * + * ```typescript + * // Get the vector length (dimension) of the field 'embedding'. + * vectorLength("embedding"); + * ``` + * + * @param fieldName The name of the field representing the Firestore Vector. + * @returns A new `Expression` representing the length of the array. + */ +export function vectorLength(fieldName: string): FunctionExpression; +export function vectorLength(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).vectorLength(); +} + +/** + * @beta + * Creates an expression that interprets an expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'microseconds' field as microseconds since epoch. + * unixMicrosToTimestamp(field("microseconds")); + * ``` + * + * @param expr The expression representing the number of microseconds since epoch. + * @returns A new `Expression` representing the timestamp. + */ +export function unixMicrosToTimestamp(expr: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that interprets a field's value as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'microseconds' field as microseconds since epoch. + * unixMicrosToTimestamp("microseconds"); + * ``` + * + * @param fieldName The name of the field representing the number of microseconds since epoch. + * @returns A new `Expression` representing the timestamp. + */ +export function unixMicrosToTimestamp(fieldName: string): FunctionExpression; +export function unixMicrosToTimestamp( + expr: Expression | string, +): FunctionExpression { + return fieldOrExpression(expr).unixMicrosToTimestamp(); +} + +/** + * @beta + * Creates an expression that converts a timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to microseconds since epoch. + * timestampToUnixMicros(field("timestamp")); + * ``` + * + * @param expr The expression representing the timestamp. + * @returns A new `Expression` representing the number of microseconds since epoch. + */ +export function timestampToUnixMicros(expr: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that converts a timestamp field to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to microseconds since epoch. + * timestampToUnixMicros("timestamp"); + * ``` + * + * @param fieldName The name of the field representing the timestamp. + * @returns A new `Expression` representing the number of microseconds since epoch. + */ +export function timestampToUnixMicros(fieldName: string): FunctionExpression; +export function timestampToUnixMicros( + expr: Expression | string, +): FunctionExpression { + return fieldOrExpression(expr).timestampToUnixMicros(); +} + +/** + * @beta + * Creates an expression that interprets an expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'milliseconds' field as milliseconds since epoch. + * unixMillisToTimestamp(field("milliseconds")); + * ``` + * + * @param expr The expression representing the number of milliseconds since epoch. + * @returns A new `Expression` representing the timestamp. + */ +export function unixMillisToTimestamp(expr: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that interprets a field's value as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'milliseconds' field as milliseconds since epoch. + * unixMillisToTimestamp("milliseconds"); + * ``` + * + * @param fieldName The name of the field representing the number of milliseconds since epoch. + * @returns A new `Expression` representing the timestamp. + */ +export function unixMillisToTimestamp(fieldName: string): FunctionExpression; +export function unixMillisToTimestamp( + expr: Expression | string, +): FunctionExpression { + const normalizedExpr = fieldOrExpression(expr); + return normalizedExpr.unixMillisToTimestamp(); +} + +/** + * @beta + * Creates an expression that converts a timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to milliseconds since epoch. + * timestampToUnixMillis(field("timestamp")); + * ``` + * + * @param expr The expression representing the timestamp. + * @returns A new `Expression` representing the number of milliseconds since epoch. + */ +export function timestampToUnixMillis(expr: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that converts a timestamp field to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to milliseconds since epoch. + * timestampToUnixMillis("timestamp"); + * ``` + * + * @param fieldName The name of the field representing the timestamp. + * @returns A new `Expression` representing the number of milliseconds since epoch. + */ +export function timestampToUnixMillis(fieldName: string): FunctionExpression; +export function timestampToUnixMillis( + expr: Expression | string, +): FunctionExpression { + const normalizedExpr = fieldOrExpression(expr); + return normalizedExpr.timestampToUnixMillis(); +} + +/** + * @beta + * Creates an expression that interprets an expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'seconds' field as seconds since epoch. + * unixSecondsToTimestamp(field("seconds")); + * ``` + * + * @param expr The expression representing the number of seconds since epoch. + * @returns A new `Expression` representing the timestamp. + */ +export function unixSecondsToTimestamp(expr: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that interprets a field's value as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'seconds' field as seconds since epoch. + * unixSecondsToTimestamp("seconds"); + * ``` + * + * @param fieldName The name of the field representing the number of seconds since epoch. + * @returns A new `Expression` representing the timestamp. + */ +export function unixSecondsToTimestamp(fieldName: string): FunctionExpression; +export function unixSecondsToTimestamp( + expr: Expression | string, +): FunctionExpression { + const normalizedExpr = fieldOrExpression(expr); + return normalizedExpr.unixSecondsToTimestamp(); +} + +/** + * @beta + * Creates an expression that converts a timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to seconds since epoch. + * timestampToUnixSeconds(field("timestamp")); + * ``` + * + * @param expr The expression representing the timestamp. + * @returns A new `Expression` representing the number of seconds since epoch. + */ +export function timestampToUnixSeconds(expr: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that converts a timestamp field to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to seconds since epoch. + * timestampToUnixSeconds("timestamp"); + * ``` + * + * @param fieldName The name of the field representing the timestamp. + * @returns A new `Expression` representing the number of seconds since epoch. + */ +export function timestampToUnixSeconds(fieldName: string): FunctionExpression; +export function timestampToUnixSeconds( + expr: Expression | string, +): FunctionExpression { + const normalizedExpr = fieldOrExpression(expr); + return normalizedExpr.timestampToUnixSeconds(); +} + +/** + * @beta + * Creates an expression that adds a specified amount of time to a timestamp. + * + * ```typescript + * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. + * timestampAdd(field("timestamp"), field("unit"), field("amount")); + * ``` + * + * @param timestamp The expression representing the timestamp. + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @returns A new `Expression` representing the resulting timestamp. + */ +export function timestampAdd( + timestamp: Expression, + unit: Expression, + amount: Expression, +): FunctionExpression; + +/** + * @beta + * Creates an expression that adds a specified amount of time to a timestamp. + * + * ```typescript + * // Add 1 day to the 'timestamp' field. + * timestampAdd(field("timestamp"), "day", 1); + * ``` + * + * @param timestamp The expression representing the timestamp. + * @param unit The unit of time to add (e.g., "day", "hour"). + * @param amount The amount of time to add. + * @returns A new `Expression` representing the resulting timestamp. + */ +export function timestampAdd( + timestamp: Expression, + unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', + amount: number, +): FunctionExpression; + +/** + * @beta + * Creates an expression that adds a specified amount of time to a timestamp represented by a field. + * + * ```typescript + * // Add 1 day to the 'timestamp' field. + * timestampAdd("timestamp", "day", 1); + * ``` + * + * @param fieldName The name of the field representing the timestamp. + * @param unit The unit of time to add (e.g., "day", "hour"). + * @param amount The amount of time to add. + * @returns A new `Expression` representing the resulting timestamp. + */ +export function timestampAdd( + fieldName: string, + unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', + amount: number, +): FunctionExpression; +export function timestampAdd( + timestamp: Expression | string, + unit: + | Expression + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: Expression | number, +): FunctionExpression { + const normalizedTimestamp = fieldOrExpression(timestamp); + const normalizedUnit = valueToDefaultExpr(unit); + const normalizedAmount = valueToDefaultExpr(amount); + return normalizedTimestamp.timestampAdd(normalizedUnit, normalizedAmount); +} + +/** + * @beta + * Creates an expression that subtracts a specified amount of time from a timestamp. + * + * ```typescript + * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. + * timestampSubtract(field("timestamp"), field("unit"), field("amount")); + * ``` + * + * @param timestamp The expression representing the timestamp. + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @returns A new `Expression` representing the resulting timestamp. + */ +export function timestampSubtract( + timestamp: Expression, + unit: Expression, + amount: Expression, +): FunctionExpression; + +/** + * @beta + * Creates an expression that subtracts a specified amount of time from a timestamp. + * + * ```typescript + * // Subtract 1 day from the 'timestamp' field. + * timestampSubtract(field("timestamp"), "day", 1); + * ``` + * + * @param timestamp The expression representing the timestamp. + * @param unit The unit of time to subtract (e.g., "day", "hour"). + * @param amount The amount of time to subtract. + * @returns A new `Expression` representing the resulting timestamp. + */ +export function timestampSubtract( + timestamp: Expression, + unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', + amount: number, +): FunctionExpression; + +/** + * @beta + * Creates an expression that subtracts a specified amount of time from a timestamp represented by a field. + * + * ```typescript + * // Subtract 1 day from the 'timestamp' field. + * timestampSubtract("timestamp", "day", 1); + * ``` + * + * @param fieldName The name of the field representing the timestamp. + * @param unit The unit of time to subtract (e.g., "day", "hour"). + * @param amount The amount of time to subtract. + * @returns A new `Expression` representing the resulting timestamp. + */ +export function timestampSubtract( + fieldName: string, + unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', + amount: number, +): FunctionExpression; +export function timestampSubtract( + timestamp: Expression | string, + unit: + | Expression + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: Expression | number, +): FunctionExpression { + const normalizedTimestamp = fieldOrExpression(timestamp); + const normalizedUnit = valueToDefaultExpr(unit); + const normalizedAmount = valueToDefaultExpr(amount); + return normalizedTimestamp.timestampSubtract( + normalizedUnit, + normalizedAmount, + ); +} + +/** + * @beta + * + * Creates an expression that evaluates to the current server timestamp. + * + * ```typescript + * // Get the current server timestamp + * currentTimestamp() + * ``` + * + * @returns A new Expression representing the current server timestamp. + */ +export function currentTimestamp(): FunctionExpression { + return new FunctionExpression('current_timestamp', []); +} + +/** + * @beta + * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. + * + * ```typescript + * // Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND + * // the 'status' field is "active" + * const condition = and(greaterThan("age", 18), equal("city", "London"), equal("status", "active")); + * ``` + * + * @param first The first filter condition. + * @param second The second filter condition. + * @param more Additional filter conditions to 'AND' together. + * @returns A new `Expression` representing the logical 'AND' operation. + */ +export function and( + first: BooleanExpression, + second: BooleanExpression, + ...more: BooleanExpression[] +): BooleanExpression { + return new FunctionExpression('and', [first, second, ...more]).asBoolean(); +} + +/** + * @beta + * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. + * + * ```typescript + * // Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR + * // the 'status' field is "active" + * const condition = or(greaterThan("age", 18), equal("city", "London"), equal("status", "active")); + * ``` + * + * @param first The first filter condition. + * @param second The second filter condition. + * @param more Additional filter conditions to 'OR' together. + * @returns A new `Expression` representing the logical 'OR' operation. + */ +export function or( + first: BooleanExpression, + second: BooleanExpression, + ...more: BooleanExpression[] +): BooleanExpression { + return new FunctionExpression('or', [first, second, ...more]).asBoolean(); +} + +/** + * @beta + * Creates an expression that returns the value of the base expression raised to the power of the exponent expression. + * + * ```typescript + * // Raise the value of the 'base' field to the power of the 'exponent' field. + * pow(field("base"), field("exponent")); + * ``` + * + * @param base The expression to raise to the power of the exponent. + * @param exponent The expression to raise the base to the power of. + * @returns A new `Expression` representing the power operation. + */ +export function pow(base: Expression, exponent: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that returns the value of the base expression raised to the power of the exponent. + * + * ```typescript + * // Raise the value of the 'base' field to the power of 2. + * pow(field("base"), 2); + * ``` + * + * @param base The expression to raise to the power of the exponent. + * @param exponent The constant value to raise the base to the power of. + * @returns A new `Expression` representing the power operation. + */ +export function pow(base: Expression, exponent: number): FunctionExpression; + +/** + * @beta + * Creates an expression that returns the value of the base field raised to the power of the exponent expression. + * + * ```typescript + * // Raise the value of the 'base' field to the power of the 'exponent' field. + * pow("base", field("exponent")); + * ``` + * + * @param base The name of the field to raise to the power of the exponent. + * @param exponent The expression to raise the base to the power of. + * @returns A new `Expression` representing the power operation. + */ +export function pow(base: string, exponent: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that returns the value of the base field raised to the power of the exponent. + * + * ```typescript + * // Raise the value of the 'base' field to the power of 2. + * pow("base", 2); + * ``` + * + * @param base The name of the field to raise to the power of the exponent. + * @param exponent The constant value to raise the base to the power of. + * @returns A new `Expression` representing the power operation. + */ +export function pow(base: string, exponent: number): FunctionExpression; +export function pow( + base: Expression | string, + exponent: Expression | number, +): FunctionExpression { + return fieldOrExpression(base).pow(exponent as number); +} + +/** + * @beta + * Creates an expression that generates a random number between 0.0 and 1.0 but not including 1.0. + * + * @example + * ```typescript + * // Generate a random number between 0.0 and 1.0. + * rand(); + * ``` + * + * @returns A new `Expression` representing the rand operation. + */ +export function rand(): FunctionExpression { + return new FunctionExpression('rand', []); +} + +/** + * @beta + * Creates an expression that rounds a numeric value to the nearest whole number. + * + * ```typescript + * // Round the value of the 'price' field. + * round("price"); + * ``` + * + * @param fieldName The name of the field to round. + * @returns A new `Expression` representing the rounded value. + */ +export function round(fieldName: string): FunctionExpression; + +/** + * @beta + * Creates an expression that rounds a numeric value to the nearest whole number. + * + * ```typescript + * // Round the value of the 'price' field. + * round(field("price")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which will be rounded. + * @returns A new `Expression` representing the rounded value. + */ +export function round(expression: Expression): FunctionExpression; +/** + * @beta + * Creates an expression that rounds a numeric value to the specified number of decimal places. + * + * ```typescript + * // Round the value of the 'price' field to two decimal places. + * round("price", 2); + * ``` + * + * @param fieldName The name of the field to round. + * @param decimalPlaces A constant or expression specifying the rounding precision in decimal places. + * @returns A new `Expr` representing the rounded value. + */ +export function round( + fieldName: string, + decimalPlaces: number | Expression, +): FunctionExpression; + +/** + * @beta + * Creates an expression that rounds a numeric value to the specified number of decimal places. + * + * ```typescript + * // Round the value of the 'price' field to two decimal places. + * round(field("price"), constant(2)); + * ``` + * + * @param expression An expression evaluating to a numeric value, which will be rounded. + * @param decimalPlaces A constant or expression specifying the rounding precision in decimal places. + * @returns A new `Expr` representing the rounded value. + */ +export function round( + expression: Expression, + decimalPlaces: number | Expression, +): FunctionExpression; +export function round( + expr: Expression | string, + decimalPlaces?: number | Expression, +): FunctionExpression { + if (decimalPlaces === undefined) { + return fieldOrExpression(expr).round(); + } else { + return fieldOrExpression(expr).round(valueToDefaultExpr(decimalPlaces)); + } +} + +/** + * @beta + * Creates an expression that truncates the numeric value of a field to an integer. + * + * @example + * ```typescript + * // Truncate the value of the 'rating' field. + * trunc("rating"); + * ``` + * + * @param fieldName The name of the field containing the number to truncate. + * @returns A new `Expression` representing the truncated value. + */ +export function trunc(fieldName: string): FunctionExpression; + +/** + * @beta + * Creates an expression that truncates the numeric value of an expression to an integer. + * + * @example + * ```typescript + * // Truncate the value of the 'rating' field. + * trunc(field("rating")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which will be truncated. + * @returns A new `Expression` representing the truncated value. + */ +export function trunc(expression: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that truncates a numeric value to the specified number of decimal places. + * + * @example + * ```typescript + * // Truncate the value of the 'rating' field to two decimal places. + * trunc("rating", 2); + * ``` + * + * @param fieldName The name of the field to truncate. + * @param decimalPlaces A constant or expression specifying the truncation precision in decimal places. + * @returns A new `Expression` representing the truncated value. + */ +export function trunc( + fieldName: string, + decimalPlaces: number | Expression, +): FunctionExpression; + +/** + * @beta + * Creates an expression that truncates a numeric value to the specified number of decimal places. + * + * @example + * ```typescript + * // Truncate the value of the 'rating' field to two decimal places. + * trunc(field("rating"), constant(2)); + * ``` + * + * @param expression An expression evaluating to a numeric value, which will be truncated. + * @param decimalPlaces A constant or expression specifying the truncation precision in decimal places. + * @returns A new `Expression` representing the truncated value. + */ +export function trunc( + expression: Expression, + decimalPlaces: number | Expression, +): FunctionExpression; +export function trunc( + expr: Expression | string, + decimalPlaces?: number | Expression, +): FunctionExpression { + if (decimalPlaces === undefined) { + return fieldOrExpression(expr).trunc(); + } else { + return fieldOrExpression(expr).trunc(valueToDefaultExpr(decimalPlaces)); + } +} + +/** + * @beta + * Creates an expression that returns the collection ID from a path. + * + * ```typescript + * // Get the collection ID from a path. + * collectionId("__name__"); + * ``` + * + * @param fieldName The name of the field to get the collection ID from. + * @returns A new `Expression` representing the collectionId operation. + */ +export function collectionId(fieldName: string): FunctionExpression; + +/** + * @beta + * Creates an expression that returns the collection ID from a path. + * + * ```typescript + * // Get the collection ID from a path. + * collectionId(field("__name__")); + * ``` + * + * @param expression An expression evaluating to a path, which the collection ID will be extracted from. + * @returns A new `Expression` representing the collectionId operation. + */ +export function collectionId(expression: Expression): FunctionExpression; +export function collectionId(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).collectionId(); +} + +/** + * @beta + * Creates an expression that calculates the length of a string, array, map, vector, or bytes. + * + * ```typescript + * // Get the length of the 'name' field. + * length("name"); + * + * // Get the number of items in the 'cart' array. + * length("cart"); + * ``` + * + * @param fieldName The name of the field to calculate the length of. + * @returns A new `Expression` representing the length of the string, array, map, vector, or bytes. + */ +export function length(fieldName: string): FunctionExpression; + +/** + * @beta + * Creates an expression that calculates the length of a string, array, map, vector, or bytes. + * + * ```typescript + * // Get the length of the 'name' field. + * length(field("name")); + * + * // Get the number of items in the 'cart' array. + * length(field("cart")); + * ``` + * + * @param expression An expression evaluating to a string, array, map, vector, or bytes, which the length will be calculated for. + * @returns A new `Expression` representing the length of the string, array, map, vector, or bytes. + */ +export function length(expression: Expression): FunctionExpression; +export function length(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).length(); +} + +/** + * @beta + * Creates an expression that computes the natural logarithm of a numeric value. + * + * ```typescript + * // Compute the natural logarithm of the 'value' field. + * ln("value"); + * ``` + * + * @param fieldName The name of the field to compute the natural logarithm of. + * @returns A new `Expression` representing the natural logarithm of the numeric value. + */ +export function ln(fieldName: string): FunctionExpression; + +/** + * @beta + * Creates an expression that computes the natural logarithm of a numeric value. + * + * ```typescript + * // Compute the natural logarithm of the 'value' field. + * ln(field("value")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the natural logarithm will be computed for. + * @returns A new `Expression` representing the natural logarithm of the numeric value. + */ +export function ln(expression: Expression): FunctionExpression; +export function ln(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).ln(); +} + +/** + * @beta + * Creates an expression that computes the square root of a numeric value. + * + * ```typescript + * // Compute the square root of the 'value' field. + * sqrt(field("value")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the square root will be computed for. + * @returns A new `Expression` representing the square root of the numeric value. + */ +export function sqrt(expression: Expression): FunctionExpression; +/** + * @beta + * Creates an expression that computes the square root of a numeric value. + * + * ```typescript + * // Compute the square root of the 'value' field. + * sqrt("value"); + * ``` + * + * @param fieldName The name of the field to compute the square root of. + * @returns A new `Expression` representing the square root of the numeric value. + */ +export function sqrt(fieldName: string): FunctionExpression; +export function sqrt(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).sqrt(); +} + +/** + * @beta + * Creates an expression that reverses a string. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * stringReverse(field("myString")); + * ``` + * + * @param stringExpression An expression evaluating to a string value, which will be reversed. + * @returns A new `Expression` representing the reversed string. + */ +export function stringReverse(stringExpression: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that reverses a string value in the specified field. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * stringReverse("myString"); + * ``` + * + * @param field The name of the field representing the string to reverse. + * @returns A new `Expression` representing the reversed string. + */ +export function stringReverse(field: string): FunctionExpression; +export function stringReverse(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).stringReverse(); +} + +/** + * @beta + * Creates an expression that concatenates strings, arrays, or blobs. Types cannot be mixed. + * + * ```typescript + * // Concatenate the 'firstName' and 'lastName' fields with a space in between. + * concat(field("firstName"), " ", field("lastName")) + * ``` + * + * @param first The first expressions to concatenate. + * @param second The second literal or expression to concatenate. + * @param others Additional literals or expressions to concatenate. + * @returns A new `Expression` representing the concatenation. + */ +export function concat( + first: Expression, + second: Expression | unknown, + ...others: Array +): FunctionExpression; + +/** + * @beta + * Creates an expression that concatenates strings, arrays, or blobs. Types cannot be mixed. + * + * ```typescript + * // Concatenate a field with a literal string. + * concat(field("firstName"), "Doe") + * ``` + * + * @param fieldName The name of a field to concatenate. + * @param second The second literal or expression to concatenate. + * @param others Additional literal or expressions to concatenate. + * @returns A new `Expression` representing the concatenation. + */ +export function concat( + fieldName: string, + second: Expression | unknown, + ...others: Array +): FunctionExpression; + +export function concat( + fieldNameOrExpression: string | Expression, + second: Expression | unknown, + ...others: Array +): FunctionExpression { + return fieldOrExpression(fieldNameOrExpression).concat( + valueToDefaultExpr(second), + ...others.map(valueToDefaultExpr), + ); +} + +/** + * @beta + * Creates an expression that computes the absolute value of a numeric value. + * + * @param expr The expression to compute the absolute value of. + * @returns A new `Expr` representing the absolute value of the numeric value. + */ +export function abs(expr: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that computes the absolute value of a numeric value. + * + * @param fieldName The field to compute the absolute value of. + * @returns A new `Expr` representing the absolute value of the numeric value. + */ +export function abs(fieldName: string): FunctionExpression; +export function abs(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).abs(); +} + +/** + * @beta + * Creates an expression that returns the `elseExpr` argument if `ifExpr` is absent, else return + * the result of the `ifExpr` argument evaluation. + * + * ```typescript + * // Returns the value of the optional field 'optional_field', or returns 'default_value' + * // if the field is absent. + * ifAbsent(field("optional_field"), constant("default_value")) + * ``` + * + * @param ifExpr The expression to check for absence. + * @param elseExpr The expression that will be evaluated and returned if [ifExpr] is absent. + * @returns A new Expression representing the ifAbsent operation. + */ +export function ifAbsent(ifExpr: Expression, elseExpr: Expression): Expression; + +/** + * @beta + * Creates an expression that returns the `elseValue` argument if `ifExpr` is absent, else + * return the result of the `ifExpr` argument evaluation. + * + * ```typescript + * // Returns the value of the optional field 'optional_field', or returns 'default_value' + * // if the field is absent. + * ifAbsent(field("optional_field"), "default_value") + * ``` + * + * @param ifExpr The expression to check for absence. + * @param elseValue The value that will be returned if `ifExpr` evaluates to an absent value. + * @returns A new [Expression] representing the ifAbsent operation. + */ +export function ifAbsent(ifExpr: Expression, elseValue: unknown): Expression; + +/** + * @beta + * Creates an expression that returns the `elseExpr` argument if `ifFieldName` is absent, else + * return the value of the field. + * + * ```typescript + * // Returns the value of the optional field 'optional_field', or returns the value of + * // 'default_field' if 'optional_field' is absent. + * ifAbsent("optional_field", field("default_field")) + * ``` + * + * @param ifFieldName The field to check for absence. + * @param elseExpr The expression that will be evaluated and returned if `ifFieldName` is + * absent. + * @returns A new Expression representing the ifAbsent operation. + */ +export function ifAbsent(ifFieldName: string, elseExpr: Expression): Expression; + +/** + * @beta + * Creates an expression that returns the `elseValue` argument if `ifFieldName` is absent, else + * return the value of the field. + * + * ```typescript + * // Returns the value of the optional field 'optional_field', or returns 'default_value' + * // if the field is absent. + * ifAbsent("optional_field", "default_value") + * ``` + * + * @param ifFieldName The field to check for absence. + * @param elseValue The value that will be returned if [ifFieldName] is absent. + * @returns A new Expression representing the ifAbsent operation. + */ +export function ifAbsent( + ifFieldName: string | Expression, + elseValue: Expression | unknown, +): Expression; +export function ifAbsent( + fieldNameOrExpression: string | Expression, + elseValue: Expression | unknown, +): Expression { + return fieldOrExpression(fieldNameOrExpression).ifAbsent( + valueToDefaultExpr(elseValue), + ); +} + +/** + * @beta + * Creates an expression that joins the elements of an array into a string. + * + * ```typescript + * // Join the elements of the 'tags' field with a comma and space. + * join("tags", ", ") + * ``` + * + * @param arrayFieldName The name of the field containing the array. + * @param delimiter The string to use as a delimiter. + * @returns A new Expression representing the join operation. + */ +export function join(arrayFieldName: string, delimiter: string): Expression; + +/** + * @beta + * Creates an expression that joins the elements of an array into a string. + * + * ```typescript + * // Join an array of string using the delimiter from the 'separator' field. + * join(array(['foo', 'bar']), field("separator")) + * ``` + * + * @param arrayExpression An expression that evaluates to an array. + * @param delimiterExpression The expression that evaluates to the delimiter string. + * @returns A new Expression representing the join operation. + */ +export function join( + arrayExpression: Expression, + delimiterExpression: Expression, +): Expression; + +/** + * @beta + * Creates an expression that joins the elements of an array into a string. + * + * ```typescript + * // Join the elements of the 'tags' field with a comma and space. + * join(field("tags"), ", ") + * ``` + * + * @param arrayExpression An expression that evaluates to an array. + * @param delimiter The string to use as a delimiter. + * @returns A new Expression representing the join operation. + */ +export function join( + arrayExpression: Expression, + delimiter: string, +): Expression; + +/** + * @beta + * Creates an expression that joins the elements of an array into a string. + * + * ```typescript + * // Join the elements of the 'tags' field with the delimiter from the 'separator' field. + * join('tags', field("separator")) + * ``` + * + * @param arrayFieldName The name of the field containing the array. + * @param delimiterExpression The expression that evaluates to the delimiter string. + * @returns A new Expression representing the join operation. + */ +export function join( + arrayFieldName: string, + delimiterExpression: Expression, +): Expression; +export function join( + fieldNameOrExpression: string | Expression, + delimiterValueOrExpression: Expression | string, +): Expression { + return fieldOrExpression(fieldNameOrExpression).join( + valueToDefaultExpr(delimiterValueOrExpression), + ); +} + +/** + * @beta + * Creates an expression that computes the base-10 logarithm of a numeric value. + * + * ```typescript + * // Compute the base-10 logarithm of the 'value' field. + * log10("value"); + * ``` + * + * @param fieldName The name of the field to compute the base-10 logarithm of. + * @returns A new `Expr` representing the base-10 logarithm of the numeric value. + */ +export function log10(fieldName: string): FunctionExpression; + +/** + * @beta + * Creates an expression that computes the base-10 logarithm of a numeric value. + * + * ```typescript + * // Compute the base-10 logarithm of the 'value' field. + * log10(field("value")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the base-10 logarithm will be computed for. + * @returns A new `Expr` representing the base-10 logarithm of the numeric value. + */ +export function log10(expression: Expression): FunctionExpression; +export function log10(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).log10(); +} + +/** + * @beta + * Creates an expression that computes the sum of the elements in an array. + * + * ```typescript + * // Compute the sum of the elements in the 'scores' field. + * arraySum("scores"); + * ``` + * + * @param fieldName The name of the field to compute the sum of. + * @returns A new `Expr` representing the sum of the elements in the array. + */ +export function arraySum(fieldName: string): FunctionExpression; + +/** + * @beta + * Creates an expression that computes the sum of the elements in an array. + * + * ```typescript + * // Compute the sum of the elements in the 'scores' field. + * arraySum(field("scores")); + * ``` + * + * @param expression An expression evaluating to a numeric array, which the sum will be computed for. + * @returns A new `Expr` representing the sum of the elements in the array. + */ +export function arraySum(expression: Expression): FunctionExpression; +export function arraySum(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).arraySum(); +} +/** + * @beta + * Creates an expression that splits the value of a field on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scoresCsv' field on delimiter ',' + * split('scoresCsv', ',') + * ``` + * + * @param fieldName Split the value in this field. + * @param delimiter Split on this delimiter. + * + * @returns A new `Expression` representing the split function. + */ +export function split(fieldName: string, delimiter: string): FunctionExpression; + +/** + * @beta + * Creates an expression that splits the value of a field on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format + * split('scores', conditional(field('format').equal('csv'), constant(','), constant(':')) + * ``` + * + * @param fieldName Split the value in this field. + * @param delimiter Split on this delimiter returned by evaluating this expression. + * + * @returns A new `Expression` representing the split function. + */ +export function split( + fieldName: string, + delimiter: Expression, +): FunctionExpression; + +/** + * @beta + * Creates an expression that splits a string into an array of substrings based on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scoresCsv' field on delimiter ',' + * split(field('scoresCsv'), ',') + * ``` + * + * @param expression Split the result of this expression. + * @param delimiter Split on this delimiter. + * + * @returns A new `Expression` representing the split function. + */ +export function split( + expression: Expression, + delimiter: string, +): FunctionExpression; + +/** + * @beta + * Creates an expression that splits a string into an array of substrings based on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format + * split(field('scores'), conditional(field('format').equal('csv'), constant(','), constant(':')) + * ``` + * + * @param expression Split the result of this expression. + * @param delimiter Split on this delimiter returned by evaluating this expression. + * + * @returns A new `Expression` representing the split function. + */ +export function split( + expression: Expression, + delimiter: Expression, +): FunctionExpression; +export function split( + fieldNameOrExpression: string | Expression, + delimiter: string | Expression, +): FunctionExpression { + return fieldOrExpression(fieldNameOrExpression).split( + valueToDefaultExpr(delimiter), + ); +} + +/** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the beginning of the day. + * field('createdAt').timestampTruncate('day') + * ``` + * + * @param fieldName Truncate the timestamp value contained in this field. + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @returns A new {Expression} representing the truncated timestamp. + */ +export function timestampTruncate( + fieldName: string, + granularity: firestore.Pipelines.TimeGranularity, + timezone?: string | Expression, +): FunctionExpression; + +/** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'. + * field('createdAt').timestampTruncate(field('granularity')) + * ``` + * + * @param fieldName Truncate the timestamp value contained in this field. + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @returns A new {Expression} representing the truncated timestamp. + */ +export function timestampTruncate( + fieldName: string, + granularity: Expression, + timezone?: string | Expression, +): FunctionExpression; + +/** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the beginning of the day. + * field('createdAt').timestampTruncate('day') + * ``` + * + * @param timestampExpression Truncate the timestamp value that is returned by this expression. + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @returns A new {Expression} representing the truncated timestamp. + */ +export function timestampTruncate( + timestampExpression: Expression, + granularity: firestore.Pipelines.TimeGranularity, + timezone?: string | Expression, +): FunctionExpression; + +/** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'. + * field('createdAt').timestampTruncate(field('granularity')) + * ``` + * + * @param timestampExpression Truncate the timestamp value that is returned by this expression. + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @returns A new {Expression} representing the truncated timestamp. + */ +export function timestampTruncate( + timestampExpression: Expression, + granularity: Expression, + timezone?: string | Expression, +): FunctionExpression; +export function timestampTruncate( + fieldNameOrExpression: string | Expression, + granularity: firestore.Pipelines.TimeGranularity | Expression, + timezone?: string | Expression, +): FunctionExpression { + const internalGranularity = isString(granularity) + ? valueToDefaultExpr(granularity.toLowerCase()) + : granularity; + return fieldOrExpression(fieldNameOrExpression).timestampTruncate( + internalGranularity, + timezone, + ); +} + +/** + * @beta + * Creates an expression that returns the data type of the data in the specified field. + * + * @example + * ```typescript + * // Get the data type of the value in field 'title' + * type('title') + * ``` + * + * @returns A new {Expression} representing the data type. + */ +export function type(fieldName: string): FunctionExpression; +/** + * @beta + * Creates an expression that returns the data type of an expression's result. + * + * @example + * ```typescript + * // Get the data type of a conditional expression + * type(conditional(exists('foo'), constant(1), constant(true))) + * ``` + * + * @returns A new {Expression} representing the data type. + */ +export function type(expression: Expression): FunctionExpression; +export function type( + fieldNameOrExpression: string | Expression, +): FunctionExpression { + return fieldOrExpression(fieldNameOrExpression).type(); +} + +/** + * @beta + * Creates an expression that checks if the value in the specified field is of the given type. + * + * @remarks Null or undefined fields evaluate to skip/error. Use `ifAbsent()` / `isAbsent()` to evaluate missing data. + * + * @example + * ```typescript + * // Check if the 'price' field is a floating point number (evaluating to true inside pipeline conditionals) + * isType('price', 'float64'); + * ``` + * + * @param fieldName The name of the field to check. + * @param type The type to check for. + * @returns A new `BooleanExpression` that evaluates to true if the field's value is of the given type, false otherwise. + */ +export function isType(fieldName: string, type: Type): BooleanExpression; + +/** + * @beta + * Creates an expression that checks if the result of an expression is of the given type. + * + * @remarks Null or undefined fields evaluate to skip/error. Use `ifAbsent()` / `isAbsent()` to evaluate missing data. + * + * @example + * ```typescript + * // Check if the result of a calculation is a number + * isType(add('count', 1), 'number') + * ``` + * + * @param expression The expression to check. + * @param type The type to check for. + * @returns A new `BooleanExpression` that evaluates to true if the expression's result is of the given type, false otherwise. + */ +export function isType(expression: Expression, type: Type): BooleanExpression; +export function isType( + fieldNameOrExpression: string | Expression, + type: Type, +): BooleanExpression { + return fieldOrExpression(fieldNameOrExpression).isType(type); +} + +// TODO(new-expression): Add new top-level expression function definitions above this line + +/** + * @beta + * Creates a `Field` instance representing the field at the given path. + * + * ```typescript + * // Sort documents by the 'name' field in lowercase in ascending order + * db.pipeline().collection("users") + * .sort(ascending(field("name").toLower())); + * ``` + * + * @param expr The expression to create an ascending ordering for. + * @returns A new `Ordering` for ascending sorting. + */ +export function ascending(expr: Expression): Ordering; + +/** + * @beta + * Creates an `Ordering` that sorts documents in ascending order based on a field. + * + * ```typescript + * // Sort documents by the 'name' field in ascending order + * db.pipeline().collection("users") + * .sort(ascending("name")); + * ``` + * + * @param fieldName The field to create an ascending ordering for. + * @returns A new `Ordering` for ascending sorting. + */ +export function ascending(fieldName: string): Ordering; +export function ascending(field: Expression | string): Ordering { + return new Ordering(fieldOrExpression(field), 'ascending'); +} + +/** + * @beta + * Creates an `Ordering` that sorts documents in descending order based on an expression. + * + * ```typescript + * // Sort documents by the 'name' field in lowercase in descending order + * db.pipeline().collection("users") + * .sort(descending(field("name").toLower())); + * ``` + * + * @param expr The expression to create a descending ordering for. + * @returns A new `Ordering` for descending sorting. + */ +export function descending(expr: Expression): Ordering; + +/** + * @beta + * Creates an `Ordering` that sorts documents in descending order based on a field. + * + * ```typescript + * // Sort documents by the 'name' field in descending order + * db.pipeline().collection("users") + * .sort(descending("name")); + * ``` + * + * @param fieldName The field to create a descending ordering for. + * @returns A new `Ordering` for descending sorting. + */ +export function descending(fieldName: string): Ordering; +export function descending(field: Expression | string): Ordering { + return new Ordering(fieldOrExpression(field), 'descending'); +} + +/** + * @beta + * Represents an ordering criterion for sorting documents in a Firestore pipeline. + * + * You create `Ordering` instances using the `ascending` and `descending` helper functions. + */ +export class Ordering implements HasUserData { + constructor( + readonly expr: Expression, + readonly direction: 'ascending' | 'descending', + ) {} + + /** + * @beta + * @internal + * @private + * Indicates if this expression was created from a literal value passed + * by the caller. + */ + _createdFromLiteral = false; + + /** + * @beta + * @private + * @internal + */ + _toProto(serializer: Serializer): api.IValue { + const expr = this.expr as Expression; + return { + mapValue: { + fields: { + direction: serializer.encodeValue(this.direction), + expression: expr._toProto(serializer), + }, + }, + }; + } + + _protoValueType: 'ProtoValue' = 'ProtoValue' as const; + + /** + * @beta + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + (this.expr as Expression)._validateUserData(ignoreUndefinedProperties); + } +} diff --git a/handwritten/firestore/dev/src/pipelines/index.ts b/handwritten/firestore/dev/src/pipelines/index.ts new file mode 100644 index 00000000000..91333c94b8f --- /dev/null +++ b/handwritten/firestore/dev/src/pipelines/index.ts @@ -0,0 +1,138 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export { + Pipeline, + PipelineResult, + PipelineSnapshot, + PipelineSource, +} from './pipelines'; + +export { + and, + arrayContains, + arrayContainsAny, + arrayReverse, + average, + equal, + ceil, + exp, + floor, + greaterThan, + like, + lessThan, + notEqual, + ascending, + not, + or, + regexContains, + regexMatch, + regexFind, + regexFindAll, + startsWith, + stringConcat, + subtract, + cosineDistance, + countDistinct, + dotProduct, + euclideanDistance, + mapGet, + mapEntries, + mapKeys, + mapSet, + mapValues, + lessThanOrEqual, + equalAny, + map, + array, + field, + xor, + AggregateFunction, + arrayGet, + add, + BooleanExpression, + Expression, + FunctionExpression, + minimum, + count, + countIf, + arrayLength, + stringContains, + charLength, + divide, + mod, + reverse, + trim, + toUpper, + toLower, + vectorLength, + exists, + isAbsent, + ifError, + isError, + substring, + documentId, + arrayContainsAll, + constant, + Field, + Constant, + sum, + maximum, + descending, + greaterThanOrEqual, + multiply, + conditional, + Ordering, + AliasedAggregate, + endsWith, + AliasedExpression, + mapMerge, + mapRemove, + byteLength, + logicalMaximum, + logicalMinimum, + notEqualAny, + countAll, + timestampAdd, + timestampSubtract, + timestampToUnixMicros, + timestampToUnixSeconds, + unixMicrosToTimestamp, + timestampToUnixMillis, + unixSecondsToTimestamp, + unixMillisToTimestamp, + pow, + collectionId, + length, + ln, + round, + sqrt, + rand, + trunc, + stringReverse, + abs, + arraySum, + ifAbsent, + log10, + concat, + join, + currentTimestamp, + arrayConcat, + type, + isType, + Type, + timestampTruncate, + split, + // TODO(new-expression): Add new expression exports above this line +} from './expression'; diff --git a/handwritten/firestore/dev/src/pipelines/options-util.ts b/handwritten/firestore/dev/src/pipelines/options-util.ts new file mode 100644 index 00000000000..82f6bdf2998 --- /dev/null +++ b/handwritten/firestore/dev/src/pipelines/options-util.ts @@ -0,0 +1,141 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {ObjectValue, Serializer} from '../serializer'; +import {ObjectValueFieldPath} from '../path'; +import {ApiMapValue} from '../types'; +import {isPlainObject, mapToArray} from '../util'; +import {google} from '../../protos/firestore_v1_proto_api'; +import IValue = google.firestore.v1.IValue; +export type OptionsDefinitions = Record; +export type OptionDefinition = { + serverName: string; + nestedOptions?: OptionsDefinitions; +}; + +/** + * A utility class for formatting known and raw options into the + * proto structure utilized by Pipelines. + * + * @example + * ``` + * myUtil = new OptionsUtil({ + * someFoo: { + * serverName: 'some_foo', + * }, + * aBar: { + * serverName: 'a_bar', + * nestedOptions: { + * baz: { + * serverName: 'baz', + * } + * }, + * }, + * }); + * + * optionsProto = myUtil.getOptionsProto( + * serializer, + * { + * someFoo: 1 + * }, + * { + * aBar.another_unknown_option: "yep" + * }); + * + * // Resulting optionsProto: + * // { + * // 'some_foo': { integerValue: 1 }, + * // 'a_bar': { mapValue: { fields: { 'another_unknown_option': {stringValue: 'yep' }}}} + * // } + * ``` + */ +export class OptionsUtil { + constructor(private optionDefinitions: OptionsDefinitions) {} + + /** + * Serialize known options to ObjectValue + * @param options - Serialize these options. + * @param serializer - Use this serializer to serialize primitives to proto. + * @private + */ + private _getKnownOptions( + options: Record, + serializer: Serializer, + ): ObjectValue { + const knownOptions: ObjectValue = ObjectValue.empty(); + + // SERIALIZE KNOWN OPTIONS + for (const knownOptionKey in this.optionDefinitions) { + const optionDefinition: OptionDefinition = + this.optionDefinitions[knownOptionKey]; + + if (knownOptionKey in options) { + const optionValue: unknown = options[knownOptionKey]; + let protoValue: IValue | undefined = undefined; + + if (optionDefinition.nestedOptions && isPlainObject(optionValue)) { + const nestedUtil = new OptionsUtil(optionDefinition.nestedOptions); + protoValue = { + mapValue: { + fields: nestedUtil.getOptionsProto(serializer, optionValue), + }, + }; + } else if (optionValue) { + protoValue = serializer.encodeValue(optionValue) ?? undefined; + } + + if (protoValue) { + knownOptions.set( + new ObjectValueFieldPath(optionDefinition.serverName), + protoValue, + ); + } + } + } + + return knownOptions; + } + + /** + * Serialize known and raw options to a proto object. + * - Renames knownOptions from the SDK name (camel case) to server name (snake case) + * - Serializes values provided for each option to a proto value, using the provided serializer. + * - Overlays optionsOverrides (which represent raw options) onto the result proto. + * - Supports nested objects (`{optionA: { optionB: true }}`) and dot notation (`{optionA.optionB: true}`). + * @param serializer + * @param knownOptions + * @param optionsOverride + */ + getOptionsProto( + serializer: Serializer, + knownOptions: Record, + optionsOverride?: Record, + ): ApiMapValue | undefined { + const result: ObjectValue = this._getKnownOptions(knownOptions, serializer); + + // APPLY OPTIONS OVERRIDES + if (optionsOverride) { + const optionsMap = new Map( + mapToArray(optionsOverride, (value, key) => [ + ObjectValueFieldPath.fromDotNotation(key), + value !== undefined ? serializer.encodeValue(value) : null, + ]), + ); + result.setAll(optionsMap); + } + + // Return IMapValue from `result` + return result.value.mapValue.fields ?? {}; + } +} diff --git a/handwritten/firestore/dev/src/pipelines/pipeline-util.ts b/handwritten/firestore/dev/src/pipelines/pipeline-util.ts new file mode 100644 index 00000000000..5c12257c23f --- /dev/null +++ b/handwritten/firestore/dev/src/pipelines/pipeline-util.ts @@ -0,0 +1,765 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type * as firestore from '@google-cloud/firestore'; +import {GoogleError} from 'google-gax'; +import {Duplex, Transform} from 'stream'; +import {google} from '../../protos/firestore_v1_proto_api'; + +import * as protos from '../../protos/firestore_v1_proto_api'; +import './expression'; +import Firestore, { + CollectionReference, + DocumentReference, + FieldValue, + Timestamp, + VectorValue, +} from '../index'; +import {logger} from '../logger'; +import {FieldPath, QualifiedResourcePath} from '../path'; +import {CompositeFilterInternal} from '../reference/composite-filter-internal'; +import {NOOP_MESSAGE} from '../reference/constants'; +import {FieldFilterInternal} from '../reference/field-filter-internal'; +import {FilterInternal} from '../reference/filter-internal'; +import { + PipelineResponse, + PipelineStreamElement, + QueryCursor, +} from '../reference/types'; +import {Serializer} from '../serializer'; +import { + Deferred, + getTotalTimeout, + isObject, + isPermanentRpcError, + isPlainObject, + requestTag, + wrapError, +} from '../util'; +import api = protos.google.firestore.v1; + +import { + Expression, + BooleanExpression, + and, + or, + field as createField, + constant, + map, + array, + Constant, + field, + Ordering, + greaterThan, + lessThan, + Field, + AggregateFunction, +} from './expression'; +import {Pipeline, PipelineResult, ExplainStats} from './pipelines'; +import {StructuredPipeline} from './structured-pipeline'; +import Selectable = FirebaseFirestore.Pipelines.Selectable; + +/** + * Returns a builder for DocumentSnapshot and QueryDocumentSnapshot instances. + * Invoke `.build()' to assemble the final snapshot. + * + * @private + * @internal + */ +export class ExecutionUtil { + constructor( + /** @private */ + readonly _firestore: Firestore, + /** @private */ + readonly _serializer: Serializer, + ) {} + + _getResponse( + structuredPipeline: StructuredPipeline, + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + ): Promise { + // Capture the error stack to preserve stack tracing across async calls. + const stack = Error().stack!; + + return new Promise((resolve, reject): void => { + const result: Array = []; + const output: PipelineResponse = {}; + + const stream: NodeJS.EventEmitter = this._stream( + structuredPipeline, + transactionOrReadTime, + ); + stream.on('error', err => { + reject(wrapError(err, stack)); + }); + stream.on('data', (data: PipelineStreamElement[]) => { + for (const element of data) { + if (element.transaction) { + output.transaction = element.transaction; + } + if (element.executionTime) { + output.executionTime = element.executionTime; + } + if (element.explainStats) { + output.explainStats = element.explainStats; + } + if (element.result) { + result.push(element.result); + } + } + }); + stream.on('end', () => { + output.result = result; + resolve(output); + }); + }); + } + + // This method exists solely to enable unit tests to mock it. + _isPermanentRpcError(err: GoogleError, methodName: string): boolean { + return isPermanentRpcError(err, methodName); + } + + _hasRetryTimedOut(methodName: string, startTime: number): boolean { + const totalTimeout = getTotalTimeout(methodName); + if (totalTimeout === 0) { + return false; + } + + return Date.now() - startTime >= totalTimeout; + } + + stream( + structuredPipeline: StructuredPipeline, + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + ): NodeJS.ReadableStream { + const responseStream = this._stream( + structuredPipeline, + transactionOrReadTime, + ); + const transform = new Transform({ + objectMode: true, + transform(chunk: Array, encoding, callback) { + chunk.forEach(item => { + if (item.result) { + this.push(item.result); + } + }); + callback(); + }, + }); + + responseStream.pipe(transform); + responseStream.on('error', e => transform.destroy(e)); + return transform; + } + + _stream( + structuredPipeline: StructuredPipeline, + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + ): NodeJS.ReadableStream { + const tag = requestTag(); + + let backendStream: Duplex; + const stream = new Transform({ + objectMode: true, + transform: ( + proto: api.ExecutePipelineResponse | typeof NOOP_MESSAGE, + enc, + callback, + ) => { + if (proto === NOOP_MESSAGE) { + callback(undefined); + return; + } + + if (proto.results && proto.results.length === 0) { + const output: PipelineStreamElement = {}; + if (proto.transaction?.length) { + output.transaction = proto.transaction; + } + if (proto.executionTime) { + output.executionTime = Timestamp.fromProto(proto.executionTime); + } + callback(undefined, [output]); + } else { + let output: PipelineStreamElement[] = proto.results.map(result => { + const output: PipelineStreamElement = {}; + if (proto.transaction?.length) { + output.transaction = proto.transaction; + } + if (proto.executionTime) { + output.executionTime = Timestamp.fromProto(proto.executionTime); + } + + const ref = result.name + ? new DocumentReference( + this._firestore, + QualifiedResourcePath.fromSlashSeparatedString(result.name), + ) + : undefined; + + if (!result.fields) { + logger( + '_stream', + null, + 'Unexpected state: `result.fields` was falsey. Using an empty map.', + ); + } + + output.result = new PipelineResult( + this._serializer, + result.fields || {}, + ref, + Timestamp.fromProto(proto.executionTime!), + result.createTime + ? Timestamp.fromProto(result.createTime!) + : undefined, + result.updateTime + ? Timestamp.fromProto(result.updateTime!) + : undefined, + ); + return output; + }); + if (proto.explainStats?.data?.value) { + const explainStats = new ExplainStats(proto.explainStats.data); + + output = [ + ...output, + { + explainStats, + } as PipelineStreamElement, + ]; + } + callback(undefined, output); + } + }, + }); + + Promise.all([ + this._firestore.initializeIfNeeded(tag), + ExplainStats._ensureMessageTypesLoaded(), + ]) + .then(async () => { + // `toProto()` might throw an exception. We rely on the behavior of an + // async function to convert this exception into the rejected Promise we + // catch below. + const request: api.IExecutePipelineRequest = { + database: this._firestore.formattedName, + structuredPipeline: structuredPipeline._toProto(this._serializer), + }; + + if (transactionOrReadTime instanceof Uint8Array) { + request.transaction = transactionOrReadTime; + } else if (transactionOrReadTime instanceof Timestamp) { + request.readTime = transactionOrReadTime.toProto().timestampValue; + } else if (transactionOrReadTime) { + request.newTransaction = transactionOrReadTime; + } + + let streamActive: Deferred; + do { + streamActive = new Deferred(); + const methodName = 'executePipeline'; + backendStream = await this._firestore.requestStream( + methodName, + /* bidirectional= */ false, + request, + tag, + ); + backendStream.on('error', err => { + backendStream.unpipe(stream); + + logger( + 'PipelineUtil._stream', + tag, + 'Pipeline failed with stream error:', + err, + ); + stream.destroy(err); + streamActive.resolve(/* active= */ false); + }); + backendStream.on('end', () => { + streamActive.resolve(/* active= */ false); + }); + backendStream.resume(); + backendStream.pipe(stream); + } while (await streamActive.promise); + }) + .catch(e => { + logger( + 'PipelineUtil._stream', + tag, + 'Pipeline failed with stream error:', + e, + ); + stream.destroy(e); + }); + + return stream; + } +} + +function isITimestamp(obj: unknown): obj is google.protobuf.ITimestamp { + if (typeof obj !== 'object' || obj === null) { + return false; // Must be a non-null object + } + if ( + 'seconds' in obj && + (obj.seconds === null || + typeof obj.seconds === 'number' || + typeof obj.seconds === 'string') && + 'nanos' in obj && + (obj.nanos === null || typeof obj.nanos === 'number') + ) { + return true; + } + + return false; +} +function isILatLng(obj: unknown): obj is google.type.ILatLng { + if (typeof obj !== 'object' || obj === null) { + return false; // Must be a non-null object + } + if ( + 'latitude' in obj && + (obj.latitude === null || typeof obj.latitude === 'number') && + 'longitude' in obj && + (obj.longitude === null || typeof obj.longitude === 'number') + ) { + return true; + } + + return false; +} +function isIArrayValue(obj: unknown): obj is api.IArrayValue { + if (typeof obj !== 'object' || obj === null) { + return false; // Must be a non-null object + } + if ('values' in obj && (obj.values === null || Array.isArray(obj.values))) { + return true; + } + + return false; +} +function isIMapValue(obj: unknown): obj is api.IMapValue { + if (typeof obj !== 'object' || obj === null) { + return false; // Must be a non-null object + } + if ('fields' in obj && (obj.fields === null || isObject(obj.fields))) { + return true; + } + + return false; +} +function isIFunction(obj: unknown): obj is api.IFunction { + if (typeof obj !== 'object' || obj === null) { + return false; // Must be a non-null object + } + if ( + 'name' in obj && + (obj.name === null || typeof obj.name === 'string') && + 'args' in obj && + (obj.args === null || Array.isArray(obj.args)) + ) { + return true; + } + + return false; +} + +function isIPipeline(obj: unknown): obj is api.IPipeline { + if (typeof obj !== 'object' || obj === null) { + return false; // Must be a non-null object + } + if ('stages' in obj && (obj.stages === null || Array.isArray(obj.stages))) { + return true; + } + + return false; +} + +export function isFirestoreValue(obj: unknown): obj is api.IValue { + if (typeof obj !== 'object' || obj === null) { + return false; // Must be a non-null object + } + + // Check optional properties and their types + if ( + ('nullValue' in obj && + (obj.nullValue === null || obj.nullValue === 'NULL_VALUE')) || + ('booleanValue' in obj && + (obj.booleanValue === null || typeof obj.booleanValue === 'boolean')) || + ('integerValue' in obj && + (obj.integerValue === null || + typeof obj.integerValue === 'number' || + typeof obj.integerValue === 'string')) || + ('doubleValue' in obj && + (obj.doubleValue === null || typeof obj.doubleValue === 'number')) || + ('timestampValue' in obj && + (obj.timestampValue === null || isITimestamp(obj.timestampValue))) || + ('stringValue' in obj && + (obj.stringValue === null || typeof obj.stringValue === 'string')) || + ('bytesValue' in obj && + (obj.bytesValue === null || obj.bytesValue instanceof Uint8Array)) || + ('referenceValue' in obj && + (obj.referenceValue === null || + typeof obj.referenceValue === 'string')) || + ('geoPointValue' in obj && + (obj.geoPointValue === null || isILatLng(obj.geoPointValue))) || + ('arrayValue' in obj && + (obj.arrayValue === null || isIArrayValue(obj.arrayValue))) || + ('mapValue' in obj && + (obj.mapValue === null || isIMapValue(obj.mapValue))) || + ('fieldReferenceValue' in obj && + (obj.fieldReferenceValue === null || + typeof obj.fieldReferenceValue === 'string')) || + ('functionValue' in obj && + (obj.functionValue === null || isIFunction(obj.functionValue))) || + ('pipelineValue' in obj && + (obj.pipelineValue === null || isIPipeline(obj.pipelineValue))) + ) { + return true; + } + + return false; +} + +export function whereConditionsFromCursor( + cursor: QueryCursor, + orderings: Ordering[], + position: 'before' | 'after', +): BooleanExpression { + // The filterFunc is either greater than or less than + const filterFunc = position === 'before' ? lessThan : greaterThan; + const cursors = cursor.values.map(value => Constant._fromProto(value)); + const size = cursors.length; + + let field = orderings[size - 1].expr; + let value = cursors[size - 1]; + + // Add condition for last bound + let condition: BooleanExpression = filterFunc(field, value); + if ( + (position === 'after' && cursor.before) || + (position === 'before' && !cursor.before) + ) { + // When the cursor bound is inclusive, then the last bound + // can be equal to the value, otherwise it's not equal + condition = or( + condition, + field.equal(value) as unknown as BooleanExpression, + ); + } + + // Iterate backwards over the remaining bounds, adding + // a condition for each one + for (let i = size - 2; i >= 0; i--) { + field = orderings[i].expr; + value = cursors[i]; + + // For each field in the orderings, the condition is either + // a) lessThan|greaterThan the cursor value, + // b) or equal the cursor value and lessThan|greaterThan the cursor values for other fields + condition = or( + filterFunc(field, value), + and(field.equal(value) as unknown as BooleanExpression, condition), + ); + } + + return condition; +} + +export function reverseOrderings(orderings: Ordering[]): Ordering[] { + return orderings.map( + o => + new Ordering( + o.expr, + o.direction === 'ascending' ? 'descending' : 'ascending', + ), + ); +} + +export function toPipelineBooleanExpr( + f: FilterInternal, + serializer: Serializer, +): BooleanExpression { + if (f instanceof FieldFilterInternal) { + const field = createField(f.field); + + // Comparison filters + const value = isFirestoreValue(f.value) + ? f.value + : serializer.encodeValue(f.value); + switch (f.op) { + case 'LESS_THAN': + return and(field.exists(), field.lessThan(value)); + case 'LESS_THAN_OR_EQUAL': + return and(field.exists(), field.lessThanOrEqual(value)); + case 'GREATER_THAN': + return and(field.exists(), field.greaterThan(value)); + case 'GREATER_THAN_OR_EQUAL': + return and(field.exists(), field.greaterThanOrEqual(value)); + case 'EQUAL': + return and(field.exists(), field.equal(value)); + case 'NOT_EQUAL': + return and(field.exists(), field.notEqual(value)); + case 'ARRAY_CONTAINS': + return and(field.exists(), field.arrayContains(value)); + case 'IN': { + const values = value?.arrayValue?.values?.map(val => constant(val)); + return and(field.exists(), field.equalAny(values!)); + } + case 'ARRAY_CONTAINS_ANY': { + const values = value?.arrayValue?.values?.map(val => constant(val)); + return and(field.exists(), field.arrayContainsAny(values!)); + } + case 'NOT_IN': { + const values = value?.arrayValue?.values?.map(val => constant(val)); + // In Enterprise DB's NOT_IN will match a field that does not exist, + // therefore we do not want an existence filter for the NOT_IN conversion + // so the Query and Pipeline behavior are consistent in Enterprise. + return field.notEqualAny(values!); + } + } + } else if (f instanceof CompositeFilterInternal) { + switch (f._getOperator()) { + case 'AND': { + const conditions = f + .getFilters() + .map(f => toPipelineBooleanExpr(f, serializer)); + return and(conditions[0], conditions[1], ...conditions.slice(2)); + } + case 'OR': { + const conditions = f + .getFilters() + .map(f => toPipelineBooleanExpr(f, serializer)); + return or(conditions[0], conditions[1], ...conditions.slice(2)); + } + } + } + + throw new Error( + `Failed to convert filter to pipeline conditions: ${f.toProto()}`, + ); +} + +export function isString(val: unknown): val is string { + return typeof val === 'string'; +} + +export function isNumber(val: unknown): val is number { + return typeof val === 'number'; +} + +export function isSelectable( + val: unknown, +): val is firestore.Pipelines.Selectable { + const candidate = val as firestore.Pipelines.Selectable; + return ( + candidate.selectable && + isString(candidate._alias) && + isExpr(candidate._expr) + ); +} + +export function isOrdering(val: unknown): val is firestore.Pipelines.Ordering { + const candidate = val as firestore.Pipelines.Ordering; + return ( + isExpr(candidate.expr) && + (candidate.direction === 'ascending' || + candidate.direction === 'descending') + ); +} + +export function isAliasedAggregate( + val: unknown, +): val is firestore.Pipelines.AliasedAggregate { + const candidate = val as firestore.Pipelines.AliasedAggregate; + return ( + isString(candidate._alias) && + candidate._aggregate instanceof AggregateFunction + ); +} + +export function isExpr(val: unknown): val is firestore.Pipelines.Expression { + return val instanceof Expression; +} + +export function isBooleanExpr( + val: unknown, +): val is firestore.Pipelines.BooleanExpression { + return val instanceof BooleanExpression; +} + +export function isField(val: unknown): val is firestore.Pipelines.Field { + return val instanceof Field; +} + +export function isPipeline(val: unknown): val is firestore.Pipelines.Pipeline { + return val instanceof Pipeline; +} + +export function isCollectionReference( + val: unknown, +): val is firestore.CollectionReference { + return val instanceof CollectionReference; +} + +/** + * Converts a value to an Expression, Returning either a Constant, MapFunction, + * ArrayFunction, or the input itself (if it's already an expression). + * + * @private + * @internal + * @param value + */ +export function valueToDefaultExpr(value: unknown): Expression { + let result: Expression | undefined; + if (isFirestoreValue(value)) { + return constant(value); + } + if (value instanceof Expression) { + return value; + } else if (isPlainObject(value)) { + result = map(value as Record); + } else if (value instanceof Array) { + result = array(value); + } else { + result = constant(value); + } + + // TODO(pipeline) is this still used? + result._createdFromLiteral = true; + return result; +} + +/** + * Converts a value to an Expression, Returning either a Constant, MapFunction, + * ArrayFunction, or the input itself (if it's already an expression). + * + * @private + * @internal + * @param value + */ +export function vectorToExpr( + value: firestore.VectorValue | number[] | Expression, +): Expression { + if (value instanceof Expression) { + return value; + } else if (value instanceof VectorValue) { + const result = constant(value); + result._createdFromLiteral = true; + return result; + } else if (Array.isArray(value)) { + const result = constant(FieldValue.vector(value)); + result._createdFromLiteral = true; + return result; + } else { + throw new Error('Unsupported value: ' + typeof value); + } +} + +/** + * Converts a value to an Expression, Returning either a Constant, MapFunction, + * ArrayFunction, or the input itself (if it's already an expression). + * If the input is a string, it is assumed to be a field name, and a + * field(value) is returned. + * + * @private + * @internal + * @param value + */ +export function fieldOrExpression(value: unknown): Expression { + if (isString(value)) { + const result = field(value); + result._createdFromLiteral = true; + return result; + } else { + return valueToDefaultExpr(value); + } +} + +export function toField(value: string | firestore.Pipelines.Field): Field { + if (isString(value)) { + const result = field(value); + result._createdFromLiteral = true; + return result; + } else { + return value as Field; + } +} + +/** + * Converts a value to a Selectable, returning either a + * Field, or the input itself (if it's already a Selectable). + * If the input is a string, it is assumed to be a field name, and a + * field(value) is returned. + * + * @private + * @internal + * @param value + */ +export function fieldOrSelectable(value: string | Selectable): Selectable { + if (isString(value)) { + const result = field(value); + result._createdFromLiteral = true; + return result; + } else { + return value; + } +} + +export function selectablesToMap( + selectables: (firestore.Pipelines.Selectable | string)[], +): Map { + const result = new Map(); + for (const selectable of selectables) { + let alias: string; + let expression: Expression; + if (typeof selectable === 'string') { + alias = selectable as string; + expression = new Field(FieldPath.fromArgument(selectable)); + } else { + alias = selectable._alias; + expression = selectable._expr as unknown as Expression; + } + + if (result.get(alias) !== undefined) { + throw new Error(`Duplicate alias or field '${alias}'`); + } + + result.set(alias, expression); + } + return result; +} + +export function aliasedAggregateToMap( + aliasedAggregatees: firestore.Pipelines.AliasedAggregate[], +): Map { + return aliasedAggregatees.reduce( + ( + map: Map, + selectable: firestore.Pipelines.AliasedAggregate, + ) => { + if (map.get(selectable._alias) !== undefined) { + throw new Error(`Duplicate alias or field '${selectable._alias}'`); + } + + map.set(selectable._alias, selectable._aggregate as AggregateFunction); + return map; + }, + new Map() as Map, + ); +} diff --git a/handwritten/firestore/dev/src/pipelines/pipelines.ts b/handwritten/firestore/dev/src/pipelines/pipelines.ts new file mode 100644 index 00000000000..2844c29ca57 --- /dev/null +++ b/handwritten/firestore/dev/src/pipelines/pipelines.ts @@ -0,0 +1,2072 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import * as firestore from '@google-cloud/firestore'; +import * as deepEqual from 'fast-deep-equal'; +import {google} from '../../protos/firestore_v1_proto_api'; +import Firestore, { + CollectionReference, + FieldPath, + Query, + Timestamp, +} from '../index'; +import {validateFieldPath} from '../path'; +import { + ExecutionUtil, + aliasedAggregateToMap, + fieldOrExpression, + isAliasedAggregate, + isBooleanExpr, + isCollectionReference, + isExpr, + isField, + isNumber, + isOrdering, + isPipeline, + isSelectable, + isString, + selectablesToMap, + toField, + vectorToExpr, +} from './pipeline-util'; +import {DocumentReference} from '../reference/document-reference'; +import {PipelineResponse} from '../reference/types'; +import {HasUserData, hasUserData, Serializer} from '../serializer'; +import {ApiMapValue} from '../types'; +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import IStage = google.firestore.v1.Pipeline.IStage; +import {isOptionalEqual, isPlainObject} from '../util'; + +import { + AggregateFunction, + AliasedAggregate, + Expression, + Field, + BooleanExpression, + Ordering, + constant, + _mapValue, + field, +} from './expression'; +import { + AddFields, + Aggregate, + CollectionSource, + CollectionGroupSource, + DatabaseSource, + DocumentsSource, + Where, + FindNearest, + RawStage, + Limit, + Offset, + Select, + Sort, + Stage, + Distinct, + RemoveFields, + ReplaceWith, + Sample, + Union, + Unnest, + InternalWhereStageOptions, + InternalOffsetStageOptions, + InternalLimitStageOptions, + InternalDistinctStageOptions, + InternalAggregateStageOptions, + InternalFindNearestStageOptions, + InternalReplaceWithStageOptions, + InternalSampleStageOptions, + InternalUnionStageOptions, + InternalUnnestStageOptions, + InternalSortStageOptions, + InternalDocumentsStageOptions, + InternalCollectionGroupStageOptions, + InternalCollectionStageOptions, +} from './stage'; +import {StructuredPipeline} from './structured-pipeline'; +import Selectable = FirebaseFirestore.Pipelines.Selectable; + +import { + load as loadProtos, + Root as ProtoRoot, + Type as MessageType, + ReflectionObject, +} from 'protobufjs'; + +/** + * @beta + * Represents the source of a Firestore `Pipeline`. + */ +export class PipelineSource implements firestore.Pipelines.PipelineSource { + constructor(private db: Firestore) {} + + /** + * @beta + * Returns all documents from the entire collection. The collection can be nested. + * @param collection - Name or reference to the collection that will be used as the Pipeline source. + */ + collection(collection: string | firestore.CollectionReference): Pipeline; + /** + * @beta + * Returns all documents from the entire collection. The collection can be nested. + * @param options - Options defining how this CollectionStage is evaluated. + */ + collection(options: firestore.Pipelines.CollectionStageOptions): Pipeline; + collection( + collectionOrOptions: + | string + | firestore.CollectionReference + | firestore.Pipelines.CollectionStageOptions, + ): Pipeline { + const options = + isString(collectionOrOptions) || + isCollectionReference(collectionOrOptions) + ? {} + : collectionOrOptions; + + const collection = + isString(collectionOrOptions) || + isCollectionReference(collectionOrOptions) + ? collectionOrOptions + : collectionOrOptions.collection; + + // Validate that a user provided reference is for the same Firestore DB + if (isCollectionReference(collection)) { + this._validateReference(collection); + } + + const normalizedCollection = isString(collection) + ? this.db.collection(collection) + : (collection as CollectionReference); + + const internalOptions: InternalCollectionStageOptions = { + ...options, + collection: normalizedCollection, + }; + + return new Pipeline(this.db, [new CollectionSource(internalOptions)]); + } + + /** + * @beta + * Returns all documents from a collection ID regardless of the parent. + * @param collectionId - ID of the collection group to use as the Pipeline source. + */ + collectionGroup(collectionId: string): Pipeline; + + /** + * @beta + * Returns all documents from a collection ID regardless of the parent. + * @param options - Options defining how this CollectionGroupStage is evaluated. + */ + collectionGroup( + options: firestore.Pipelines.CollectionGroupStageOptions, + ): Pipeline; + collectionGroup( + collectionIdOrOptions: + | string + | firestore.Pipelines.CollectionGroupStageOptions, + ): Pipeline { + const options: InternalCollectionGroupStageOptions = isString( + collectionIdOrOptions, + ) + ? {collectionId: collectionIdOrOptions} + : {...collectionIdOrOptions}; + return new Pipeline(this.db, [new CollectionGroupSource(options)]); + } + + /** + * @beta + * Returns all documents from the entire database. + */ + database(): Pipeline; + /** + * @beta + * Returns all documents from the entire database. + * @param options - Options defining how a DatabaseStage is evaluated. + */ + database(options: firestore.Pipelines.DatabaseStageOptions): Pipeline; + database(options?: firestore.Pipelines.DatabaseStageOptions): Pipeline { + return new Pipeline(this.db, [new DatabaseSource(options ?? {})]); + } + + /** + * @beta + * Set the pipeline's source to the documents specified by the given paths and DocumentReferences. + * + * @param docs An array of paths and DocumentReferences specifying the individual documents that will be the source of this pipeline. + * The converters for these DocumentReferences will be ignored and not have an effect on this pipeline. + * + * @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. + */ + documents(docs: Array): Pipeline; + + /** + * @beta + * Set the pipeline's source to the documents specified by the given paths and DocumentReferences. + * + * @param options - Options defining how this DocumentsStage is evaluated. + * + * @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. + */ + documents(options: firestore.Pipelines.DocumentsStageOptions): Pipeline; + documents( + docsOrOptions: + | Array + | firestore.Pipelines.DocumentsStageOptions, + ): Pipeline { + const options = Array.isArray(docsOrOptions) ? {} : docsOrOptions; + const docs = Array.isArray(docsOrOptions) + ? docsOrOptions + : docsOrOptions.docs; + + // Validate that all user provided references are for the same Firestore DB + docs + .filter(v => v instanceof DocumentReference) + .forEach(dr => + this._validateReference(dr as firestore.DocumentReference), + ); + + const normalizedDocs: Array = docs.map(doc => + isString(doc) ? this.db.doc(doc) : (doc as DocumentReference), + ); + + const internalOptions: InternalDocumentsStageOptions = { + ...options, + docs: normalizedDocs, + }; + return new Pipeline(this.db, [new DocumentsSource(internalOptions)]); + } + + /** + * @beta + * Convert the given VectorQuery into an equivalent Pipeline. + * + * @param query A VectorQuery to be converted into a Pipeline. + * + * @throws {@FirestoreError} Thrown if the provided VectorQuer targets a different project or database than the Pipeline. + */ + createFrom(query: firestore.VectorQuery): Pipeline; + + /** + * @beta + * Convert the given Query into an equivalent Pipeline. + * + * @param query A Query to be converted into a Pipeline. + * + * @throws {@FirestoreError} Thrown if the provided VectorQuer targets a different project or database than the Pipeline. + */ + createFrom(query: firestore.Query): Pipeline; + createFrom(query: firestore.Query | firestore.VectorQuery): Pipeline { + return (query as unknown as {_pipeline(): Pipeline})._pipeline(); + } + + _validateReference( + reference: firestore.CollectionReference | firestore.DocumentReference, + ): reference is CollectionReference | DocumentReference { + if ( + !( + reference instanceof CollectionReference || + reference instanceof DocumentReference + ) + ) { + throw new Error( + 'Invalid reference. The value may not be a CollectionReference or DocumentReference. Or, it may be an object from a different SDK build.', + ); + } + + const refDbId = reference.firestore.formattedName; + if (refDbId !== this.db.formattedName) { + throw new Error( + `Invalid ${ + reference instanceof CollectionReference + ? 'CollectionReference' + : 'DocumentReference' + }. ` + + `The database name ("${refDbId}") of this reference does not match ` + + `the database name ("${this.db.formattedName}") of the target database of this Pipeline.`, + ); + } + + return true; + } +} + +/** + * @beta + * The Pipeline class provides a flexible and expressive framework for building complex data + * transformation and query pipelines for Firestore. + * + * A pipeline takes data sources, such as Firestore collections or collection groups, and applies + * a series of stages that are chained together. Each stage takes the output from the previous stage + * (or the data source) and produces an output for the next stage (or as the final output of the + * pipeline). + * + * Expressions can be used within each stage to filter and transform data through the stage. + * + * NOTE: The chained stages do not prescribe exactly how Firestore will execute the pipeline. + * Instead, Firestore only guarantees that the result is the same as if the chained stages were + * executed in order. + * + * Usage Examples: + * + * @example + * ```typescript + * const db: Firestore; // Assumes a valid firestore instance. + * + * // Example 1: Select specific fields and rename 'rating' to 'bookRating' + * const results1 = await db.pipeline() + * .collection('books') + * .select('title', 'author', field('rating').as('bookRating')) + * .execute(); + * + * // Example 2: Filter documents where 'genre' is 'Science Fiction' and 'published' is after 1950 + * const results2 = await db.pipeline() + * .collection('books') + * .where(and(field('genre').equal('Science Fiction'), field('published').greaterThan(1950))) + * .execute(); + * + * // Example 3: Calculate the average rating of books published after 1980 + * const results3 = await db.pipeline() + * .collection('books') + * .where(field('published').greaterThan(1980)) + * .aggregate(average(field('rating')).as('averageRating')) + * .execute(); + * ``` + */ +export class Pipeline implements firestore.Pipelines.Pipeline { + constructor( + private db: Firestore, + private stages: Stage[], + ) {} + + private _addStage(stage: Stage): Pipeline { + const copy = this.stages.map(s => s); + copy.push(stage); + return new Pipeline(this.db, copy); + } + + /** + * @beta + * Adds new fields to outputs from previous stages. + * + * This stage allows you to compute values on-the-fly based on existing data from previous + * stages or constants. You can use this to create new fields or overwrite existing ones (if there + * is name overlaps). + * + * The added fields are defined using `Selectable`s, which can be: + * + * - `Field`: References an existing document field. + * - `Expression`: Either a literal value (see `constant(value)`) or a computed value + * (see `Expression`) with an assigned alias using `Expression.as('alias')`. + * + * + * @example + * ```typescript + * firestore.pipeline().collection("books") + * .addFields( + * field("rating").as("bookRating"), // Rename 'rating' to 'bookRating' + * add(5, field("quantity")).as("totalCost") // Calculate 'totalCost' + * ); + * ``` + * + * @param field The first field to add to the documents, specified as a `Selectable`. + * @param additionalFields Optional additional fields to add to the documents, specified as `Selectable`s. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + addFields( + field: firestore.Pipelines.Selectable, + ...additionalFields: firestore.Pipelines.Selectable[] + ): Pipeline; + /** + * @beta + * Adds new fields to outputs from previous stages. + * + * This stage allows you to compute values on-the-fly based on existing data from previous + * stages or constants. You can use this to create new fields or overwrite existing ones (if there + * is name overlaps). + * + * The added fields are defined using `Selectable`s, which can be: + * + * - `Field`: References an existing document field. + * - `Expression`: Either a literal value (see `constant(value)`) or a computed value + * (see `Expression`) with an assigned alias using `Expression.as('alias')`}. + * + * + * @example + * ```typescript + * firestore.pipeline().collection("books") + * .addFields( + * field("rating").as("bookRating"), // Rename 'rating' to 'bookRating' + * add(5, field("quantity")).as("totalCost") // Calculate 'totalCost' + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + addFields(options: firestore.Pipelines.AddFieldsStageOptions): Pipeline; + addFields( + fieldOrOptions: + | firestore.Pipelines.Selectable + | firestore.Pipelines.AddFieldsStageOptions, + ...additionalFields: firestore.Pipelines.Selectable[] + ): Pipeline { + const options = isSelectable(fieldOrOptions) ? {} : fieldOrOptions; + const fields: firestore.Pipelines.Selectable[] = isSelectable( + fieldOrOptions, + ) + ? [fieldOrOptions, ...additionalFields] + : fieldOrOptions.fields; + const normalizedFields: Map = selectablesToMap(fields); + + this._validateUserData('select', normalizedFields); + + const internalOptions = { + ...options, + fields: normalizedFields, + }; + return this._addStage(new AddFields(internalOptions)); + } + + /** + * @beta + * Remove fields from outputs of previous stages. + * + * + * @example + * ```typescript + * firestore.pipeline().collection('books') + * // removes field 'rating' and 'cost' from the previous stage outputs. + * .removeFields( + * field('rating'), + * 'cost' + * ); + * ``` + * + * @param fieldValue The first field to remove. + * @param additionalFields Optional additional fields to remove. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + removeFields( + fieldValue: firestore.Pipelines.Field | string, + ...additionalFields: Array + ): Pipeline; + /** + * @beta + * Remove fields from outputs of previous stages. + * + * + * @example + * ```typescript + * firestore.pipeline().collection('books') + * // removes field 'rating' and 'cost' from the previous stage outputs. + * .removeFields( + * field('rating'), + * 'cost' + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + removeFields(options: firestore.Pipelines.RemoveFieldsStageOptions): Pipeline; + removeFields( + fieldValueOrOptions: + | firestore.Pipelines.Field + | string + | firestore.Pipelines.RemoveFieldsStageOptions, + ...additionalFields: Array + ): Pipeline { + const options = + isField(fieldValueOrOptions) || isString(fieldValueOrOptions) + ? {} + : fieldValueOrOptions; + + const fields: Array = + isField(fieldValueOrOptions) || isString(fieldValueOrOptions) + ? [fieldValueOrOptions, ...additionalFields] + : fieldValueOrOptions.fields; + const convertedFields: Array = fields.map(f => + isString(f) ? field(f) : (f as Field), + ); + this._validateUserData('removeFields', convertedFields); + + const innerOptions = { + ...options, + fields: convertedFields, + }; + + return this._addStage(new RemoveFields(innerOptions)); + } + + /** + * @beta + * Selects or creates a set of fields from the outputs of previous stages. + * + *

The selected fields are defined using `Selectable` expressions, which can be: + * + *

    + *
  • `string`: Name of an existing field
  • + *
  • `Field`: References an existing field.
  • + *
  • `AliasedExpression`: Represents the result of a function with an assigned alias name using + * {@link Expression#as}
  • + *
+ * + *

If no selections are provided, the output of this stage is empty. Use {@link + * Pipeline#addFields} instead if only additions are + * desired. + * + * + * @example + * ```typescript + * db.pipeline().collection("books") + * .select( + * "firstName", + * field("lastName"), + * field("address").toUppercase().as("upperAddress"), + * ); + * ``` + * + * @param selection The first field to include in the output documents, specified as + * `Selectable` expression or string value representing the field name. + * @param additionalSelections Optional additional fields to include in the output documents, specified as + * `Selectable` expressions or `string` values representing field names. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + select( + selection: firestore.Pipelines.Selectable | string, + ...additionalSelections: Array + ): Pipeline; + /** + * @beta + * Selects or creates a set of fields from the outputs of previous stages. + * + *

The selected fields are defined using `Selectable` expressions, which can be: + * + *

    + *
  • `string`: Name of an existing field
  • + *
  • `Field`: References an existing field.
  • + *
  • `AliasedExpression`: Represents the result of a function with an assigned alias name using + * {@link Expression#as}
  • + *
+ * + *

If no selections are provided, the output of this stage is empty. Use {@link + * Pipeline#addFields} instead if only additions are + * desired. + * + * + * @example + * ```typescript + * db.pipeline().collection("books") + * .select( + * "firstName", + * field("lastName"), + * field("address").toUppercase().as("upperAddress"), + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + select(options: firestore.Pipelines.SelectStageOptions): Pipeline; + select( + selectionOrOptions: + | firestore.Pipelines.Selectable + | string + | firestore.Pipelines.SelectStageOptions, + ...additionalSelections: Array + ): Pipeline { + const options = + isSelectable(selectionOrOptions) || isString(selectionOrOptions) + ? {} + : selectionOrOptions; + + const selections: Array = + isSelectable(selectionOrOptions) || isString(selectionOrOptions) + ? [selectionOrOptions, ...additionalSelections] + : selectionOrOptions.selections; + const normalizedSelections: Map = + selectablesToMap(selections); + + this._validateUserData('select', normalizedSelections); + + const internalOptions = { + ...options, + selections: normalizedSelections, + }; + return this._addStage(new Select(internalOptions)); + } + + /** + * @beta + * Filters the documents from previous stages to only include those matching the specified `BooleanExpression`. + * + *

This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. + * You can filter documents based on their field values, using implementations of `BooleanExpression`, typically + * including but not limited to: + * + *

    + *
  • field comparators: {@link Function#equal}, {@link Function#lessThan} (less than), {@link + * Function#greaterThan} (greater than), etc.
  • + *
  • logical operators: {@link Function#and}, {@link Function#or}, {@link Function#not}, etc.
  • + *
  • advanced functions: {@link Function#regexMatch}, {@link + * Function#arrayContains}, etc.
  • + *
+ * + * + * @example + * ```typescript + * firestore.pipeline().collection("books") + * .where( + * and( + * greaterThan(field("rating"), 4.0), // Filter for ratings greater than 4.0 + * field("genre").equal("Science Fiction") // Equivalent to greaterThan("genre", "Science Fiction") + * ) + * ); + * ``` + * + * @param condition The `BooleanExpression` to apply. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + where(condition: firestore.Pipelines.BooleanExpression): Pipeline; + /** + * @beta + * Filters the documents from previous stages to only include those matching the specified `BooleanExpression`. + * + *

This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. + * You can filter documents based on their field values, using implementations of `BooleanExpression`, typically + * including but not limited to: + * + *

    + *
  • field comparators: {@link Function#equal}, {@link Function#lessThan} (less than), {@link + * Function#greaterThan} (greater than), etc.
  • + *
  • logical operators: {@link Function#and}, {@link Function#or}, {@link Function#not}, etc.
  • + *
  • advanced functions: {@link Function#regexMatch}, {@link + * Function#arrayContains}, etc.
  • + *
+ * + * + * @example + * ```typescript + * firestore.pipeline().collection("books") + * .where( + * and( + * greaterThan(field("rating"), 4.0), // Filter for ratings greater than 4.0 + * field("genre").equal("Science Fiction") // Equivalent to greaterThan("genre", "Science Fiction") + * ) + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + where(options: firestore.Pipelines.WhereStageOptions): Pipeline; + where( + conditionOrOptions: + | firestore.Pipelines.BooleanExpression + | firestore.Pipelines.WhereStageOptions, + ): Pipeline { + const options = isBooleanExpr(conditionOrOptions) ? {} : conditionOrOptions; + + const condition: firestore.Pipelines.BooleanExpression = isBooleanExpr( + conditionOrOptions, + ) + ? conditionOrOptions + : conditionOrOptions.condition; + const convertedCondition: BooleanExpression = + condition as BooleanExpression; + this._validateUserData('where', convertedCondition); + + const internalOptions: InternalWhereStageOptions = { + ...options, + condition: convertedCondition, + }; + + return this._addStage(new Where(internalOptions)); + } + + /** + * @beta + * Skips the first `offset` number of documents from the results of previous stages. + * + *

This stage is useful for implementing pagination in your pipelines, allowing you to retrieve + * results in chunks. It is typically used in conjunction with to control the + * size of each page. + * + * + * @example + * ```typescript + * // Retrieve the second page of 20 results + * firestore.pipeline().collection('books') + * .sort(field('published').descending()) + * .offset(20) // Skip the first 20 results + * .limit(20); // Take the next 20 results + * ``` + * + * @param offset The number of documents to skip. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + offset(offset: number): Pipeline; + /** + * @beta + * Skips the first `offset` number of documents from the results of previous stages. + * + *

This stage is useful for implementing pagination in your pipelines, allowing you to retrieve + * results in chunks. It is typically used in conjunction with `limit` to control the + * size of each page. + * + * + * @example + * ```typescript + * // Retrieve the second page of 20 results + * firestore.pipeline().collection('books') + * .sort(field('published').descending()) + * .offset(20) // Skip the first 20 results + * .limit(20); // Take the next 20 results + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + offset(options: firestore.Pipelines.OffsetStageOptions): Pipeline; + offset( + offsetOrOptions: number | firestore.Pipelines.OffsetStageOptions, + ): Pipeline { + const options = isNumber(offsetOrOptions) ? {} : offsetOrOptions; + + const offset: number = isNumber(offsetOrOptions) + ? offsetOrOptions + : offsetOrOptions.offset; + + const internalOptions: InternalOffsetStageOptions = { + ...options, + offset, + }; + return this._addStage(new Offset(internalOptions)); + } + + /** + * @beta + * Limits the maximum number of documents returned by previous stages to `limit`. + * + *

This stage is particularly useful when you want to retrieve a controlled subset of data from + * a potentially large result set. It's often used for: + * + *

    + *
  • **Pagination:** In combination with `offset` to retrieve specific pages of + * results.
  • + *
  • **Limiting Data Retrieval:** To prevent excessive data transfer and improve performance, + * especially when dealing with large collections.
  • + *
+ * + * + * @example + * ```typescript + * // Limit the results to the top 10 highest-rated books + * firestore.pipeline().collection('books') + * .sort(field('rating').descending()) + * .limit(10); + * ``` + * + * @param limit The maximum number of documents to return. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + limit(limit: number): Pipeline; + /** + * @beta + * Limits the maximum number of documents returned by previous stages to `limit`. + * + *

This stage is particularly useful when you want to retrieve a controlled subset of data from + * a potentially large result set. It's often used for: + * + *

    + *
  • **Pagination:** In combination with `offset` to retrieve specific pages of + * results.
  • + *
  • **Limiting Data Retrieval:** To prevent excessive data transfer and improve performance, + * especially when dealing with large collections.
  • + *
+ * + * + * @example + * ```typescript + * // Limit the results to the top 10 highest-rated books + * firestore.pipeline().collection('books') + * .sort(field('rating').descending()) + * .limit(10); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + limit(options: firestore.Pipelines.LimitStageOptions): Pipeline; + limit( + limitOrOptions: number | firestore.Pipelines.LimitStageOptions, + ): Pipeline { + const options = isNumber(limitOrOptions) ? {} : limitOrOptions; + + const limit: number = isNumber(limitOrOptions) + ? limitOrOptions + : limitOrOptions.limit; + + const internalOptions: InternalLimitStageOptions = { + ...options, + limit, + }; + return this._addStage(new Limit(internalOptions)); + } + + /** + * @beta + * Returns a set of distinct values from the inputs to this stage. + * + * This stage runs through the results from previous stages to include only results with + * unique combinations of `Expression` values. + * + * The parameters to this stage are defined using `Selectable` expressions or strings: + * + * - `string`: Name of an existing field + * - `Field`: References an existing document field. + * - `AliasedExpression`: Represents the result of a function with an assigned alias name + * using {@link Expression#as}. + * + * + * @example + * ```typescript + * // Get a list of unique author names in uppercase and genre combinations. + * firestore.pipeline().collection("books") + * .distinct(toUppercase(field("author")).as("authorName"), field("genre"), "publishedAt") + * .select("authorName"); + * ``` + * + * @param group The `Selectable` expression or field name to consider when determining + * distinct value combinations. + * @param additionalGroups Optional additional `Selectable` expressions to consider when determining distinct + * value combinations or strings representing field names. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + distinct( + group: string | firestore.Pipelines.Selectable, + ...additionalGroups: Array + ): Pipeline; + /** + * @beta + * Returns a set of distinct values from the inputs to this stage. + * + * This stage runs through the results from previous stages to include only results with + * unique combinations of `Expression` values. + * + * The parameters to this stage are defined using `Selectable` expressions or strings: + * + * - `string`: Name of an existing field + * - `Field`: References an existing document field. + * - `AliasedExpression`: Represents the result of a function with an assigned alias name + * using {@link Expression#as}. + * + * + * @example + * ```typescript + * // Get a list of unique author names in uppercase and genre combinations. + * firestore.pipeline().collection("books") + * .distinct(toUppercase(field("author")).as("authorName"), field("genre"), "publishedAt") + * .select("authorName"); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + distinct(options: firestore.Pipelines.DistinctStageOptions): Pipeline; + distinct( + groupOrOptions: + | string + | firestore.Pipelines.Selectable + | firestore.Pipelines.DistinctStageOptions, + ...additionalGroups: Array + ): Pipeline { + const options = + isString(groupOrOptions) || isSelectable(groupOrOptions) + ? {} + : groupOrOptions; + + const groups: Array = + isString(groupOrOptions) || isSelectable(groupOrOptions) + ? [groupOrOptions, ...additionalGroups] + : groupOrOptions.groups; + const convertedGroups: Map = selectablesToMap(groups); + this._validateUserData('distinct', convertedGroups); + + const internalOptions: InternalDistinctStageOptions = { + ...options, + groups: convertedGroups, + }; + + return this._addStage(new Distinct(internalOptions)); + } + + /** + * @beta + * Performs aggregation operations on the documents from previous stages. + * + *

This stage allows you to calculate aggregate values over a set of documents. You define the + * aggregations to perform using `AliasedAggregate` expressions which are typically results of + * calling {@link Expression#as} on `AggregateFunction` instances. + * + * + * @example + * ```typescript + * // Calculate the average rating and the total number of books + * firestore.pipeline().collection("books") + * .aggregate( + * field("rating").average().as("averageRating"), + * countAll().as("totalBooks") + * ); + * ``` + * + * @param accumulator The first `AliasedAggregate`, wrapping an `AggregateFunction` + * and providing a name for the accumulated results. + * @param additionalAccumulators Optional additional `AliasedAggregate`, each wrapping an `AggregateFunction` + * and providing a name for the accumulated results. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + aggregate( + accumulator: firestore.Pipelines.AliasedAggregate, + ...additionalAccumulators: firestore.Pipelines.AliasedAggregate[] + ): Pipeline; + /** + * @beta + * Performs optionally grouped aggregation operations on the documents from previous stages. + * + *

This stage allows you to calculate aggregate values over a set of documents, optionally + * grouped by one or more fields or functions. You can specify: + * + *

    + *
  • **Grouping Fields or Functions:** One or more fields or functions to group the documents + * by. For each distinct combination of values in these fields, a separate group is created. + * If no grouping fields are provided, a single group containing all documents is used. Not + * specifying groups is the same as putting the entire inputs into one group.
  • + *
  • **Accumulators:** One or more accumulation operations to perform within each group. These + * are defined using `AliasedAggregate` expressions, which are typically created by + * calling {@link Expression#as} on `AggregateFunction` instances. Each aggregation + * calculates a value (e.g., sum, average, count) based on the documents within its group.
  • + *
+ * + * + * @example + * ```typescript + * // Calculate the average rating for each genre. + * firestore.pipeline().collection("books") + * .aggregate({ + * accumulators: [average(field("rating")).as("avg_rating")] + * groups: ["genre"] + * }); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new `Pipeline` object with this stage appended to the stage + * list. + */ + aggregate(options: firestore.Pipelines.AggregateStageOptions): Pipeline; + aggregate( + targetOrOptions: + | firestore.Pipelines.AliasedAggregate + | firestore.Pipelines.AggregateStageOptions, + ...rest: firestore.Pipelines.AliasedAggregate[] + ): Pipeline { + const options = isAliasedAggregate(targetOrOptions) ? {} : targetOrOptions; + + const accumulators: Array = + isAliasedAggregate(targetOrOptions) + ? [targetOrOptions, ...rest] + : targetOrOptions.accumulators; + const convertedAccumulators: Map = + aliasedAggregateToMap(accumulators); + const groups: Array = + isAliasedAggregate(targetOrOptions) ? [] : (targetOrOptions.groups ?? []); + const convertedGroups: Map = selectablesToMap(groups); + this._validateUserData('aggregate', convertedGroups); + + const internalOptions: InternalAggregateStageOptions = { + ...options, + accumulators: convertedAccumulators, + groups: convertedGroups, + }; + + return this._addStage(new Aggregate(internalOptions)); + } + + /** + * @beta + * Performs a vector proximity search on the documents from the previous stage, returning the + * K-nearest documents based on the specified query `vectorValue` and `distanceMeasure`. The + * returned documents will be sorted in order from nearest to furthest from the query `vectorValue`. + * + * + * @example + * ```typescript + * // Find the 10 most similar books based on the book description. + * const bookDescription = "Lorem ipsum..."; + * const queryVector: number[] = ...; // compute embedding of `bookDescription` + * + * firestore.pipeline().collection("books") + * .findNearest({ + * field: 'embedding', + * vectorValue: queryVector, + * distanceMeasure: 'euclidean', + * limit: 10, // optional + * distanceField: 'computedDistance' // optional + * }); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + findNearest(options: firestore.Pipelines.FindNearestStageOptions): Pipeline { + const field = toField(options.field); + const vectorValue = vectorToExpr(options.vectorValue); + const distanceField = options.distanceField + ? toField(options.distanceField) + : undefined; + + this._validateUserData('findNearest', field); + + this._validateUserData('findNearest', vectorValue); + + const internalOptions: InternalFindNearestStageOptions = { + ...options, + field, + vectorValue, + distanceField, + }; + + return this._addStage(new FindNearest(internalOptions)); + } + + /** + * @beta + * Fully overwrites all fields in a document with those coming from a nested map. + * + *

This stage allows you to emit a map value as a document. Each key of the map becomes a field + * on the document that contains the corresponding value. + * + * + * @example + * ```typescript + * // Input. + * // { + * // 'name': 'John Doe Jr.', + * // 'parents': { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * // } + * + * // Emit parents as document. + * firestore.pipeline().collection('people').replaceWith('parents'); + * + * // Output + * // { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * ``` + * + * @param fieldName The `Field` field containing the nested map. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + replaceWith(fieldName: string): Pipeline; + /** + * @beta + * Fully overwrites all fields in a document with those coming from a map. + * + *

This stage allows you to emit a map value as a document. Each key of the map becomes a field + * on the document that contains the corresponding value. + * + * + * @example + * ```typescript + * // Input. + * // { + * // 'name': 'John Doe Jr.', + * // 'parents': { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * // } + * + * // Emit parents as document. + * firestore.pipeline().collection('people').replaceWith(map({ + * foo: 'bar', + * info: { + * name: field('name') + * } + * })); + * + * // Output + * // { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * ``` + * + * @param expr An `Expression` that when returned evaluates to a map. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + replaceWith(expr: firestore.Pipelines.Expression): Pipeline; + /** + * @beta + * Fully overwrites all fields in a document with those coming from a map. + * + *

This stage allows you to emit a map value as a document. Each key of the map becomes a field + * on the document that contains the corresponding value. + * + * + * @example + * ```typescript + * // Input. + * // { + * // 'name': 'John Doe Jr.', + * // 'parents': { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * // } + * + * // Emit parents as document. + * firestore.pipeline().collection('people').replaceWith(map({ + * foo: 'bar', + * info: { + * name: field('name') + * } + * })); + * + * // Output + * // { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + replaceWith(options: firestore.Pipelines.ReplaceWithStageOptions): Pipeline; + replaceWith( + valueOrOptions: + | firestore.Pipelines.Expression + | string + | firestore.Pipelines.ReplaceWithStageOptions, + ): Pipeline { + const options = + isString(valueOrOptions) || isExpr(valueOrOptions) ? {} : valueOrOptions; + + const fieldNameOrExpr: string | firestore.Pipelines.Expression = + isString(valueOrOptions) || isExpr(valueOrOptions) + ? valueOrOptions + : valueOrOptions.map; + const mapExpr = fieldOrExpression(fieldNameOrExpr); + this._validateUserData('replaceWith', mapExpr); + + const internalOptions: InternalReplaceWithStageOptions = { + ...options, + map: mapExpr, + }; + return this._addStage(new ReplaceWith(internalOptions)); + } + + /** + * @beta + * Performs a pseudo-random sampling of the documents from the previous stage. + * + *

This stage will filter documents pseudo-randomly. The parameter specifies how number of + * documents to be returned. + * + *

Examples: + * + * @example + * ```typescript + * // Sample 25 books, if available. + * firestore.pipeline().collection('books') + * .sample(25); + * ``` + * + * @param documents The number of documents to sample. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + sample(documents: number): Pipeline; + + /** + * @beta + * Performs a pseudo-random sampling of the documents from the previous stage. + * + *

This stage will filter documents pseudo-randomly. The 'options' parameter specifies how + * sampling will be performed. See `SampleOptions` for more information. + * + *

Examples: + * + * // Sample 10 books, if available. + * firestore.pipeline().collection("books") + * .sample({ documents: 10 }); + * + * // Sample 50% of books. + * firestore.pipeline().collection("books") + * .sample({ percentage: 0.5 }); + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + sample(options: firestore.Pipelines.SampleStageOptions): Pipeline; + sample( + documentsOrOptions: number | firestore.Pipelines.SampleStageOptions, + ): Pipeline { + const options = isNumber(documentsOrOptions) ? {} : documentsOrOptions; + + let rate: number; + let mode: 'documents' | 'percent'; + if (isNumber(documentsOrOptions)) { + rate = documentsOrOptions; + mode = 'documents'; + } else if (isNumber(documentsOrOptions.documents)) { + rate = documentsOrOptions.documents; + mode = 'documents'; + } else { + rate = documentsOrOptions.percentage!; + mode = 'percent'; + } + + const internalOptions: InternalSampleStageOptions = { + ...options, + rate, + mode, + }; + + return this._addStage(new Sample(internalOptions)); + } + + /** + * @beta + * Performs union of all documents from two pipelines, including duplicates. + * + *

This stage will pass through documents from previous stage, and also pass through documents + * from previous stage of the `other` `Pipeline` given in parameter. The order of documents + * emitted from this stage is undefined. + * + * + * @example + * ```typescript + * // Emit documents from books collection and magazines collection. + * firestore.pipeline().collection('books') + * .union(firestore.pipeline().collection('magazines')); + * ``` + * + * @param other The other `Pipeline` that is part of union. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + union(other: firestore.Pipelines.Pipeline): Pipeline; + /** + * @beta + * Performs union of all documents from two pipelines, including duplicates. + * + *

This stage will pass through documents from previous stage, and also pass through documents + * from previous stage of the `other` `Pipeline` given in parameter. The order of documents + * emitted from this stage is undefined. + * + * + * @example + * ```typescript + * // Emit documents from books collection and magazines collection. + * firestore.pipeline().collection('books') + * .union(firestore.pipeline().collection('magazines')); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + union(options: firestore.Pipelines.UnionStageOptions): Pipeline; + union( + otherOrOptions: + | firestore.Pipelines.Pipeline + | firestore.Pipelines.UnionStageOptions, + ): Pipeline { + const options = isPipeline(otherOrOptions) ? {} : otherOrOptions; + + const otherPipeline: firestore.Pipelines.Pipeline = isPipeline( + otherOrOptions, + ) + ? otherOrOptions + : otherOrOptions.other; + const normalizedOtherPipeline = otherPipeline as Pipeline; + + const internalOptions: InternalUnionStageOptions = { + ...options, + other: normalizedOtherPipeline, + }; + return this._addStage(new Union(internalOptions)); + } + + /** + * @beta + * Produces a document for each element in an input array. + * + * For each previous stage document, this stage will emit zero or more augmented documents. The + * input array specified by the `selectable` parameter, will emit an augmented document for each input array element. The input array element will + * augment the previous stage document by setting the `alias` field with the array element value. + * + * When `selectable` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for + * the current input document, returning it as is with the `alias` field absent. + * + * No documents are emitted when `selectable` evaluates to an empty array. + * + * + * @example + * ```typescript + * // Input: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tags": [ "comedy", "space", "adventure" ], ... } + * + * // Emit a book document for each tag of the book. + * firestore.pipeline().collection("books") + * .unnest(field("tags").as('tag'), 'tagIndex'); + * + * // Output: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", "tagIndex": 0, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", "tagIndex": 1, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", "tagIndex": 2, ... } + * ``` + * + * @param selectable A selectable expression defining the field to unnest and the alias to use for each un-nested element in the output documents. + * @param indexField An optional string value specifying the field path to write the offset (starting at zero) into the array the un-nested element is from + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + unnest( + selectable: firestore.Pipelines.Selectable, + indexField?: string, + ): Pipeline; + /** + * @beta + * Produces a document for each element in an input array. + * + * For each previous stage document, this stage will emit zero or more augmented documents. The + * input array specified by the `selectable` parameter, will emit an augmented document for each input array element. The input array element will + * augment the previous stage document by setting the `alias` field with the array element value. + * + * When `selectable` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for + * the current input document, returning it as is with the `alias` field absent. + * + * No documents are emitted when `selectable` evaluates to an empty array. + * + * + * @example + * ```typescript + * // Input: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tags": [ "comedy", "space", "adventure" ], ... } + * + * // Emit a book document for each tag of the book. + * firestore.pipeline().collection("books") + * .unnest(field("tags").as('tag'), 'tagIndex'); + * + * // Output: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", "tagIndex": 0, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", "tagIndex": 1, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", "tagIndex": 2, ... } + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + unnest(options: firestore.Pipelines.UnnestStageOptions): Pipeline; + unnest( + selectableOrOptions: + | firestore.Pipelines.Selectable + | firestore.Pipelines.UnnestStageOptions, + indexField?: string, + ): Pipeline { + const options = isSelectable(selectableOrOptions) + ? {} + : selectableOrOptions; + + const selectable: firestore.Pipelines.Selectable = isSelectable( + selectableOrOptions, + ) + ? selectableOrOptions + : selectableOrOptions.selectable; + const alias = selectable._alias; + const expr = selectable._expr as Expression; + + const indexFieldName = isSelectable(selectableOrOptions) + ? indexField + : selectableOrOptions.indexField; + const normalizedIndexField = indexFieldName + ? field(indexFieldName) + : undefined; + + const internalOptions: InternalUnnestStageOptions = { + ...options, + alias, + expr, + indexField: normalizedIndexField, + }; + return this._addStage(new Unnest(internalOptions)); + } + + /** + * @beta + * Sorts the documents from previous stages based on one or more `Ordering` criteria. + * + *

This stage allows you to order the results of your pipeline. You can specify multiple + * `Ordering` instances to sort by multiple fields in ascending or descending order. If documents + * have the same value for a field used for sorting, the next specified ordering will be used. If + * all orderings result in equal comparison, the documents are considered equal and the order is + * unspecified. + * + * + * @example + * ```typescript + * // Sort books by rating in descending order, and then by title in ascending order for books + * // with the same rating + * firestore.pipeline().collection("books") + * .sort( + * Ordering.of(field("rating")).descending(), + * Ordering.of(field("title")) // Ascending order is the default + * ); + * ``` + * + * @param ordering The first `Ordering` instance specifying the sorting criteria. + * @param additionalOrderings Optional additional `Ordering` instances specifying the additional sorting criteria. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + sort( + ordering: firestore.Pipelines.Ordering, + ...additionalOrderings: firestore.Pipelines.Ordering[] + ): Pipeline; + /** + * @beta + * Sorts the documents from previous stages based on one or more `Ordering` criteria. + * + *

This stage allows you to order the results of your pipeline. You can specify multiple + * `Ordering` instances to sort by multiple fields in ascending or descending order. If documents + * have the same value for a field used for sorting, the next specified ordering will be used. If + * all orderings result in equal comparison, the documents are considered equal and the order is + * unspecified. + * + * + * @example + * ```typescript + * // Sort books by rating in descending order, and then by title in ascending order for books + * // with the same rating + * firestore.pipeline().collection("books") + * .sort( + * Ordering.of(field("rating")).descending(), + * Ordering.of(field("title")) // Ascending order is the default + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + sort(options: firestore.Pipelines.SortStageOptions): Pipeline; + sort( + orderingOrOptions: + | firestore.Pipelines.Ordering + | firestore.Pipelines.SortStageOptions, + ...additionalOrderings: firestore.Pipelines.Ordering[] + ): Pipeline { + const options = isOrdering(orderingOrOptions) ? {} : orderingOrOptions; + + const orderings: Array = isOrdering( + orderingOrOptions, + ) + ? [orderingOrOptions, ...additionalOrderings] + : orderingOrOptions.orderings; + const normalizedOrderings = orderings as Array; + this._validateUserData('sort', normalizedOrderings); + + const internalOptions: InternalSortStageOptions = { + ...options, + orderings: normalizedOrderings, + }; + + return this._addStage(new Sort(internalOptions)); + } + + /** + * @beta + * Adds a raw stage to the pipeline. + * + *

This method provides a flexible way to extend the pipeline's functionality by adding custom + * stages. Each raw stage is defined by a unique `name` and a set of `params` that control its + * behavior. + * + * @example + * Assuming there is no 'where' stage available in SDK: + * + * @example + * ```typescript + * // Assume we don't have a built-in 'where' stage + * firestore.pipeline().collection('books') + * .rawStage('where', [field('published').lessThan(1900)]) // Custom 'where' stage + * .select('title', 'author'); + * ``` + * + * @param name - The unique name of the raw stage to add. + * @param params - A list of parameters to configure the raw stage's behavior. + * @param options - An object of key value pairs that specifies optional parameters for the stage. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + rawStage( + name: string, + params: unknown[], + options?: {[key: string]: Expression | unknown}, + ): Pipeline { + // Convert input values to Expressions. + // We treat objects as mapValues and arrays as arrayValues, + // this is unlike the default conversion for objects and arrays + // passed to an expression. + const expressionParams = params.map((value: unknown) => { + if (value instanceof Expression) { + return value; + } else if (value instanceof AggregateFunction) { + return value; + } else if (isPlainObject(value)) { + return _mapValue(value as Record); + } else { + return constant(value); + } + }); + + expressionParams.forEach(param => { + if (hasUserData(param)) { + param._validateUserData(!!this.db._settings.ignoreUndefinedProperties); + } + }); + return this._addStage(new RawStage(name, expressionParams, options ?? {})); + } + + /** + * @beta + * Executes this pipeline and returns a Promise to represent the asynchronous operation. + * + *

The returned Promise can be used to track the progress of the pipeline execution + * and retrieve the results (or handle any errors) asynchronously. + * + *

The pipeline results are returned in a `PipelineSnapshot` object, which contains a list of + * `PipelineResult` objects. Each `PipelineResult` typically represents a single key/value map that + * has passed through all the stages of the pipeline, however this might differ depending on the stages involved + * in the pipeline. For example: + * + *

    + *
  • If there are no stages or only transformation stages, each `PipelineResult` + * represents a single document.
  • + *
  • If there is an aggregation, only a single `PipelineResult` is returned, + * representing the aggregated results over the entire dataset .
  • + *
  • If there is an aggregation stage with grouping, each `PipelineResult` represents a + * distinct group and its associated aggregated values.
  • + *
+ * + * + * @example + * ```typescript + * const futureResults = await firestore.pipeline().collection('books') + * .where(greaterThan(field('rating'), 4.5)) + * .select('title', 'author', 'rating') + * .execute(); + * ``` + * + * @param pipelineExecuteOptions - Optionally specify pipeline execution behavior. + * @returns A Promise representing the asynchronous pipeline execution. + */ + execute( + pipelineExecuteOptions?: firestore.Pipelines.PipelineExecuteOptions, + ): Promise { + return this._execute(undefined, pipelineExecuteOptions).then(response => { + const results = response.result || []; + const executionTime = response.executionTime; + const stats = response.explainStats; + + return new PipelineSnapshot(this, results, executionTime, stats); + }); + } + + _execute( + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + pipelineExecuteOptions?: firestore.Pipelines.PipelineExecuteOptions, + ): Promise { + const util = new ExecutionUtil(this.db, this.db._serializer!); + const structuredPipeline = this._toStructuredPipeline( + pipelineExecuteOptions, + ); + return util + ._getResponse(structuredPipeline, transactionOrReadTime) + .then(result => result!); + } + + _toStructuredPipeline( + pipelineExecuteOptions?: firestore.Pipelines.PipelineExecuteOptions, + ): StructuredPipeline { + const structuredPipelineOptions = pipelineExecuteOptions ?? {}; + const optionsOverride = pipelineExecuteOptions?.rawOptions ?? {}; + return new StructuredPipeline( + this, + structuredPipelineOptions, + optionsOverride, + ); + } + + /** + * @beta + * Executes this pipeline and streams the results as `PipelineResult`s. + * + * @returns {Stream.} A stream of + * PipelineResult. + * + * @example + * ```typescript + * firestore.pipeline().collection('books') + * .where(greaterThan(field('rating'), 4.5)) + * .select('title', 'author', 'rating') + * .stream() + * .on('data', (pipelineResult) => {}) + * .on('end', () => {}); + * ``` + */ + stream(): NodeJS.ReadableStream { + const util = new ExecutionUtil(this.db, this.db._serializer!); + // TODO(pipelines) support options + const structuredPipeline = this._toStructuredPipeline(); + return util.stream(structuredPipeline, undefined); + } + + _toProto(): api.IPipeline { + const stages: IStage[] = this.stages.map(stage => + stage._toProto(this.db._serializer!), + ); + return {stages}; + } + + /** + * @beta + * Validates user data for each expression in the expressionMap. + * @param name Name of the calling function. Used for error messages when invalid user data is encountered. + * @param val + * @returns the expressionMap argument. + * @private + */ + _validateUserData< + T extends Map | HasUserData[] | HasUserData, + >(_: string, val: T): T { + const ignoreUndefinedProperties = + !!this.db._settings.ignoreUndefinedProperties; + if (hasUserData(val)) { + val._validateUserData(ignoreUndefinedProperties); + } else if (Array.isArray(val)) { + val.forEach(readableData => { + readableData._validateUserData(ignoreUndefinedProperties); + }); + } else { + val.forEach(expr => expr._validateUserData(ignoreUndefinedProperties)); + } + return val; + } +} + +/** + * @beta + * A wrapper object to access explain stats if explain or analyze + * was enabled for the Pipeline query execution. + */ +export class ExplainStats implements firestore.Pipelines.ExplainStats { + private static protoRoot: ProtoRoot | undefined = undefined; + + /** + * @beta + * @private + * @internal + */ + static async _ensureMessageTypesLoaded(): Promise { + if (ExplainStats.protoRoot) { + return; + } + this.protoRoot = await loadProtos( + '../protos/google/protobuf/wrappers.proto', + ); + } + + /** + * @beta + * @private + * @internal + * @hideconstructor + * @param _value + */ + constructor(private readonly explainStatsData: google.protobuf.IAny) {} + + /** + * @beta + * Decode an ExplainStats proto message into a value. + * @private + * @internal + * @param explainStatsMessage + */ + _decode(): unknown { + if (!ExplainStats.protoRoot) { + throw new Error( + 'Ensure message types are loaded before attempting to decode ExplainStats', + ); + } + + if (!this.explainStatsData.value) { + throw new Error('Unexpected explainStatsMessage without data'); + } + + if (!this.explainStatsData.type_url) { + throw new Error('Unexpected explainStatsMessage without type_url'); + } + + const typeUrl = this.explainStatsData.type_url; + let reflectionObject: ReflectionObject | null = null; + const NAMESPACE = 'type.googleapis.com/'; + + if ( + !typeUrl.startsWith(NAMESPACE) || + !(reflectionObject = ExplainStats.protoRoot.lookup( + typeUrl.slice(NAMESPACE.length), + )) || + !(reflectionObject instanceof MessageType) + ) { + throw new Error( + `Unsupported explainStatsMessage type_url "${this.explainStatsData.type_url}". Use \`.rawMessage\` to get access to the encoded explainStats message and perform the protobuf parsing in your application.`, + ); + } + + const messageType = reflectionObject as MessageType; + + return messageType.toObject(messageType.decode(this.explainStatsData.value)) + .value; + } + + /** + * @beta + * When explain stats were requested with `outputFormat = 'text'`, this returns + * the explain stats string verbatium as returned from the Firestore backend. + * + * If explain stats were requested with `outputFormat = 'json'`, this returns + * the explain stats as stringified JSON, which was returned from the Firestore backend. + */ + get text(): string { + const value = this._decode(); + if (isString(value)) { + return value; + } + + throw new Error( + "Explain stats is not in a string format, ensure you requested an `explainOptions.outputFormat` that returns a string value, such as 'text'.", + ); + } + + /** + * @beta + * Returns the explain stats in an encoded proto format, as returned from the Firestore backend. + * The caller is responsible for unpacking this proto message. + */ + get rawData(): { + type_url?: string | null; + value?: Uint8Array | null; + } { + return this.explainStatsData; + } +} + +/** + * @beta + * Represents the results of a Firestore pipeline execution. + * + * A `PipelineSnapshot` contains zero or more `PipelineResult` objects + * representing the documents returned by a pipeline query. It provides methods + * to iterate over the documents and access metadata about the query results. + * + * @example + * ```typescript + * const snapshot: PipelineSnapshot = await firestore + * .pipeline() + * .collection('myCollection') + * .where(field('value').greaterThan(10)) + * .execute(); + * + * snapshot.results.forEach(doc => { + * console.log(doc.id, '=>', doc.data()); + * }); + * ``` + */ +export class PipelineSnapshot implements firestore.Pipelines.PipelineSnapshot { + private readonly _pipeline: Pipeline; + private readonly _executionTime: Timestamp | undefined; + private readonly _results: PipelineResult[]; + private readonly _explainStats: ExplainStats | undefined; + + constructor( + pipeline: Pipeline, + results: PipelineResult[], + executionTime?: Timestamp, + explainStats?: ExplainStats, + ) { + this._pipeline = pipeline; + this._executionTime = executionTime; + this._results = results; + this._explainStats = explainStats; + } + + /** + * @beta + * The Pipeline on which you called `execute()` in order to get this + * `PipelineSnapshot`. + */ + get pipeline(): Pipeline { + return this._pipeline; + } + + /** + * @beta An array of all the results in the `PipelineSnapshot`. */ + get results(): PipelineResult[] { + return this._results; + } + + /** + * @beta + * The time at which the pipeline producing this result is executed. + * + * @type {Timestamp} + * @readonly + * + */ + get executionTime(): Timestamp { + if (this._executionTime === undefined) { + throw new Error( + "'executionTime' is expected to exist, but it is undefined", + ); + } + return this._executionTime; + } + + /** + * @beta + * Return stats from query explain. + * + * If `explainOptions.mode` was set to `execute` or left unset, then this returns `undefined`. + */ + get explainStats(): ExplainStats | undefined { + return this._explainStats; + } +} + +/** + * @beta + * A PipelineResult contains data read from a Firestore Pipeline. The data can be extracted with the + * `data()` or `get(String)` methods. + * + *

If the PipelineResult represents a non-document result, `ref` will return a undefined + * value. + */ +export class PipelineResult implements firestore.Pipelines.PipelineResult { + private readonly _ref: DocumentReference | undefined; + private _serializer: Serializer; + public readonly _executionTime: Timestamp | undefined; + public readonly _createTime: Timestamp | undefined; + public readonly _updateTime: Timestamp | undefined; + + /** + * @beta + * @private + * @internal + * + * @param serializer The serializer used to encode/decode protobuf. + * @param ref The reference to the document. + * @param _fieldsProto The fields of the Firestore `Document` Protobuf backing + * this document (or undefined if the document does not exist). + * @param readTime The time when this result was read (or undefined if + * the document exists only locally). + * @param createTime The time when the document was created if the result is a document, undefined otherwise. + * @param updateTime The time when the document was last updated if the result is a document, undefined otherwise. + */ + constructor( + serializer: Serializer, + /** + * @beta + * @internal + * @private + **/ + readonly _fieldsProto: ApiMapValue, + ref?: DocumentReference, + readTime?: Timestamp, + createTime?: Timestamp, + updateTime?: Timestamp, + ) { + this._ref = ref; + this._serializer = serializer; + this._executionTime = readTime; + this._createTime = createTime; + this._updateTime = updateTime; + } + + /** + * @beta + * The reference of the document, if it is a document; otherwise `undefined`. + */ + get ref(): DocumentReference | undefined { + return this._ref; + } + + /** + * @beta + * The ID of the document for which this PipelineResult contains data, if it is a document; otherwise `undefined`. + * + * @type {string} + * @readonly + * + */ + get id(): string | undefined { + return this._ref?.id; + } + + /** + * @beta + * The time the document was created. Undefined if this result is not a document. + * + * @type {Timestamp|undefined} + * @readonly + */ + get createTime(): Timestamp | undefined { + return this._createTime; + } + + /** + * @beta + * The time the document was last updated (at the time the snapshot was + * generated). Undefined if this result is not a document. + * + * @type {Timestamp|undefined} + * @readonly + */ + get updateTime(): Timestamp | undefined { + return this._updateTime; + } + + /** + * @beta + * Retrieves all fields in the result as an object. + * + * @returns {T} An object containing all fields in the document. + * + * @example + * ``` + * let p = firestore.pipeline().collection('col'); + * + * p.execute().then(results => { + * let data = results[0].data(); + * console.log(`Retrieved data: ${JSON.stringify(data)}`); + * }); + * ``` + */ + data(): firestore.DocumentData { + const fields = this._fieldsProto; + + const obj: firestore.DocumentData = {}; + for (const prop of Object.keys(fields)) { + obj[prop] = this._serializer.decodeValue(fields[prop]); + } + return obj; + } + + /** + * @beta + * Retrieves the field specified by `field`. + * + * @param {string|FieldPath} fieldPath The field path + * (e.g. 'foo' or 'foo.bar') to a specific field. + * @returns {*} The data at the specified field location or undefined if no + * such field exists. + * + * @example + * ``` + * let p = firestore.pipeline().collection('col'); + * + * p.execute().then(results => { + * let field = results[0].get('a.b'); + * console.log(`Retrieved field value: ${field}`); + * }); + * ``` + */ + // We deliberately use `any` in the external API to not impose type-checking + // on end users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(fieldPath: string | FieldPath): any { + validateFieldPath('field', fieldPath); + + const protoField = this.protoField(fieldPath); + + if (protoField === undefined) { + return undefined; + } + + return this._serializer.decodeValue(protoField); + } + + /** + * @beta + * Retrieves the field specified by 'fieldPath' in its Protobuf JS + * representation. + * + * @private + * @internal + * @param field The path (e.g. 'foo' or 'foo.bar') to a specific field. + * @returns The Protobuf-encoded data at the specified field location or + * undefined if no such field exists. + */ + protoField(field: string | FieldPath): api.IValue | undefined { + let fields: ApiMapValue | api.IValue | undefined = this._fieldsProto; + + if (fields === undefined) { + return undefined; + } + + const components = FieldPath.fromArgument(field).toArray(); + while (components.length > 1) { + fields = (fields as ApiMapValue)[components.shift()!]; + + if (!fields || !fields.mapValue) { + return undefined; + } + + fields = fields.mapValue.fields!; + } + + return (fields as ApiMapValue)[components[0]]; + } + + /** + * @beta + * Returns true if the document's data and path in this `PipelineResult` is + * equal to the provided value. + * + * @param {*} other The value to compare against. + * @returns {boolean} true if this `PipelineResult` is equal to the provided + * value. + */ + isEqual(other: PipelineResult): boolean { + return ( + this === other || + (isOptionalEqual(this.ref, other.ref) && + deepEqual(this._fieldsProto, other._fieldsProto)) + ); + } +} diff --git a/handwritten/firestore/dev/src/pipelines/stage.ts b/handwritten/firestore/dev/src/pipelines/stage.ts new file mode 100644 index 00000000000..9695624fbdd --- /dev/null +++ b/handwritten/firestore/dev/src/pipelines/stage.ts @@ -0,0 +1,679 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import * as firestore from '@google-cloud/firestore'; +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; + +import {DocumentReference} from '../reference/document-reference'; +import {ProtoSerializable, Serializer} from '../serializer'; + +import { + AggregateFunction, + BooleanExpression, + Expression, + Field, + field, + Ordering, +} from './expression'; +import {OptionsUtil} from './options-util'; +import {CollectionReference} from '../reference/collection-reference'; + +/** + * Interface for Stage classes. + */ +export interface Stage extends ProtoSerializable { + name: string; + + _toProto(serializer: Serializer): api.Pipeline.IStage; +} + +/** + * Internal options for RemoveFields stage. + */ +export type InternalRemoveFieldsStageOptions = Omit< + firestore.Pipelines.RemoveFieldsStageOptions, + 'fields' +> & { + fields: Array; +}; + +/** + * RemoveFields stage. + */ +export class RemoveFields implements Stage { + name = 'remove_fields'; + readonly optionsUtil = new OptionsUtil({}); + + constructor(private options: InternalRemoveFieldsStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: this.options.fields.map(f => serializer.encodeValue(f)!), + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Internal options for Aggregate stage. + */ +export type InternalAggregateStageOptions = Omit< + firestore.Pipelines.AggregateStageOptions, + 'groups' | 'accumulators' +> & { + groups: Map; + accumulators: Map; +}; + +/** + * Aggregate stage. + */ +export class Aggregate implements Stage { + name = 'aggregate'; + readonly optionsUtil = new OptionsUtil({}); + + constructor(private options: InternalAggregateStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [ + serializer.encodeValue(this.options.accumulators)!, + serializer.encodeValue(this.options.groups)!, + ], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Internal options for Distinct stage. + */ +export type InternalDistinctStageOptions = Omit< + firestore.Pipelines.DistinctStageOptions, + 'groups' +> & { + groups: Map; +}; + +/** + * Distinct stage. + */ +export class Distinct implements Stage { + name = 'distinct'; + readonly optionsUtil = new OptionsUtil({}); + + constructor(private options: InternalDistinctStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [serializer.encodeValue(this.options.groups)!], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Internal options for Collection stage. + */ +export type InternalCollectionStageOptions = Omit< + firestore.Pipelines.CollectionStageOptions, + 'collection' +> & { + collection: CollectionReference; +}; + +/** + * Collection stage. + */ +export class CollectionSource implements Stage { + name = 'collection'; + readonly optionsUtil = new OptionsUtil({ + forceIndex: { + serverName: 'force_index', + }, + }); + readonly collectionPath: string; + + constructor(private options: InternalCollectionStageOptions) { + this.collectionPath = this.options.collection.path; + // prepend slash to collection string + if (!this.collectionPath.startsWith('/')) { + this.collectionPath = '/' + this.collectionPath; + } + } + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [serializer.encodeReference(this.collectionPath)], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Internal options for CollectionGroup stage. + */ +export type InternalCollectionGroupStageOptions = + firestore.Pipelines.CollectionGroupStageOptions; + +/** + * CollectionGroup stage + */ +export class CollectionGroupSource implements Stage { + name = 'collection_group'; + readonly optionsUtil = new OptionsUtil({ + forceIndex: { + serverName: 'force_index', + }, + }); + + constructor(private options: InternalCollectionGroupStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [ + serializer.encodeReference(''), + serializer.encodeValue(this.options.collectionId)!, + ], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Internal options for Database stage. + */ +export type InternalDatabaseStageOptions = + firestore.Pipelines.DatabaseStageOptions; + +/** + * Database stage. + */ +export class DatabaseSource implements Stage { + name = 'database'; + readonly optionsUtil = new OptionsUtil({}); + + constructor(private options: InternalDatabaseStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Internal options for Documents stage. + */ +export type InternalDocumentsStageOptions = Omit< + firestore.Pipelines.DocumentsStageOptions, + 'docs' +> & { + docs: Array; +}; + +/** + * Documents stage. + */ +export class DocumentsSource implements Stage { + name = 'documents'; + readonly optionsUtil = new OptionsUtil({}); + readonly formattedPaths: string[]; + + constructor(private options: InternalDocumentsStageOptions) { + this.formattedPaths = options.docs.map(ref => '/' + ref.path); + } + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: this.formattedPaths.map(p => serializer.encodeReference(p)!), + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Internal options for Where stage. + */ +export type InternalWhereStageOptions = Omit< + firestore.Pipelines.WhereStageOptions, + 'condition' +> & { + condition: BooleanExpression; +}; + +/** + * Where stage. + */ +export class Where implements Stage { + name = 'where'; + readonly optionsUtil = new OptionsUtil({}); + + constructor(private options: InternalWhereStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [this.options.condition._toProto(serializer)], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Internal options for FindNearest stage. + */ +export type InternalFindNearestStageOptions = Omit< + firestore.Pipelines.FindNearestStageOptions, + 'vectorValue' | 'field' | 'distanceField' +> & { + vectorValue: Expression; + field: Field; + distanceField?: Field; +}; + +/** + * FindNearest stage. + */ +export class FindNearest implements Stage { + name = 'find_nearest'; + readonly optionsUtil = new OptionsUtil({ + limit: { + serverName: 'limit', + }, + distanceField: { + serverName: 'distance_field', + }, + }); + + constructor(private _options: InternalFindNearestStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [ + serializer.encodeValue(this._options.field)!, + serializer.encodeValue(this._options.vectorValue)!, + serializer.encodeValue(this._options.distanceMeasure)!, + ], + options: this.optionsUtil.getOptionsProto( + serializer, + this._options, + this._options.rawOptions, + ), + }; + } +} + +/** + * Internal options for Sample stage. + */ +export type InternalSampleStageOptions = Omit< + firestore.Pipelines.SampleStageOptions, + 'percentage' | 'documents' +> & { + rate: number; + mode: 'percent' | 'documents'; +}; + +/** + * Sample stage. + */ +export class Sample implements Stage { + name = 'sample'; + readonly optionsUtil = new OptionsUtil({}); + + constructor(private options: InternalSampleStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [ + serializer.encodeValue(this.options.rate)!, + serializer.encodeValue(this.options.mode)!, + ], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Internal options for Union stage. + */ +export type InternalUnionStageOptions = firestore.Pipelines.UnionStageOptions; + +/** + * Union stage. + */ +export class Union implements Stage { + name = 'union'; + readonly optionsUtil = new OptionsUtil({}); + + constructor(private options: InternalUnionStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [serializer.encodeValue(this.options.other)!], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Internal options for Unnest stage. + */ +export type InternalUnnestStageOptions = Omit< + firestore.Pipelines.UnnestStageOptions, + 'selectable' | 'indexField' +> & { + alias: string; + expr: Expression; + indexField?: Field; +}; + +/** + * Unnest stage. + */ +export class Unnest implements Stage { + name = 'unnest'; + readonly optionsUtil = new OptionsUtil({ + indexField: { + serverName: 'index_field', + }, + }); + + constructor(private options: InternalUnnestStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [ + serializer.encodeValue(this.options.expr)!, + serializer.encodeValue(field(this.options.alias))!, + ], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Internal options for Limit stage. + */ +export type InternalLimitStageOptions = firestore.Pipelines.LimitStageOptions; + +/** + * Limit stage. + */ +export class Limit implements Stage { + name = 'limit'; + readonly optionsUtil = new OptionsUtil({}); + + constructor(private options: InternalLimitStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [serializer.encodeValue(this.options.limit)!], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Internal options for Offset stage. + */ +export type InternalOffsetStageOptions = firestore.Pipelines.OffsetStageOptions; + +/** + * Offset stage. + */ +export class Offset implements Stage { + name = 'offset'; + readonly optionsUtil = new OptionsUtil({}); + + constructor(private options: InternalOffsetStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [serializer.encodeValue(this.options.offset)!], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Internal options for ReplaceWith stage. + */ +export type InternalReplaceWithStageOptions = Omit< + firestore.Pipelines.ReplaceWithStageOptions, + 'map' +> & { + map: Expression; +}; + +/** + * ReplaceWith stage. + */ +export class ReplaceWith implements Stage { + name = 'replace_with'; + readonly optionsUtil = new OptionsUtil({}); + + constructor(private options: InternalReplaceWithStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [ + serializer.encodeValue(this.options.map)!, + serializer.encodeValue('full_replace'), + ], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Internal options for Select stage. + */ +export type InternalSelectStageOptions = Omit< + firestore.Pipelines.SelectStageOptions, + 'selections' +> & { + selections: Map; +}; + +/** + * Select stage. + */ +export class Select implements Stage { + name = 'select'; + readonly optionsUtil = new OptionsUtil({}); + + constructor(private options: InternalSelectStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [serializer.encodeValue(this.options.selections)!], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Internal options for AddFields stage. + */ +export type InternalAddFieldsStageOptions = Omit< + firestore.Pipelines.AddFieldsStageOptions, + 'fields' +> & { + fields: Map; +}; + +/** + * AddFields stage. + */ +export class AddFields implements Stage { + name = 'add_fields'; + readonly optionsUtil = new OptionsUtil({}); + + constructor(private options: InternalAddFieldsStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [serializer.encodeValue(this.options.fields)!], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Internal options for Sort stage. + */ +export type InternalSortStageOptions = Omit< + firestore.Pipelines.SortStageOptions, + 'orderings' +> & { + orderings: Array; +}; + +/** + * Sort stage. + */ +export class Sort implements Stage { + name = 'sort'; + readonly optionsUtil = new OptionsUtil({}); + + constructor(private options: InternalSortStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: this.options.orderings.map(o => serializer.encodeValue(o)!), + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.rawOptions, + ), + }; + } +} + +/** + * Raw stage. + */ +export class RawStage implements Stage { + readonly optionsUtil = new OptionsUtil({}); + + /** + * @private + * @internal + */ + constructor( + public name: string, + private params: Array, + private rawOptions: Record, + ) {} + + /** + * @internal + * @private + */ + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: this.params.map(o => o._toProto(serializer)), + options: this.optionsUtil.getOptionsProto( + serializer, + {}, + this.rawOptions, + ), + }; + } +} diff --git a/handwritten/firestore/dev/src/pipelines/structured-pipeline.ts b/handwritten/firestore/dev/src/pipelines/structured-pipeline.ts new file mode 100644 index 00000000000..bd74d236997 --- /dev/null +++ b/handwritten/firestore/dev/src/pipelines/structured-pipeline.ts @@ -0,0 +1,93 @@ +/** + * @license + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {ProtoSerializable, Serializer} from '../serializer'; +import {google} from '../../protos/firestore_v1_proto_api'; +import IStructuredPipeline = google.firestore.v1.IStructuredPipeline; +import IPipeline = google.firestore.v1.IPipeline; +import {OptionsUtil} from './options-util'; + +/** + * Defines the known options for StructuredPipeline and the valid values of + * each option. + */ +export type StructuredPipelineOptions = { + indexMode?: 'recommended'; + explainOptions?: { + mode?: 'execute' | 'explain' | 'analyze'; + outputFormat?: 'text'; + }; +}; + +/** + * StructuredPipeline class represents the StructuredPipeline proto object + * which is a parameter to the ExecutePipelineRequest proto and executePipeline RPC. + * + * StructuredPipeline encapsulates the Pipeline and PipelineOptions and supports + * serialization of this data to a StructuredPipeline proto. + */ +export class StructuredPipeline + implements ProtoSerializable +{ + /** + * OptionsUtil which defines the known StructuredPipelineOptions. + * This maps client side options to their server names and structure. + */ + readonly optionsUtil = new OptionsUtil({ + indexMode: { + serverName: 'index_mode', + }, + explainOptions: { + serverName: 'explain_options', + nestedOptions: { + mode: { + serverName: 'mode', + }, + outputFormat: { + serverName: 'output_format', + }, + }, + }, + }); + + /** + * StructuredPipeline constructor. + * @param pipeline - Pipeline executed by this StructuredPipeline. + * @param options - Known structured pipeline options. + * @param optionsOverride - Key value pairs of known and unknown options. + */ + constructor( + private pipeline: ProtoSerializable, + private options: StructuredPipelineOptions, + private optionsOverride: Record, + ) {} + + /** + * Serializes this object to a StructuredPipeline proto. + * @param serializer - Serializer instance used to perform serialization of this object. + */ + _toProto(serializer: Serializer): IStructuredPipeline { + return { + pipeline: this.pipeline._toProto(serializer), + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.optionsOverride, + ), + }; + } +} diff --git a/handwritten/firestore/dev/src/pool.ts b/handwritten/firestore/dev/src/pool.ts new file mode 100644 index 00000000000..5bb4550171b --- /dev/null +++ b/handwritten/firestore/dev/src/pool.ts @@ -0,0 +1,550 @@ +/*! + * Copyright 2018 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {GoogleError} from 'google-gax'; +import * as assert from 'assert'; + +import {logger} from './logger'; +import {Deferred, requestTag as generateTag} from './util'; + +export const CLIENT_TERMINATED_ERROR_MSG = + 'The client has already been terminated'; + +/** + * An auto-resizing pool that distributes concurrent operations over multiple + * clients of type `T`. + * + * ClientPool is used within Firestore to manage a pool of GAPIC clients and + * automatically initializes multiple clients if we issue more than 100 + * concurrent operations. + * + * @private + * @internal + */ +export class ClientPool { + private grpcEnabled = false; + + /** + * Stores each active clients and how many operations it has outstanding. + */ + private readonly activeClients = new Map< + T, + {activeRequestCount: number; grpcEnabled: boolean} + >(); + + /** + * A set of clients that have seen RST_STREAM errors (see + * https://github.com/googleapis/nodejs-firestore/issues/1023) and should + * no longer be used. + */ + private readonly failedClients = new Set(); + + /** + * A mapping from "client" objects to their corresponding IDs. These IDs have + * no semantic meaning but are used for logging to enable tracing the events + * of a particular client over time (such as creating, acquiring, and + * releasing). + */ + private readonly clientIdByClient = new WeakMap(); + + /** + * An object that can be specified to `logger()` to lazily calculate a long + * log message that includes all client IDs of active and pending clients. + */ + private readonly lazyLogStringForAllClientIds: unknown; + + /** + * Whether the Firestore instance has been terminated. Once terminated, the + * ClientPool can longer schedule new operations. + */ + private terminated = false; + + /** + * Deferred promise that is resolved when there are no active operations on + * the client pool after terminate() has been called. + */ + private readonly terminateDeferred = new Deferred(); + + /** + * A unique identifier for this object, for inclusion in log messages. + */ + private readonly instanceId = 'cpl' + generateTag(); + + /** + * @param concurrentOperationLimit The number of operations that each client + * can handle. + * @param maxIdleClients The maximum number of idle clients to keep before + * garbage collecting. + * @param clientFactory A factory function called as needed when new clients + * are required. + * @param clientDestructor A cleanup function that is called when a client is + * disposed of. + */ + constructor( + private readonly concurrentOperationLimit: number, + private readonly maxIdleClients: number, + private readonly clientFactory: (requiresGrpc: boolean) => T, + private readonly clientDestructor: (client: T) => Promise = () => + Promise.resolve(), + ) { + this.lazyLogStringForAllClientIds = new LazyLogStringForAllClientIds({ + activeClients: this.activeClients, + failedClients: this.failedClients, + clientIdByClient: this.clientIdByClient, + }); + } + + /** + * Returns an already existing client if it has less than the maximum number + * of concurrent operations or initializes and returns a new client. + * + * @private + * @internal + */ + private acquire(requestTag: string, requiresGrpc: boolean): T { + let selectedClient: T | null = null; + let selectedClientRequestCount = -1; + + // Transition to grpc when we see the first operation that requires grpc. + this.grpcEnabled = this.grpcEnabled || requiresGrpc; + + // Require a grpc client for this operation if we have transitioned to grpc. + requiresGrpc = requiresGrpc || this.grpcEnabled; + + for (const [client, metadata] of this.activeClients) { + // Use the "most-full" client that can still accommodate the request + // in order to maximize the number of idle clients as operations start to + // complete. + if ( + !this.failedClients.has(client) && + metadata.activeRequestCount > selectedClientRequestCount && + metadata.activeRequestCount < this.concurrentOperationLimit && + (metadata.grpcEnabled || !requiresGrpc) + ) { + selectedClient = client; + selectedClientRequestCount = metadata.activeRequestCount; + } + } + + if (selectedClient) { + const selectedClientId = this.clientIdByClient.get(selectedClient); + logger( + `ClientPool[${this.instanceId}].acquire`, + requestTag, + 'Re-using existing client [%s] with %s remaining operations', + selectedClientId, + this.concurrentOperationLimit - selectedClientRequestCount, + ); + } else { + const newClientId = 'cli' + generateTag(); + logger( + `ClientPool[${this.instanceId}].acquire`, + requestTag, + 'Creating a new client [%s] (requiresGrpc: %s)', + newClientId, + requiresGrpc, + ); + selectedClient = this.clientFactory(requiresGrpc); + this.clientIdByClient.set(selectedClient, newClientId); + selectedClientRequestCount = 0; + assert( + !this.activeClients.has(selectedClient), + 'The provided client factory returned an existing instance', + ); + } + + this.activeClients.set(selectedClient, { + grpcEnabled: requiresGrpc, + activeRequestCount: selectedClientRequestCount + 1, + }); + + return selectedClient!; + } + + /** + * Reduces the number of operations for the provided client, potentially + * removing it from the pool of active clients. + * @private + * @internal + */ + private async release(requestTag: string, client: T): Promise { + const clientId = this.clientIdByClient.get(client); + const metadata = this.activeClients.get(client); + assert(metadata && metadata.activeRequestCount > 0, 'No active requests'); + + this.activeClients.set(client, { + grpcEnabled: metadata.grpcEnabled, + activeRequestCount: metadata.activeRequestCount - 1, + }); + if (this.terminated && this.opCount === 0) { + this.terminateDeferred.resolve(); + } + + const gcDetermination = this.shouldGarbageCollectClient(client); + logger( + `ClientPool[${this.instanceId}].release`, + requestTag, + 'Releasing client [%s] (gc=%s)', + clientId, + gcDetermination, + ); + + if (!gcDetermination.shouldGarbageCollectClient) { + return; + } + + logger( + `ClientPool[${this.instanceId}].release`, + requestTag, + 'Garbage collecting client [%s] (%s)', + clientId, + this.lazyLogStringForAllClientIds, + ); + + const activeClientDeleted = this.activeClients.delete(client); + this.failedClients.delete(client); + await this.clientDestructor(client); + + logger( + `ClientPool[${this.instanceId}].release`, + requestTag, + 'Garbage collected client [%s] activeClientDeleted=%s (%s)', + clientId, + activeClientDeleted, + this.lazyLogStringForAllClientIds, + ); + } + + /** + * Given the current operation counts, determines if the given client should + * be garbage collected. + * @private + * @internal + */ + private shouldGarbageCollectClient( + client: T, + ): ShouldGarbageCollectClientResult { + const clientMetadata = this.activeClients.get(client)!; + + if (clientMetadata.activeRequestCount !== 0) { + // Don't garbage collect clients that have active requests. + return new ClientHasActiveRequests({ + shouldGarbageCollectClient: false, + clientActiveRequestCount: clientMetadata.activeRequestCount, + }); + } + + if (this.grpcEnabled !== clientMetadata.grpcEnabled) { + // We are transitioning to GRPC. Garbage collect REST clients. + return new PoolIsTransitioningToGrpc({ + shouldGarbageCollectClient: true, + clientActiveRequestCount: clientMetadata.activeRequestCount, + poolGrpcEnabled: this.grpcEnabled, + clientGrpcEnabled: clientMetadata.grpcEnabled, + }); + } + + // Idle clients that have received RST_STREAM errors are always garbage + // collected. + if (this.failedClients.has(client)) { + return new ClientIsFailed({ + shouldGarbageCollectClient: true, + clientActiveRequestCount: clientMetadata.activeRequestCount, + }); + } + + // Otherwise, only garbage collect if we have too much idle capacity (e.g. + // more than 100 idle capacity with default settings). + let idleCapacityCount = 0; + for (const [, metadata] of this.activeClients) { + idleCapacityCount += + this.concurrentOperationLimit - metadata.activeRequestCount; + } + + const maxIdleCapacityCount = + this.maxIdleClients * this.concurrentOperationLimit; + return new IdleCapacity({ + shouldGarbageCollectClient: idleCapacityCount > maxIdleCapacityCount, + clientActiveRequestCount: clientMetadata.activeRequestCount, + idleCapacityCount: idleCapacityCount, + maxIdleCapacityCount: maxIdleCapacityCount, + maxIdleClients: this.maxIdleClients, + concurrentOperationLimit: this.concurrentOperationLimit, + }); + } + + /** + * The number of currently registered clients. + * + * @returns Number of currently registered clients. + * @private + * @internal + */ + // Visible for testing. + get size(): number { + return this.activeClients.size; + } + + /** + * The number of currently active operations. + * + * @returns Number of currently active operations. + * @private + * @internal + */ + // Visible for testing. + get opCount(): number { + let activeOperationCount = 0; + this.activeClients.forEach( + metadata => (activeOperationCount += metadata.activeRequestCount), + ); + return activeOperationCount; + } + + /** + * The currently active clients. + * + * @returns The currently active clients. + * @private + * @internal + */ + // Visible for testing. + get _activeClients(): Map< + T, + {activeRequestCount: number; grpcEnabled: boolean} + > { + return this.activeClients; + } + + /** + * Runs the provided operation in this pool. This function may create an + * additional client if all existing clients already operate at the concurrent + * operation limit. + * + * @param requestTag A unique client-assigned identifier for this operation. + * @param op A callback function that returns a Promise. The client T will + * be returned to the pool when callback finishes. + * @returns A Promise that resolves with the result of `op`. + * @private + * @internal + */ + run( + requestTag: string, + requiresGrpc: boolean, + op: (client: T) => Promise, + ): Promise { + if (this.terminated) { + return Promise.reject(new Error(CLIENT_TERMINATED_ERROR_MSG)); + } + const client = this.acquire(requestTag, requiresGrpc); + + return op(client) + .catch(async (err: GoogleError) => { + if (err.message?.match(/RST_STREAM/)) { + // Once a client has seen a RST_STREAM error, the GRPC channel can + // no longer be used. We mark the client as failed, which ensures that + // we open a new GRPC channel for the next request. + this.failedClients.add(client); + } + await this.release(requestTag, client); + return Promise.reject(err); + }) + .then(async res => { + await this.release(requestTag, client); + return res; + }); + } + + async terminate(): Promise { + this.terminated = true; + + // Wait for all pending operations to complete before terminating. + if (this.opCount > 0) { + logger( + `ClientPool[${this.instanceId}].terminate`, + /* requestTag= */ null, + 'Waiting for %s pending operations to complete before terminating (%s)', + this.opCount, + this.lazyLogStringForAllClientIds, + ); + await this.terminateDeferred.promise; + } + logger( + `ClientPool[${this.instanceId}].terminate`, + /* requestTag= */ null, + 'Closing all active clients (%s)', + this.lazyLogStringForAllClientIds, + ); + for (const [client] of this.activeClients) { + this.activeClients.delete(client); + await this.clientDestructor(client); + } + } +} + +/** + * Helper class that, when logged as a direct argument of `logger()`, will + * lazily evaluate to a long string that contains all IDs of both active and + * failed clients. + */ +class LazyLogStringForAllClientIds { + private readonly activeClients: Map; + private readonly failedClients: Set; + private readonly clientIdByClient: WeakMap; + + constructor(config: { + activeClients: Map; + failedClients: Set; + clientIdByClient: WeakMap; + }) { + this.activeClients = config.activeClients; + this.failedClients = config.failedClients; + this.clientIdByClient = config.clientIdByClient; + } + + toString(): string { + const activeClientsDescription = Array.from(this.activeClients.entries()) + .map( + ([client, metadata]) => + `${this.clientIdByClient.get(client)}=${metadata.activeRequestCount}`, + ) + .sort() + .join(', '); + const failedClientsDescription = Array.from(this.failedClients) + .map(client => `${this.clientIdByClient.get(client)}`) + .sort() + .join(', '); + + return ( + `${this.activeClients.size} active clients: {` + + activeClientsDescription + + '}, ' + + `${this.failedClients.size} failed clients: {` + + failedClientsDescription + + '}' + ); + } +} + +/** + * Minimum data to be included in the objects returned from + * ClientPool.shouldGarbageCollectClient(). + */ +abstract class BaseShouldGarbageCollectClientResult { + abstract readonly name: string; + abstract readonly shouldGarbageCollectClient: boolean; + abstract readonly clientActiveRequestCount: number; + + /** + * Return a terse, one-line string representation. This makes it easy to + * grep through log output to find the logged values. + */ + toString(): string { + const propertyStrings: string[] = []; + for (const propertyName of Object.getOwnPropertyNames(this)) { + const propertyValue = this[propertyName as keyof typeof this]; + propertyStrings.push(`${propertyName}=${propertyValue}`); + } + return '{' + propertyStrings.join(', ') + '}'; + } +} + +class ClientHasActiveRequests extends BaseShouldGarbageCollectClientResult { + override readonly name = 'ClientHasActiveRequests' as const; + override readonly shouldGarbageCollectClient: false; + override readonly clientActiveRequestCount: number; + + constructor(args: { + shouldGarbageCollectClient: false; + clientActiveRequestCount: number; + }) { + super(); + this.shouldGarbageCollectClient = args.shouldGarbageCollectClient; + this.clientActiveRequestCount = args.clientActiveRequestCount; + } +} + +class PoolIsTransitioningToGrpc extends BaseShouldGarbageCollectClientResult { + override readonly name = 'PoolIsTransitioningToGrpc' as const; + override readonly shouldGarbageCollectClient: true; + override readonly clientActiveRequestCount: 0; + readonly poolGrpcEnabled: boolean; + readonly clientGrpcEnabled: boolean; + + constructor(args: { + shouldGarbageCollectClient: true; + clientActiveRequestCount: 0; + poolGrpcEnabled: boolean; + clientGrpcEnabled: boolean; + }) { + super(); + this.shouldGarbageCollectClient = args.shouldGarbageCollectClient; + this.clientActiveRequestCount = args.clientActiveRequestCount; + this.poolGrpcEnabled = args.poolGrpcEnabled; + this.clientGrpcEnabled = args.clientGrpcEnabled; + } +} + +class ClientIsFailed extends BaseShouldGarbageCollectClientResult { + override readonly name = 'ClientIsFailed' as const; + override readonly shouldGarbageCollectClient: true; + override readonly clientActiveRequestCount: 0; + + constructor(args: { + shouldGarbageCollectClient: true; + clientActiveRequestCount: 0; + }) { + super(); + this.shouldGarbageCollectClient = args.shouldGarbageCollectClient; + this.clientActiveRequestCount = args.clientActiveRequestCount; + } +} + +class IdleCapacity extends BaseShouldGarbageCollectClientResult { + override readonly name = 'IdleCapacity' as const; + override readonly shouldGarbageCollectClient: boolean; + override readonly clientActiveRequestCount: 0; + readonly idleCapacityCount: number; + readonly maxIdleCapacityCount: number; + readonly maxIdleClients: number; + readonly concurrentOperationLimit: number; + + constructor(args: { + shouldGarbageCollectClient: boolean; + clientActiveRequestCount: 0; + idleCapacityCount: number; + maxIdleCapacityCount: number; + maxIdleClients: number; + concurrentOperationLimit: number; + }) { + super(); + this.shouldGarbageCollectClient = args.shouldGarbageCollectClient; + this.clientActiveRequestCount = args.clientActiveRequestCount; + this.idleCapacityCount = args.idleCapacityCount; + this.maxIdleCapacityCount = args.maxIdleCapacityCount; + this.maxIdleClients = args.maxIdleClients; + this.concurrentOperationLimit = args.concurrentOperationLimit; + } +} + +/** + * The set of return types from ClientPool.shouldGarbageCollectClient(). + */ +type ShouldGarbageCollectClientResult = + | ClientHasActiveRequests + | PoolIsTransitioningToGrpc + | ClientIsFailed + | IdleCapacity; diff --git a/handwritten/firestore/dev/src/query-partition.ts b/handwritten/firestore/dev/src/query-partition.ts new file mode 100644 index 00000000000..46f25486483 --- /dev/null +++ b/handwritten/firestore/dev/src/query-partition.ts @@ -0,0 +1,171 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; +import * as protos from '../protos/firestore_v1_proto_api'; + +import {FieldOrder} from './reference/field-order'; +import {Query} from './reference/query'; +import {QueryOptions} from './reference/query-options'; +import {FieldPath} from './path'; +import {Serializer} from './serializer'; +import {Firestore} from './index'; + +import api = protos.google.firestore.v1; + +/** + * A split point that can be used in a query as a starting and/or end point for + * the query results. The cursors returned by {@link #startAt} and {@link + * #endBefore} can only be used in a query that matches the constraint of query + * that produced this partition. + * + * @class QueryPartition + */ +export class QueryPartition< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> implements firestore.QueryPartition +{ + private readonly _serializer: Serializer; + private _memoizedStartAt: unknown[] | undefined; + private _memoizedEndBefore: unknown[] | undefined; + + /** @private */ + constructor( + private readonly _firestore: Firestore, + private readonly _collectionId: string, + private readonly _converter: firestore.FirestoreDataConverter< + AppModelType, + DbModelType + >, + private readonly _startAt: api.IValue[] | undefined, + private readonly _endBefore: api.IValue[] | undefined, + ) { + this._serializer = new Serializer(_firestore); + } + + /** + * The cursor that defines the first result for this partition or `undefined` + * if this is the first partition. The cursor value must be + * destructured when passed to `startAt()` (for example with + * `query.startAt(...queryPartition.startAt)`). + * + * @example + * ``` + * const query = firestore.collectionGroup('collectionId'); + * for await (const partition of query.getPartitions(42)) { + * let partitionedQuery = query.orderBy(FieldPath.documentId()); + * if (partition.startAt) { + * partitionedQuery = partitionedQuery.startAt(...partition.startAt); + * } + * if (partition.endBefore) { + * partitionedQuery = partitionedQuery.endBefore(...partition.endBefore); + * } + * const querySnapshot = await partitionedQuery.get(); + * console.log(`Partition contained ${querySnapshot.length} documents`); + * } + * + * ``` + * @type {Array<*>} + * @returns {Array<*>} A cursor value that can be used with {@link + * Query#startAt} or `undefined` if this is the first partition. + */ + get startAt(): unknown[] | undefined { + if (this._startAt && !this._memoizedStartAt) { + this._memoizedStartAt = this._startAt.map(v => + this._serializer.decodeValue(v), + ); + } + + return this._memoizedStartAt; + } + + /** + * The cursor that defines the first result after this partition or + * `undefined` if this is the last partition. The cursor value must be + * destructured when passed to `endBefore()` (for example with + * `query.endBefore(...queryPartition.endBefore)`). + * + * @example + * ``` + * const query = firestore.collectionGroup('collectionId'); + * for await (const partition of query.getPartitions(42)) { + * let partitionedQuery = query.orderBy(FieldPath.documentId()); + * if (partition.startAt) { + * partitionedQuery = partitionedQuery.startAt(...partition.startAt); + * } + * if (partition.endBefore) { + * partitionedQuery = partitionedQuery.endBefore(...partition.endBefore); + * } + * const querySnapshot = await partitionedQuery.get(); + * console.log(`Partition contained ${querySnapshot.length} documents`); + * } + * + * ``` + * @type {Array<*>} + * @returns {Array<*>} A cursor value that can be used with {@link + * Query#endBefore} or `undefined` if this is the last partition. + */ + get endBefore(): unknown[] | undefined { + if (this._endBefore && !this._memoizedEndBefore) { + this._memoizedEndBefore = this._endBefore.map(v => + this._serializer.decodeValue(v), + ); + } + + return this._memoizedEndBefore; + } + + /** + * Returns a query that only encapsulates the documents for this partition. + * + * @example + * ``` + * const query = firestore.collectionGroup('collectionId'); + * for await (const partition of query.getPartitions(42)) { + * const partitionedQuery = partition.toQuery(); + * const querySnapshot = await partitionedQuery.get(); + * console.log(`Partition contained ${querySnapshot.length} documents`); + * } + * + * ``` + * @returns {Query} A query partitioned by a {@link Query#startAt} and + * {@link Query#endBefore} cursor. + */ + toQuery(): Query { + // Since the api.Value to JavaScript type conversion can be lossy (unless + // `useBigInt` is used), we pass the original protobuf representation to the + // created query. + let queryOptions = QueryOptions.forCollectionGroupQuery( + this._collectionId, + this._converter, + ); + queryOptions = queryOptions.with({ + fieldOrders: [new FieldOrder(FieldPath.documentId())], + }); + if (this._startAt !== undefined) { + queryOptions = queryOptions.with({ + startAt: {before: true, values: this._startAt}, + }); + } + if (this._endBefore !== undefined) { + queryOptions = queryOptions.with({ + endAt: {before: true, values: this._endBefore}, + }); + } + return new Query(this._firestore, queryOptions); + } +} diff --git a/handwritten/firestore/dev/src/query-profile.ts b/handwritten/firestore/dev/src/query-profile.ts new file mode 100644 index 00000000000..fa1dcdb4146 --- /dev/null +++ b/handwritten/firestore/dev/src/query-profile.ts @@ -0,0 +1,139 @@ +/*! + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; +import {google} from '../protos/firestore_v1_proto_api'; +import {Serializer} from './serializer'; +import IPlanSummary = google.firestore.v1.IPlanSummary; +import IExecutionStats = google.firestore.v1.IExecutionStats; +import IExplainMetrics = google.firestore.v1.IExplainMetrics; + +/** + * PlanSummary contains information about the planning stage of a query. + * + * @class PlanSummary + */ +export class PlanSummary implements firestore.PlanSummary { + /** + * @private + * @internal + */ + constructor(readonly indexesUsed: Record[]) {} + + /** + * @private + * @internal + */ + static _fromProto( + plan: IPlanSummary | null | undefined, + serializer: Serializer, + ): PlanSummary { + const indexes: Record[] = []; + if (plan && plan.indexesUsed) { + for (const index of plan.indexesUsed) { + indexes.push(serializer.decodeGoogleProtobufStruct(index)); + } + } + return new PlanSummary(indexes); + } +} + +/** + * ExecutionStats contains information about the execution of a query. + * + * @class ExecutionStats + */ +export class ExecutionStats implements firestore.ExecutionStats { + /** + * @private + * @internal + */ + constructor( + readonly resultsReturned: number, + readonly executionDuration: firestore.Duration, + readonly readOperations: number, + readonly debugStats: Record, + ) {} + + /** + * @private + * @internal + */ + static _fromProto( + stats: IExecutionStats | null | undefined, + serializer: Serializer, + ): ExecutionStats | null { + if (stats) { + return new ExecutionStats( + Number(stats.resultsReturned), + { + seconds: Number(stats.executionDuration?.seconds), + nanoseconds: Number(stats.executionDuration?.nanos), + }, + Number(stats.readOperations), + serializer.decodeGoogleProtobufStruct(stats.debugStats), + ); + } + return null; + } +} + +/** + * ExplainMetrics contains information about planning and execution of a query. + * + * @class ExplainMetrics + */ +export class ExplainMetrics implements firestore.ExplainMetrics { + /** + * @private + * @internal + */ + constructor( + readonly planSummary: PlanSummary, + readonly executionStats: ExecutionStats | null, + ) {} + + /** + * @private + * @internal + */ + static _fromProto( + metrics: IExplainMetrics, + serializer: Serializer, + ): ExplainMetrics { + return new ExplainMetrics( + PlanSummary._fromProto(metrics.planSummary, serializer), + ExecutionStats._fromProto(metrics.executionStats, serializer), + ); + } +} + +/** + * ExplainResults contains information about planning, execution, and results + * of a query. + * + * @class ExplainResults + */ +export class ExplainResults implements firestore.ExplainResults { + /** + * @private + * @internal + */ + constructor( + readonly metrics: ExplainMetrics, + readonly snapshot: T | null, + ) {} +} diff --git a/handwritten/firestore/dev/src/rate-limiter.ts b/handwritten/firestore/dev/src/rate-limiter.ts new file mode 100644 index 00000000000..a7985560129 --- /dev/null +++ b/handwritten/firestore/dev/src/rate-limiter.ts @@ -0,0 +1,179 @@ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as assert from 'assert'; +import {logger} from './logger'; + +/** + * A helper that uses the Token Bucket algorithm to rate limit the number of + * operations that can be made in a second. + * + * Before a given request containing a number of operations can proceed, + * RateLimiter determines doing so stays under the provided rate limits. It can + * also determine how much time is required before a request can be made. + * + * RateLimiter can also implement a gradually increasing rate limit. This is + * used to enforce the 500/50/5 rule + * (https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic). + * + * @private + * @internal + */ +export class RateLimiter { + // Number of tokens available. Each operation consumes one token. + availableTokens: number; + + // When the token bucket was last refilled. + lastRefillTimeMillis: number; + + // The last operations per second capacity that was calculated. Used to log + // changes to the maximum QPS. + previousCapacity: number; + + /** + * @param initialCapacity Initial maximum number of operations per second. + * @param multiplier Rate by which to increase the capacity. + * @param multiplierMillis How often the capacity should increase in + * milliseconds. + * @param maximumCapacity Maximum number of allowed operations per second. + * The number of tokens added per second will never exceed this number. + * @param startTimeMillis The starting time in epoch milliseconds that the + * rate limit is based on. Used for testing the limiter. + */ + constructor( + private readonly initialCapacity: number, + private readonly multiplier: number, + private readonly multiplierMillis: number, + readonly maximumCapacity: number, + private readonly startTimeMillis = Date.now(), + ) { + this.availableTokens = initialCapacity; + this.lastRefillTimeMillis = startTimeMillis; + this.previousCapacity = initialCapacity; + } + + /** + * Tries to make the number of operations. Returns true if the request + * succeeded and false otherwise. + * + * @param requestTimeMillis The time used to calculate the number of available + * tokens. Used for testing the limiter. + * @private + * @internal + */ + tryMakeRequest( + numOperations: number, + requestTimeMillis = Date.now(), + ): boolean { + this.refillTokens(requestTimeMillis); + if (numOperations <= this.availableTokens) { + this.availableTokens -= numOperations; + return true; + } + return false; + } + + /** + * Returns the number of ms needed to make a request with the provided number + * of operations. Returns 0 if the request can be made with the existing + * capacity. Returns -1 if the request is not possible with the current + * capacity. + * + * @param requestTimeMillis The time used to calculate the number of available + * tokens. Used for testing the limiter. + * @private + * @internal + */ + getNextRequestDelayMs( + numOperations: number, + requestTimeMillis = Date.now(), + ): number { + this.refillTokens(requestTimeMillis); + if (numOperations < this.availableTokens) { + return 0; + } + + const capacity = this.calculateCapacity(requestTimeMillis); + if (capacity < numOperations) { + return -1; + } + + const requiredTokens = numOperations - this.availableTokens; + return Math.ceil((requiredTokens * 1000) / capacity); + } + + /** + * Refills the number of available tokens based on how much time has elapsed + * since the last time the tokens were refilled. + * + * @param requestTimeMillis The time used to calculate the number of available + * tokens. Used for testing the limiter. + * @private + * @internal + */ + private refillTokens(requestTimeMillis: number): void { + if (requestTimeMillis >= this.lastRefillTimeMillis) { + const elapsedTime = requestTimeMillis - this.lastRefillTimeMillis; + const capacity = this.calculateCapacity(requestTimeMillis); + const tokensToAdd = Math.floor((elapsedTime * capacity) / 1000); + if (tokensToAdd > 0) { + this.availableTokens = Math.min( + capacity, + this.availableTokens + tokensToAdd, + ); + this.lastRefillTimeMillis = requestTimeMillis; + } + } else { + throw new Error( + 'Request time should not be before the last token refill time.', + ); + } + } + + /** + * Calculates the maximum capacity based on the provided date. + * + * @private + * @internal + */ + // Visible for testing. + calculateCapacity(requestTimeMillis: number): number { + assert( + requestTimeMillis >= this.startTimeMillis, + 'startTime cannot be after currentTime', + ); + const millisElapsed = requestTimeMillis - this.startTimeMillis; + const operationsPerSecond = Math.min( + Math.floor( + Math.pow( + this.multiplier, + Math.floor(millisElapsed / this.multiplierMillis), + ) * this.initialCapacity, + ), + this.maximumCapacity, + ); + + if (operationsPerSecond !== this.previousCapacity) { + logger( + 'RateLimiter.calculateCapacity', + null, + `New request capacity: ${operationsPerSecond} operations per second.`, + ); + } + + this.previousCapacity = operationsPerSecond; + return operationsPerSecond; + } +} diff --git a/handwritten/firestore/dev/src/recursive-delete.ts b/handwritten/firestore/dev/src/recursive-delete.ts new file mode 100644 index 00000000000..938c37b53d7 --- /dev/null +++ b/handwritten/firestore/dev/src/recursive-delete.ts @@ -0,0 +1,348 @@ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as firestore from '@google-cloud/firestore'; + +import * as assert from 'assert'; + +import Firestore, { + BulkWriter, + CollectionReference, + DocumentReference, + FieldPath, + Query, + QueryDocumentSnapshot, +} from '.'; +import {Deferred, wrapError} from './util'; +import type {GoogleError} from 'google-gax'; +import {BulkWriterError} from './bulk-writer'; +import {QueryOptions} from './reference/query-options'; +import {StatusCode} from './status-code'; + +/*! + * Datastore allowed numeric IDs where Firestore only allows strings. Numeric + * IDs are exposed to Firestore as __idNUM__, so this is the lowest possible + * negative numeric value expressed in that format. + * + * This constant is used to specify startAt/endAt values when querying for all + * descendants in a single collection. + */ +export const REFERENCE_NAME_MIN_ID = '__id-9223372036854775808__'; + +/*! + * The query limit used for recursive deletes when fetching all descendants of + * the specified reference to delete. This is done to prevent the query stream + * from streaming documents faster than Firestore can delete. + */ +// Visible for testing. +export const RECURSIVE_DELETE_MAX_PENDING_OPS = 5000; + +/*! + * The number of pending BulkWriter operations at which RecursiveDelete + * starts the next limit query to fetch descendants. By starting the query + * while there are pending operations, Firestore can improve BulkWriter + * throughput. This helps prevent BulkWriter from idling while Firestore + * fetches the next query. + */ +export const RECURSIVE_DELETE_MIN_PENDING_OPS = 1000; + +/** + * Class used to store state required for running a recursive delete operation. + * Each recursive delete call should use a new instance of the class. + * @private + * @internal + */ +export class RecursiveDelete { + /** + * The number of deletes that failed with a permanent error. + * @private + * @internal + */ + private errorCount = 0; + + /** + * The most recently thrown error. Used to populate the developer-facing + * error message when the recursive delete operation completes. + * @private + * @internal + */ + private lastError: GoogleError | BulkWriterError | undefined; + + /** + * Whether there are still documents to delete that still need to be fetched. + * @private + * @internal + */ + private documentsPending = true; + + /** + * Whether run() has been called. + * @private + * @internal + */ + private started = false; + + /** + * Query limit to use when fetching all descendants. + * @private + * @internal + */ + private readonly maxPendingOps: number; + + /** + * The number of pending BulkWriter operations at which RecursiveDelete + * starts the next limit query to fetch descendants. + * @private + * @internal + */ + private readonly minPendingOps: number; + + /** + * A deferred promise that resolves when the recursive delete operation + * is completed. + * @private + * @internal + */ + private readonly completionDeferred = new Deferred(); + + /** + * Whether a query stream is currently in progress. Only one stream can be + * run at a time. + * @private + * @internal + */ + private streamInProgress = false; + + /** + * The last document snapshot returned by the stream. Used to set the + * startAfter() field in the subsequent stream. + * @private + * @internal + */ + private lastDocumentSnap: QueryDocumentSnapshot | undefined; + + /** + * The number of pending BulkWriter operations. Used to determine when the + * next query can be run. + * @private + * @internal + */ + private pendingOpsCount = 0; + + private errorStack = ''; + + /** + * + * @param firestore The Firestore instance to use. + * @param writer The BulkWriter instance to use for delete operations. + * @param ref The document or collection reference to recursively delete. + * @param maxLimit The query limit to use when fetching descendants + * @param minLimit The number of pending BulkWriter operations at which + * RecursiveDelete starts the next limit query to fetch descendants. + */ + constructor( + private readonly firestore: Firestore, + private readonly writer: BulkWriter, + private readonly ref: + | firestore.CollectionReference + | firestore.DocumentReference, + private readonly maxLimit: number, + private readonly minLimit: number, + ) { + this.maxPendingOps = maxLimit; + this.minPendingOps = minLimit; + } + + /** + * Recursively deletes the reference provided in the class constructor. + * Returns a promise that resolves when all descendants have been deleted, or + * if an error occurs. + */ + run(): Promise { + assert(!this.started, 'RecursiveDelete.run() should only be called once.'); + + // Capture the error stack to preserve stack tracing across async calls. + this.errorStack = Error().stack!; + + this.writer._verifyNotClosed(); + this.setupStream(); + return this.completionDeferred.promise; + } + + /** + * Creates a query stream and attaches event handlers to it. + * @private + * @internal + */ + private setupStream(): void { + const stream = this.getAllDescendants( + this.ref instanceof CollectionReference + ? (this.ref as CollectionReference) + : (this.ref as DocumentReference), + ); + this.streamInProgress = true; + let streamedDocsCount = 0; + stream + .on('error', err => { + err.code = StatusCode.UNAVAILABLE; + err.stack = 'Failed to fetch children documents: ' + err.stack; + this.lastError = err; + this.onQueryEnd(); + }) + .on('data', (snap: QueryDocumentSnapshot) => { + streamedDocsCount++; + this.lastDocumentSnap = snap; + this.deleteRef(snap.ref); + }) + .on('end', () => { + this.streamInProgress = false; + // If there are fewer than the number of documents specified in the + // limit() field, we know that the query is complete. + if (streamedDocsCount < this.minPendingOps) { + this.onQueryEnd(); + } else if (this.pendingOpsCount === 0) { + this.setupStream(); + } + }); + } + + /** + * Retrieves all descendant documents nested under the provided reference. + * @param ref The reference to fetch all descendants for. + * @private + * @internal + * @returns {Stream} Stream of descendant documents. + */ + private getAllDescendants( + ref: CollectionReference | DocumentReference, + ): NodeJS.ReadableStream { + // The parent is the closest ancestor document to the location we're + // deleting. If we are deleting a document, the parent is the path of that + // document. If we are deleting a collection, the parent is the path of the + // document containing that collection (or the database root, if it is a + // root collection). + let parentPath = ref._resourcePath; + if (ref instanceof CollectionReference) { + parentPath = parentPath.popLast(); + } + const collectionId = + ref instanceof CollectionReference + ? ref.id + : (ref as DocumentReference).parent.id; + + let query: Query = new Query( + this.firestore, + QueryOptions.forKindlessAllDescendants( + parentPath, + collectionId, + /* requireConsistency= */ false, + ), + ); + + // Query for names only to fetch empty snapshots. + query = query.select(FieldPath.documentId()).limit(this.maxPendingOps); + + if (ref instanceof CollectionReference) { + // To find all descendants of a collection reference, we need to use a + // composite filter that captures all documents that start with the + // collection prefix. The MIN_KEY constant represents the minimum key in + // this collection, and a null byte + the MIN_KEY represents the minimum + // key is the next possible collection. + const nullChar = String.fromCharCode(0); + const startAt = collectionId + '/' + REFERENCE_NAME_MIN_ID; + const endAt = collectionId + nullChar + '/' + REFERENCE_NAME_MIN_ID; + query = query + .where(FieldPath.documentId(), '>=', startAt) + .where(FieldPath.documentId(), '<', endAt); + } + + if (this.lastDocumentSnap) { + query = query.startAfter(this.lastDocumentSnap); + } + + return query.stream(); + } + + /** + * Called when all descendants of the provided reference have been streamed + * or if a permanent error occurs during the stream. Deletes the developer + * provided reference and wraps any errors that occurred. + * @private + * @internal + */ + private onQueryEnd(): void { + this.documentsPending = false; + if (this.ref instanceof DocumentReference) { + this.writer.delete(this.ref).catch(err => this.incrementErrorCount(err)); + } + void this.writer.flush().then(async () => { + if (this.lastError === undefined) { + this.completionDeferred.resolve(); + } else { + let error = new (require('google-gax/fallback').GoogleError)( + `${this.errorCount} ` + + `${this.errorCount !== 1 ? 'deletes' : 'delete'} ` + + 'failed. The last delete failed with: ', + ); + if (this.lastError.code !== undefined) { + error.code = this.lastError.code as number; + } + error = wrapError(error, this.errorStack); + + // Wrap the BulkWriter error last to provide the full stack trace. + this.completionDeferred.reject( + this.lastError.stack + ? wrapError(error, this.lastError.stack ?? '') + : error, + ); + } + }); + } + + /** + * Deletes the provided reference and starts the next stream if conditions + * are met. + * @private + * @internal + */ + private deleteRef(docRef: DocumentReference): void { + this.pendingOpsCount++; + void this.writer + .delete(docRef) + .catch(err => { + this.incrementErrorCount(err); + }) + .then(() => { + this.pendingOpsCount--; + + // We wait until the previous stream has ended in order to sure the + // startAfter document is correct. Starting the next stream while + // there are pending operations allows Firestore to maximize + // BulkWriter throughput. + if ( + this.documentsPending && + !this.streamInProgress && + this.pendingOpsCount < this.minPendingOps + ) { + this.setupStream(); + } + }); + } + + private incrementErrorCount(err: Error): void { + this.errorCount++; + this.lastError = err; + } +} diff --git a/handwritten/firestore/dev/src/reference/aggregate-query-snapshot.ts b/handwritten/firestore/dev/src/reference/aggregate-query-snapshot.ts new file mode 100644 index 00000000000..b0d4a06fc4d --- /dev/null +++ b/handwritten/firestore/dev/src/reference/aggregate-query-snapshot.ts @@ -0,0 +1,113 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as deepEqual from 'fast-deep-equal'; + +import * as firestore from '@google-cloud/firestore'; +import {Timestamp} from '../timestamp'; +import {AggregateQuery} from './aggregate-query'; + +/** + * The results of executing an aggregation query. + */ +export class AggregateQuerySnapshot< + AggregateSpecType extends firestore.AggregateSpec, + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> implements + firestore.AggregateQuerySnapshot< + AggregateSpecType, + AppModelType, + DbModelType + > +{ + /** + * @internal + * + * @param _query The query that was executed to produce this result. + * @param _readTime The time this snapshot was read. + * @param _data The results of the aggregations performed over the underlying + * query. + */ + constructor( + private readonly _query: AggregateQuery< + AggregateSpecType, + AppModelType, + DbModelType + >, + private readonly _readTime: Timestamp, + private readonly _data: firestore.AggregateSpecData, + ) {} + + /** The query that was executed to produce this result. */ + get query(): AggregateQuery { + return this._query; + } + + /** The time this snapshot was read. */ + get readTime(): Timestamp { + return this._readTime; + } + + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the + * values will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): firestore.AggregateSpecData { + return this._data; + } + + /** + * Compares this object with the given object for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they + * have the same data and their underlying queries compare "equal" using + * `AggregateQuery.isEqual()`. + * + * @param other The object to compare to this object for equality. + * @returns `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual( + other: firestore.AggregateQuerySnapshot< + AggregateSpecType, + AppModelType, + DbModelType + >, + ): boolean { + if (this === other) { + return true; + } + if (!(other instanceof AggregateQuerySnapshot)) { + return false; + } + // Since the read time is different on every read, we explicitly ignore all + // document metadata in this comparison, just like + // `DocumentSnapshot.isEqual()` does. + if (!this.query.isEqual(other.query)) { + return false; + } + + return deepEqual(this._data, other._data); + } +} diff --git a/handwritten/firestore/dev/src/reference/aggregate-query.ts b/handwritten/firestore/dev/src/reference/aggregate-query.ts new file mode 100644 index 00000000000..f4934c44d7b --- /dev/null +++ b/handwritten/firestore/dev/src/reference/aggregate-query.ts @@ -0,0 +1,441 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; + +import * as assert from 'assert'; +import * as deepEqual from 'fast-deep-equal'; + +import * as firestore from '@google-cloud/firestore'; +import {Aggregate, AggregateSpec} from '../aggregate'; +import {average, count, countAll, field, sum} from '../pipelines'; +import {Pipeline} from '../pipelines'; +import {Timestamp} from '../timestamp'; +import {mapToArray, requestTag, wrapError} from '../util'; +import {ExplainMetrics, ExplainResults} from '../query-profile'; +import {logger} from '../logger'; +import {AggregateQuerySnapshot} from './aggregate-query-snapshot'; +import {Query} from './query'; +import {Readable, Transform} from 'stream'; +import {QueryResponse, QuerySnapshotResponse} from './types'; +import { + SPAN_NAME_AGGREGATION_QUERY_GET, + SPAN_NAME_RUN_AGGREGATION_QUERY, +} from '../telemetry/trace-util'; + +/** + * A query that calculates aggregations over an underlying query. + */ +export class AggregateQuery< + AggregateSpecType extends AggregateSpec, + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> implements + firestore.AggregateQuery +{ + private readonly clientAliasToServerAliasMap: Record = {}; + private readonly serverAliasToClientAliasMap: Record = {}; + + /** + * @internal + * @param _query The query whose aggregations will be calculated by this + * object. + * @param _aggregates The aggregations that will be performed by this query. + */ + constructor( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + private readonly _query: Query, + private readonly _aggregates: AggregateSpecType, + ) { + // Client-side aliases may be too long and exceed the 1500-byte string size limit. + // Such long strings do not need to be transferred over the wire either. + // The client maps the user's alias to a short form alias and send that to the server. + let aggregationNum = 0; + for (const clientAlias in this._aggregates) { + if (Object.prototype.hasOwnProperty.call(this._aggregates, clientAlias)) { + const serverAlias = `aggregate_${aggregationNum++}`; + this.clientAliasToServerAliasMap[clientAlias] = serverAlias; + this.serverAliasToClientAliasMap[serverAlias] = clientAlias; + } + } + } + + /** The query whose aggregations will be calculated by this object. */ + get query(): Query { + return this._query; + } + + /** + * Executes this query. + * + * @returns A promise that will be resolved with the results of the query. + */ + async get(): Promise< + AggregateQuerySnapshot + > { + return this._query._firestore._traceUtil.startActiveSpan( + SPAN_NAME_AGGREGATION_QUERY_GET, + async () => { + const {result} = await this._get(); + return result; + }, + ); + } + + /** + * Internal get() method that accepts an optional transaction options and + * returns a snapshot with transaction and explain metadata. + * + * @private + * @internal + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + */ + async _get( + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + ): Promise< + QuerySnapshotResponse< + AggregateQuerySnapshot + > + > { + const response = await this._getResponse(transactionOrReadTime); + if (!response.result) { + throw new Error('No AggregateQuery results'); + } + return response as QuerySnapshotResponse< + AggregateQuerySnapshot + >; + } + + /** + * Internal get() method that accepts an optional transaction id, and returns + * transaction metadata. + * + * @private + * @internal + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + */ + _getResponse( + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + explainOptions?: firestore.ExplainOptions, + ): Promise< + QueryResponse< + AggregateQuerySnapshot + > + > { + // Capture the error stack to preserve stack tracing across async calls. + const stack = Error().stack!; + + return new Promise((resolve, reject) => { + const output: QueryResponse< + AggregateQuerySnapshot + > = {}; + + const stream = this._stream(transactionOrReadTime, explainOptions); + stream.on('error', err => { + reject(wrapError(err, stack)); + }); + stream.on( + 'data', + ( + data: QueryResponse< + AggregateQuerySnapshot + >, + ) => { + if (data.transaction) { + output.transaction = data.transaction; + } + if (data.explainMetrics) { + output.explainMetrics = data.explainMetrics; + } + if (data.result) { + output.result = data.result; + } + }, + ); + stream.on('end', () => { + stream.destroy(); + resolve(output); + }); + }); + } + + /** + * Internal streaming method that accepts an optional transaction ID. + * + * BEWARE: If `transactionOrReadTime` is `ITransactionOptions`, then the first + * response in the stream will be a transaction response. + * + * @private + * @internal + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + * @param explainOptions Options to use for explaining the query (if any). + * @returns A stream of document results optionally preceded by a transaction response. + */ + _stream( + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + explainOptions?: firestore.ExplainOptions, + ): Readable { + const tag = requestTag(); + const firestore = this._query.firestore; + + const stream: Transform = new Transform({ + objectMode: true, + transform: (proto: api.IRunAggregationQueryResponse, enc, callback) => { + const output: QueryResponse< + AggregateQuerySnapshot + > = {}; + + // Proto comes with zero-length buffer by default + if (proto.transaction?.length) { + output.transaction = proto.transaction; + } + + if (proto.explainMetrics) { + output.explainMetrics = ExplainMetrics._fromProto( + proto.explainMetrics, + firestore._serializer!, + ); + } + + if (proto.result) { + const readTime = Timestamp.fromProto(proto.readTime!); + const data = this.decodeResult(proto.result); + output.result = new AggregateQuerySnapshot(this, readTime, data); + } + + callback(undefined, output); + }, + }); + + firestore + .initializeIfNeeded(tag) + .then(async () => { + // `toProto()` might throw an exception. We rely on the behavior of an + // async function to convert this exception into the rejected Promise we + // catch below. + const request = this.toProto(transactionOrReadTime, explainOptions); + + const backendStream = await firestore.requestStream( + 'runAggregationQuery', + /* bidirectional= */ false, + request, + tag, + ); + stream.on('close', () => { + backendStream.resume(); + backendStream.end(); + }); + backendStream.on('error', err => { + // TODO(group-by) When group-by queries are supported for aggregates + // consider implementing retries if the stream is making progress + // receiving results for groups. See the use of lastReceivedDocument + // in the retry strategy for runQuery. + // Also note that explain queries should not be retried. + + backendStream.unpipe(stream); + logger( + 'AggregateQuery._stream', + tag, + 'AggregateQuery failed with stream error:', + err, + ); + + this._query._firestore._traceUtil + .currentSpan() + .addEvent(`${SPAN_NAME_RUN_AGGREGATION_QUERY}: Error.`, { + 'error.message': err.message, + }); + + stream.destroy(err); + }); + backendStream.resume(); + backendStream.pipe(stream); + }) + .catch(e => stream.destroy(e)); + + return stream; + } + + /** + * Internal method to decode values within result. + * @private + */ + private decodeResult( + proto: api.IAggregationResult, + ): firestore.AggregateSpecData { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const data: any = {}; + const fields = proto.aggregateFields; + if (fields) { + const serializer = this._query.firestore._serializer!; + for (const prop of Object.keys(fields)) { + const alias = this.serverAliasToClientAliasMap[prop]; + assert( + alias !== null && alias !== undefined, + `'${prop}' not present in server-client alias mapping.`, + ); + if (this._aggregates[alias] === undefined) { + throw new Error( + `Unexpected alias [${prop}] in result aggregate result`, + ); + } + data[alias] = serializer.decodeValue(fields[prop]); + } + } + return data; + } + + /** + * Internal method for serializing a query to its RunAggregationQuery proto + * representation with an optional transaction id. + * + * @private + * @internal + * @returns Serialized JSON for the query. + */ + toProto( + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + explainOptions?: firestore.ExplainOptions, + ): api.IRunAggregationQueryRequest { + const queryProto = this._query.toProto(); + const runQueryRequest: api.IRunAggregationQueryRequest = { + parent: queryProto.parent, + structuredAggregationQuery: { + structuredQuery: queryProto.structuredQuery, + aggregations: mapToArray(this._aggregates, (aggregate, clientAlias) => { + const serverAlias = this.clientAliasToServerAliasMap[clientAlias]; + assert( + serverAlias !== null && serverAlias !== undefined, + `'${clientAlias}' not present in client-server alias mapping.`, + ); + return new Aggregate( + serverAlias, + aggregate.aggregateType, + aggregate._field, + ).toProto(); + }), + }, + }; + + if (transactionOrReadTime instanceof Uint8Array) { + runQueryRequest.transaction = transactionOrReadTime; + } else if (transactionOrReadTime instanceof Timestamp) { + runQueryRequest.readTime = transactionOrReadTime.toProto().timestampValue; + } else if (transactionOrReadTime) { + runQueryRequest.newTransaction = transactionOrReadTime; + } + + if (explainOptions) { + runQueryRequest.explainOptions = explainOptions; + } + + return runQueryRequest; + } + + /** + * @private + * @internal + */ + _pipeline(): Pipeline { + const aggregates = mapToArray( + this._aggregates, + (aggregate, clientAlias) => { + if (aggregate.aggregateType === 'count') { + if (aggregate._field === undefined) { + return countAll().as(clientAlias); + } + return count(field(aggregate._field)).as(clientAlias); + } else if (aggregate.aggregateType === 'avg') { + return average(field(aggregate._field!)).as(clientAlias); + } else if (aggregate.aggregateType === 'sum') { + return sum(field(aggregate._field!)).as(clientAlias); + } else { + throw new Error(`Unknown aggregate type ${aggregate.aggregateType}`); + } + }, + ); + + if (aggregates.length === 0) { + throw new Error( + 'Cannot convert an AggregateQuery with 0 aggregates to a Pipeline', + ); + } + + return this._query + ._pipeline() + .aggregate(aggregates[0], ...aggregates.slice(1)); + } + + /** + * Compares this object with the given object for equality. + * + * This object is considered "equal" to the other object if and only if + * `other` performs the same aggregations as this `AggregateQuery` and + * the underlying Query of `other` compares equal to that of this object + * using `Query.isEqual()`. + * + * @param other The object to compare to this object for equality. + * @returns `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual( + other: firestore.AggregateQuery< + AggregateSpecType, + AppModelType, + DbModelType + >, + ): boolean { + if (this === other) { + return true; + } + if (!(other instanceof AggregateQuery)) { + return false; + } + if (!this.query.isEqual(other.query)) { + return false; + } + return deepEqual(this._aggregates, other._aggregates); + } + + /** + * Plans and optionally executes this query. Returns a Promise that will be + * resolved with the planner information, statistics from the query + * execution (if any), and the query results (if any). + * + * @returns A Promise that will be resolved with the planner information, + * statistics from the query execution (if any), and the query results (if any). + */ + async explain( + options?: firestore.ExplainOptions, + ): Promise< + ExplainResults< + AggregateQuerySnapshot + > + > { + const {result, explainMetrics} = await this._getResponse( + undefined, + options || {}, + ); + if (!explainMetrics) { + throw new Error('No explain results'); + } + return new ExplainResults(explainMetrics, result || null); + } +} diff --git a/handwritten/firestore/dev/src/reference/collection-reference.ts b/handwritten/firestore/dev/src/reference/collection-reference.ts new file mode 100644 index 00000000000..0cdacee326e --- /dev/null +++ b/handwritten/firestore/dev/src/reference/collection-reference.ts @@ -0,0 +1,384 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; + +import * as firestore from '@google-cloud/firestore'; +import { + QualifiedResourcePath, + ResourcePath, + validateResourcePath, +} from '../path'; +import {autoId, requestTag} from '../util'; +import {validateDocumentData} from '../write-batch'; +import {defaultConverter} from '../types'; +import {Query} from './query'; +import Firestore from '../index'; +import {DocumentReference} from './document-reference'; +import {QueryOptions} from './query-options'; +import { + SPAN_NAME_COL_REF_ADD, + SPAN_NAME_COL_REF_LIST_DOCUMENTS, +} from '../telemetry/trace-util'; + +/** + * A CollectionReference object can be used for adding documents, getting + * document references, and querying for documents (using the methods + * inherited from [Query]{@link Query}). + * + * @class CollectionReference + * @extends Query + */ +export class CollectionReference< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, + > + extends Query + implements firestore.CollectionReference +{ + /** + * @private + * + * @param firestore The Firestore Database client. + * @param path The Path of this collection. + */ + constructor( + firestore: Firestore, + path: ResourcePath, + converter?: firestore.FirestoreDataConverter, + ) { + super(firestore, QueryOptions.forCollectionQuery(path, converter)); + } + + /** + * Returns a resource path for this collection. + * @private + * @internal + */ + get _resourcePath(): ResourcePath { + return this._queryOptions.parentPath.append( + this._queryOptions.collectionId, + ); + } + + /** + * The last path element of the referenced collection. + * + * @type {string} + * @name CollectionReference#id + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col/doc/subcollection'); + * console.log(`ID of the subcollection: ${collectionRef.id}`); + * ``` + */ + get id(): string { + return this._queryOptions.collectionId; + } + + /** + * A reference to the containing Document if this is a subcollection, else + * null. + * + * @type {DocumentReference|null} + * @name CollectionReference#parent + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col/doc/subcollection'); + * let documentRef = collectionRef.parent; + * console.log(`Parent name: ${documentRef.path}`); + * ``` + */ + get parent(): DocumentReference | null { + if (this._queryOptions.parentPath.isDocument) { + return new DocumentReference( + this.firestore, + this._queryOptions.parentPath, + ); + } + + return null; + } + + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + * + * @type {string} + * @name CollectionReference#path + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col/doc/subcollection'); + * console.log(`Path of the subcollection: ${collectionRef.path}`); + * ``` + */ + get path(): string { + return this._resourcePath.relativeName; + } + + /** + * Retrieves the list of documents in this collection. + * + * The document references returned may include references to "missing + * documents", i.e. document locations that have no document present but + * which contain subcollections with documents. Attempting to read such a + * document reference (e.g. via `.get()` or `.onSnapshot()`) will return a + * `DocumentSnapshot` whose `.exists` property is false. + * + * @returns {Promise} The list of documents in this + * collection. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * return collectionRef.listDocuments().then(documentRefs => { + * return firestore.getAll(...documentRefs); + * }).then(documentSnapshots => { + * for (let documentSnapshot of documentSnapshots) { + * if (documentSnapshot.exists) { + * console.log(`Found document with data: ${documentSnapshot.id}`); + * } else { + * console.log(`Found missing document: ${documentSnapshot.id}`); + * } + * } + * }); + * ``` + */ + listDocuments(): Promise< + Array> + > { + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_COL_REF_LIST_DOCUMENTS, + () => { + const tag = requestTag(); + return this.firestore.initializeIfNeeded(tag).then(() => { + const parentPath = + this._queryOptions.parentPath.toQualifiedResourcePath( + this.firestore.projectId, + this.firestore.databaseId, + ); + + const request: api.IListDocumentsRequest = { + parent: parentPath.formattedName, + collectionId: this.id, + showMissing: true, + mask: {fieldPaths: []}, + }; + + return this.firestore + .request< + api.IListDocumentsRequest, + api.IDocument[] + >('listDocuments', request, tag) + .then(documents => { + // Note that the backend already orders these documents by name, + // so we do not need to manually sort them. + return documents.map(doc => { + const path = QualifiedResourcePath.fromSlashSeparatedString( + doc.name!, + ); + return this.doc(path.id!); + }); + }); + }); + }, + ); + } + + doc(): DocumentReference; + doc(documentPath: string): DocumentReference; + /** + * Gets a [DocumentReference]{@link DocumentReference} instance that + * refers to the document at the specified path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * DocumentReference. + * + * @param {string=} documentPath A slash-separated path to a document. + * @returns {DocumentReference} The `DocumentReference` + * instance. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * let documentRefWithName = collectionRef.doc('doc'); + * let documentRefWithAutoId = collectionRef.doc(); + * console.log(`Reference with name: ${documentRefWithName.path}`); + * console.log(`Reference with auto-id: ${documentRefWithAutoId.path}`); + * ``` + */ + doc(documentPath?: string): DocumentReference { + if (arguments.length === 0) { + documentPath = autoId(); + } else { + validateResourcePath('documentPath', documentPath!); + } + + const path = this._resourcePath.append(documentPath!); + if (!path.isDocument) { + throw new Error( + `Value for argument "documentPath" must point to a document, but was "${documentPath}". Your path does not contain an even number of components.`, + ); + } + + return new DocumentReference( + this.firestore, + path, + this._queryOptions.converter, + ); + } + + /** + * Add a new document to this collection with the specified data, assigning + * it a document ID automatically. + * + * @param {DocumentData} data An Object containing the data for the new + * document. + * @throws {Error} If the provided input is not a valid Firestore document. + * @returns {Promise.} A Promise resolved with a + * [DocumentReference]{@link DocumentReference} pointing to the + * newly created document. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * collectionRef.add({foo: 'bar'}).then(documentReference => { + * console.log(`Added document with name: ${documentReference.id}`); + * }); + * ``` + */ + add( + data: firestore.WithFieldValue, + ): Promise> { + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_COL_REF_ADD, + () => { + const firestoreData = this._queryOptions.converter.toFirestore(data); + validateDocumentData( + 'data', + firestoreData, + /*allowDeletes=*/ false, + this._allowUndefined, + ); + + const documentRef = this.doc(); + return documentRef.create(data).then(() => documentRef); + }, + ); + } + + /** + * Returns true if this `CollectionReference` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @returns {boolean} true if this `CollectionReference` is equal to the + * provided value. + */ + isEqual( + other: firestore.CollectionReference, + ): boolean { + return ( + this === other || + (other instanceof CollectionReference && super.isEqual(other)) + ); + } + + withConverter< + NewAppModelType, + NewDbModelType extends firestore.DocumentData = firestore.DocumentData, + >( + converter: firestore.FirestoreDataConverter< + NewAppModelType, + NewDbModelType + >, + ): CollectionReference; + withConverter( + converter: null, + ): CollectionReference; + /** + * Applies a custom data converter to this CollectionReference, allowing you + * to use your own custom model objects with Firestore. When you call add() on + * the returned CollectionReference instance, the provided converter will + * convert between Firestore data of type `NewDbModelType` and your custom + * type `NewAppModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * Passing in `null` as the converter parameter removes the current + * converter. + * + * @example + * ``` + * class Post { + * constructor(readonly title: string, readonly author: string) {} + * + * toString(): string { + * return this.title + ', by ' + this.author; + * } + * } + * + * const postConverter = { + * toFirestore(post: Post): FirebaseFirestore.DocumentData { + * return {title: post.title, author: post.author}; + * }, + * fromFirestore( + * snapshot: FirebaseFirestore.QueryDocumentSnapshot + * ): Post { + * const data = snapshot.data(); + * return new Post(data.title, data.author); + * } + * }; + * + * const postSnap = await Firestore() + * .collection('posts') + * .withConverter(postConverter) + * .doc().get(); + * const post = postSnap.data(); + * if (post !== undefined) { + * post.title; // string + * post.toString(); // Should be defined + * post.someNonExistentProperty; // TS error + * } + * + * ``` + * @param {FirestoreDataConverter | null} converter Converts objects to and + * from Firestore. Passing in `null` removes the current converter. + * @returns A CollectionReference that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends firestore.DocumentData = firestore.DocumentData, + >( + converter: firestore.FirestoreDataConverter< + NewAppModelType, + NewDbModelType + > | null, + ): CollectionReference { + return new CollectionReference( + this.firestore, + this._resourcePath, + converter ?? defaultConverter(), + ); + } +} diff --git a/handwritten/firestore/dev/src/reference/composite-filter-internal.ts b/handwritten/firestore/dev/src/reference/composite-filter-internal.ts new file mode 100644 index 00000000000..a6a04297328 --- /dev/null +++ b/handwritten/firestore/dev/src/reference/composite-filter-internal.ts @@ -0,0 +1,94 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; + +import {FilterInternal} from './filter-internal'; +import {FieldFilterInternal} from './field-filter-internal'; + +export class CompositeFilterInternal extends FilterInternal { + constructor( + private filters: FilterInternal[], + private operator: api.StructuredQuery.CompositeFilter.Operator, + ) { + super(); + } + + // Memoized list of all field filters that can be found by traversing the tree of filters + // contained in this composite filter. + private memoizedFlattenedFilters: FieldFilterInternal[] | null = null; + + public getFilters(): FilterInternal[] { + return this.filters; + } + + public isConjunction(): boolean { + return this.operator === 'AND'; + } + + /** + * @private + * @internal + */ + public _getOperator(): api.StructuredQuery.CompositeFilter.Operator { + return this.operator; + } + + public getFlattenedFilters(): FieldFilterInternal[] { + if (this.memoizedFlattenedFilters !== null) { + return this.memoizedFlattenedFilters; + } + + this.memoizedFlattenedFilters = this.filters.reduce( + (allFilters: FieldFilterInternal[], subfilter: FilterInternal) => + allFilters.concat(subfilter.getFlattenedFilters()), + [], + ); + + return this.memoizedFlattenedFilters; + } + + public toProto(): api.StructuredQuery.IFilter { + if (this.filters.length === 1) { + return this.filters[0].toProto(); + } + + const proto: api.StructuredQuery.IFilter = { + compositeFilter: { + op: this.operator, + filters: this.filters.map(filter => filter.toProto()), + }, + }; + + return proto; + } + + isEqual(other: FilterInternal): boolean { + if (other instanceof CompositeFilterInternal) { + const otherFilters = other.getFilters(); + return ( + this.operator === other.operator && + this.getFilters().length === other.getFilters().length && + this.getFilters().every((filter, index) => + filter.isEqual(otherFilters[index]), + ) + ); + } else { + return false; + } + } +} diff --git a/handwritten/firestore/dev/src/reference/constants.ts b/handwritten/firestore/dev/src/reference/constants.ts new file mode 100644 index 00000000000..ad0f28f0579 --- /dev/null +++ b/handwritten/firestore/dev/src/reference/constants.ts @@ -0,0 +1,56 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; + +/** + * The direction of a `Query.orderBy()` clause is specified as 'desc' or 'asc' + * (descending or ascending). + * + * @private + * @internal + */ +export const directionOperators: {[k: string]: api.StructuredQuery.Direction} = + { + asc: 'ASCENDING', + desc: 'DESCENDING', + }; + +/** + * Filter conditions in a `Query.where()` clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', 'not-in', + * and 'array-contains-any'. + * + * @private + * @internal + */ +export const comparisonOperators: { + [k: string]: api.StructuredQuery.FieldFilter.Operator; +} = { + '<': 'LESS_THAN', + '<=': 'LESS_THAN_OR_EQUAL', + '==': 'EQUAL', + '!=': 'NOT_EQUAL', + '>': 'GREATER_THAN', + '>=': 'GREATER_THAN_OR_EQUAL', + 'array-contains': 'ARRAY_CONTAINS', + in: 'IN', + 'not-in': 'NOT_IN', + 'array-contains-any': 'ARRAY_CONTAINS_ANY', +}; + +export const NOOP_MESSAGE = Symbol('a noop message'); diff --git a/handwritten/firestore/dev/src/reference/document-reference.ts b/handwritten/firestore/dev/src/reference/document-reference.ts new file mode 100644 index 00000000000..da3f518e9c3 --- /dev/null +++ b/handwritten/firestore/dev/src/reference/document-reference.ts @@ -0,0 +1,643 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; + +import * as firestore from '@google-cloud/firestore'; +import Firestore, {DocumentSnapshot, WriteBatch, WriteResult} from '../index'; +import {ResourcePath, validateResourcePath} from '../path'; +import {defaultConverter} from '../types'; +import {Serializable} from '../serializer'; +import {CollectionReference} from './collection-reference'; +import {requestTag} from '../util'; +import {validateFunction, validateMinNumberOfArguments} from '../validate'; +import {DocumentWatch} from '../watch'; +import {DocumentSnapshotBuilder} from '../document'; +import { + SPAN_NAME_DOC_REF_CREATE, + SPAN_NAME_DOC_REF_DELETE, + SPAN_NAME_DOC_REF_GET, + SPAN_NAME_DOC_REF_LIST_COLLECTIONS, + SPAN_NAME_DOC_REF_SET, + SPAN_NAME_DOC_REF_UPDATE, +} from '../telemetry/trace-util'; + +/** + * A DocumentReference refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. A DocumentReference can + * also be used to create a + * [CollectionReference]{@link CollectionReference} to a + * subcollection. + * + * @class DocumentReference + */ +export class DocumentReference< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, + > + implements + Serializable, + firestore.DocumentReference +{ + /** + * @private + * @internal + * @param _firestore The Firestore Database client. + * @param _path The Path of this reference. + * @param _converter The converter to use when serializing data. + */ + constructor( + private readonly _firestore: Firestore, + /** + * @private + * @internal + **/ + readonly _path: ResourcePath, + /** + * @internal + * @private + **/ + readonly _converter = defaultConverter(), + ) {} + + /** + * The string representation of the DocumentReference's location. + * @private + * @internal + * @type {string} + * @name DocumentReference#formattedName + */ + get formattedName(): string { + const projectId = this.firestore.projectId; + const databaseId = this.firestore.databaseId; + return this._path.toQualifiedResourcePath(projectId, databaseId) + .formattedName; + } + + /** + * The [Firestore]{@link Firestore} instance for the Firestore + * database (useful for performing transactions, etc.). + * + * @type {Firestore} + * @name DocumentReference#firestore + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.add({foo: 'bar'}).then(documentReference => { + * let firestore = documentReference.firestore; + * console.log(`Root location for document is ${firestore.formattedName}`); + * }); + * ``` + */ + get firestore(): Firestore { + return this._firestore; + } + + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + * + * @type {string} + * @name DocumentReference#path + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.add({foo: 'bar'}).then(documentReference => { + * console.log(`Added document at '${documentReference.path}'`); + * }); + * ``` + */ + get path(): string { + return this._path.relativeName; + } + + /** + * The last path element of the referenced document. + * + * @type {string} + * @name DocumentReference#id + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.add({foo: 'bar'}).then(documentReference => { + * console.log(`Added document with name '${documentReference.id}'`); + * }); + * ``` + */ + get id(): string { + return this._path.id!; + } + + /** + * Returns a resource path for this document. + * @private + * @internal + */ + get _resourcePath(): ResourcePath { + return this._path; + } + + /** + * A reference to the collection to which this DocumentReference belongs. + * + * @name DocumentReference#parent + * @type {CollectionReference} + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * let collectionRef = documentRef.parent; + * + * collectionRef.where('foo', '==', 'bar').get().then(results => { + * console.log(`Found ${results.size} matches in parent collection`); + * }): + * ``` + */ + get parent(): CollectionReference { + return new CollectionReference( + this._firestore, + this._path.parent()!, + this._converter, + ); + } + + /** + * Reads the document referred to by this DocumentReference. + * + * @returns {Promise.} A Promise resolved with a + * DocumentSnapshot for the retrieved document on success. For missing + * documents, DocumentSnapshot.exists will be false. If the get() fails for + * other reasons, the Promise will be rejected. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * if (documentSnapshot.exists) { + * console.log('Document retrieved successfully.'); + * } + * }); + * ``` + */ + get(): Promise> { + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_DOC_REF_GET, + () => { + return this._firestore.getAll(this).then(([result]) => result); + }, + ); + } + + /** + * Gets a [CollectionReference]{@link CollectionReference} instance + * that refers to the collection at the specified path. + * + * @param {string} collectionPath A slash-separated path to a collection. + * @returns {CollectionReference} A reference to the new + * subcollection. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * let subcollection = documentRef.collection('subcollection'); + * console.log(`Path to subcollection: ${subcollection.path}`); + * ``` + */ + collection(collectionPath: string): CollectionReference { + validateResourcePath('collectionPath', collectionPath); + + const path = this._path.append(collectionPath); + if (!path.isCollection) { + throw new Error( + `Value for argument "collectionPath" must point to a collection, but was "${collectionPath}". Your path does not contain an odd number of components.`, + ); + } + + return new CollectionReference(this._firestore, path); + } + + /** + * Fetches the subcollections that are direct children of this document. + * + * @returns {Promise.>} A Promise that resolves + * with an array of CollectionReferences. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.listCollections().then(collections => { + * for (let collection of collections) { + * console.log(`Found subcollection with id: ${collection.id}`); + * } + * }); + * ``` + */ + listCollections(): Promise> { + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_DOC_REF_LIST_COLLECTIONS, + () => { + const tag = requestTag(); + return this.firestore.initializeIfNeeded(tag).then(() => { + const request: api.IListCollectionIdsRequest = { + parent: this.formattedName, + }; + return this._firestore + .request< + api.IListCollectionIdsRequest, + string[] + >('listCollectionIds', request, tag) + .then(collectionIds => { + const collections: Array = []; + + // We can just sort this list using the default comparator since it + // will only contain collection ids. + collectionIds.sort(); + + for (const collectionId of collectionIds) { + collections.push(this.collection(collectionId)); + } + + return collections; + }); + }); + }, + ); + } + + /** + * Create a document with the provided object values. This will fail the write + * if a document exists at its location. + * + * @param {DocumentData} data An object that contains the fields and data to + * serialize as the document. + * @throws {Error} If the provided input is not a valid Firestore document or if the document already exists. + * @returns {Promise.} A Promise that resolves with the + * write time of this create. + * + * @example + * ``` + * let documentRef = firestore.collection('col').doc(); + * + * documentRef.create({foo: 'bar'}).then((res) => { + * console.log(`Document created at ${res.updateTime}`); + * }).catch((err) => { + * console.log(`Failed to create document: ${err}`); + * }); + * ``` + */ + create(data: firestore.WithFieldValue): Promise { + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_DOC_REF_CREATE, + () => { + const writeBatch = new WriteBatch(this._firestore); + return writeBatch + .create(this, data) + .commit() + .then(([writeResult]) => writeResult); + }, + ); + } + + /** + * Deletes the document referred to by this `DocumentReference`. + * + * A delete for a non-existing document is treated as a success (unless + * lastUptimeTime is provided). + * + * @param {Precondition=} precondition A precondition to enforce for this + * delete. + * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the + * document was last updated at lastUpdateTime. Fails the delete if the + * document was last updated at a different time. + * @param {boolean=} precondition.exists If set, enforces that the target + * document must or must not exist. + * @returns {Promise.} A Promise that resolves with the + * delete time. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.delete().then(() => { + * console.log('Document successfully deleted.'); + * }); + * ``` + */ + delete(precondition?: firestore.Precondition): Promise { + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_DOC_REF_DELETE, + () => { + const writeBatch = new WriteBatch(this._firestore); + return writeBatch + .delete(this, precondition) + .commit() + .then(([writeResult]) => writeResult); + }, + ); + } + + set( + data: firestore.PartialWithFieldValue, + options: firestore.SetOptions, + ): Promise; + set(data: firestore.WithFieldValue): Promise; + /** + * Writes to the document referred to by this DocumentReference. If the + * document does not yet exist, it will be created. If you pass + * [SetOptions]{@link SetOptions}, the provided data can be merged into an + * existing document. + * + * @param {T|Partial} data A map of the fields and values for + * the document. + * @param {SetOptions=} options An object to configure the set behavior. + * @param {boolean=} options.merge If true, set() merges the values specified + * in its data argument. Fields omitted from this set() call remain untouched. + * If your input sets any field to an empty map, all nested fields are + * overwritten. + * @param {Array.=} options.mergeFields If provided, + * set() only replaces the specified field paths. Any field path that is not + * specified is ignored and remains untouched. If your input sets any field to + * an empty map, all nested fields are overwritten. + * @throws {Error} If the provided input is not a valid Firestore document. + * @returns {Promise.} A Promise that resolves with the + * write time of this set. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({foo: 'bar'}).then(res => { + * console.log(`Document written at ${res.updateTime}`); + * }); + * ``` + */ + set( + data: firestore.PartialWithFieldValue, + options?: firestore.SetOptions, + ): Promise { + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_DOC_REF_SET, + () => { + let writeBatch = new WriteBatch(this._firestore); + if (options) { + writeBatch = writeBatch.set(this, data, options); + } else { + writeBatch = writeBatch.set( + this, + data as firestore.WithFieldValue, + ); + } + return writeBatch.commit().then(([writeResult]) => writeResult); + }, + ); + } + + /** + * Updates fields in the document referred to by this DocumentReference. + * If the document doesn't yet exist, the update fails and the returned + * Promise will be rejected. + * + * The update() method accepts either an object with field paths encoded as + * keys and field values encoded as values, or a variable number of arguments + * that alternate between field paths and field values. + * + * A Precondition restricting this update can be specified as the last + * argument. + * + * @param {UpdateData|string|FieldPath} dataOrField An object containing the + * fields and values with which to update the document or the path of the + * first field to update. + * @param { + * ...(*|string|FieldPath|Precondition)} preconditionOrValues An alternating + * list of field paths and values to update or a Precondition to restrict + * this update. + * @throws {Error} If the provided input is not valid Firestore data. + * @returns {Promise.} A Promise that resolves once the + * data has been successfully written to the backend. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.update({foo: 'bar'}).then(res => { + * console.log(`Document updated at ${res.updateTime}`); + * }); + * ``` + */ + update( + dataOrField: + | firestore.UpdateData + | string + | firestore.FieldPath, + ...preconditionOrValues: Array< + unknown | string | firestore.FieldPath | firestore.Precondition + > + ): Promise { + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_DOC_REF_UPDATE, + () => { + // eslint-disable-next-line prefer-rest-params + validateMinNumberOfArguments('DocumentReference.update', arguments, 1); + + const writeBatch = new WriteBatch(this._firestore); + return writeBatch + .update(this, dataOrField, ...preconditionOrValues) + .commit() + .then(([writeResult]) => writeResult); + }, + ); + } + + /** + * Attaches a listener for DocumentSnapshot events. + * + * @param {documentSnapshotCallback} onNext A callback to be called every + * time a new `DocumentSnapshot` is available. + * @param {errorCallback=} onError A callback to be called if the listen fails + * or is cancelled. No further callbacks will occur. If unset, errors will be + * logged to the console. + * + * @returns {function()} An unsubscribe function that can be called to cancel + * the snapshot listener. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * let unsubscribe = documentRef.onSnapshot(documentSnapshot => { + * if (documentSnapshot.exists) { + * console.log(documentSnapshot.data()); + * } + * }, err => { + * console.log(`Encountered error: ${err}`); + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + onSnapshot( + onNext: ( + snapshot: firestore.DocumentSnapshot, + ) => void, + onError?: (error: Error) => void, + ): () => void { + validateFunction('onNext', onNext); + validateFunction('onError', onError, {optional: true}); + + const watch: DocumentWatch = + new (require('../watch').DocumentWatch)(this.firestore, this); + return watch.onSnapshot((readTime, size, docs) => { + for (const document of docs()) { + if (document.ref.path === this.path) { + onNext(document); + return; + } + } + + // The document is missing. + const ref = new DocumentReference( + this._firestore, + this._path, + this._converter, + ); + const document = new DocumentSnapshotBuilder( + ref, + ); + document.readTime = readTime; + onNext(document.build()); + }, onError || console.error); + } + + /** + * Returns true if this `DocumentReference` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @returns {boolean} true if this `DocumentReference` is equal to the provided + * value. + */ + isEqual( + other: firestore.DocumentReference, + ): boolean { + return ( + this === other || + (other instanceof DocumentReference && + this._firestore === other._firestore && + this._path.isEqual(other._path) && + this._converter === other._converter) + ); + } + + /** + * Converts this DocumentReference to the Firestore Proto representation. + * + * @private + * @internal + */ + toProto(): api.IValue { + return {referenceValue: this.formattedName}; + } + + withConverter< + NewAppModelType, + NewDbModelType extends firestore.DocumentData = firestore.DocumentData, + >( + converter: firestore.FirestoreDataConverter< + NewAppModelType, + NewDbModelType + > | null, + ): DocumentReference; + /** + * Applies a custom data converter to this DocumentReference, allowing you to + * use your own custom model objects with Firestore. When you call set(), + * get(), etc. on the returned DocumentReference instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * Passing in `null` as the converter parameter removes the current + * converter. + * + * @example + * ``` + * class Post { + * constructor(readonly title: string, readonly author: string) {} + * + * toString(): string { + * return this.title + ', by ' + this.author; + * } + * } + * + * const postConverter = { + * toFirestore(post: Post): FirebaseFirestore.DocumentData { + * return {title: post.title, author: post.author}; + * }, + * fromFirestore( + * snapshot: FirebaseFirestore.QueryDocumentSnapshot + * ): Post { + * const data = snapshot.data(); + * return new Post(data.title, data.author); + * } + * }; + * + * const postSnap = await Firestore() + * .collection('posts') + * .withConverter(postConverter) + * .doc().get(); + * const post = postSnap.data(); + * if (post !== undefined) { + * post.title; // string + * post.toString(); // Should be defined + * post.someNonExistentProperty; // TS error + * } + * + * ``` + * @param {FirestoreDataConverter | null} converter Converts objects to and + * from Firestore. Passing in `null` removes the current converter. + * @returns A DocumentReference that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends firestore.DocumentData = firestore.DocumentData, + >( + converter: firestore.FirestoreDataConverter< + NewAppModelType, + NewDbModelType + > | null, + ): DocumentReference { + return new DocumentReference( + this.firestore, + this._path, + converter ?? defaultConverter(), + ); + } +} diff --git a/handwritten/firestore/dev/src/reference/field-filter-internal.ts b/handwritten/firestore/dev/src/reference/field-filter-internal.ts new file mode 100644 index 00000000000..3b08c491981 --- /dev/null +++ b/handwritten/firestore/dev/src/reference/field-filter-internal.ts @@ -0,0 +1,157 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as deepEqual from 'fast-deep-equal'; + +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import {FilterInternal} from './filter-internal'; +import {Serializer} from '../serializer'; +import {FieldPath} from '../path'; + +/** + * A field constraint for a Query where clause. + * + * @private + * @internal + * @class + */ +export class FieldFilterInternal extends FilterInternal { + public getFlattenedFilters(): FieldFilterInternal[] { + return [this]; + } + + public getFilters(): FilterInternal[] { + return [this]; + } + + /** + * @param serializer The Firestore serializer + * @param field The path of the property value to compare. + * @param op A comparison operation. + * @param value The value to which to compare the field for inclusion in a + * query. + */ + constructor( + private readonly serializer: Serializer, + readonly field: FieldPath, + readonly op: api.StructuredQuery.FieldFilter.Operator, + readonly value: unknown, + ) { + super(); + } + + /** + * Returns whether this FieldFilter uses an equals comparison. + * + * @private + * @internal + */ + isInequalityFilter(): boolean { + switch (this.op) { + case 'GREATER_THAN': + case 'GREATER_THAN_OR_EQUAL': + case 'LESS_THAN': + case 'LESS_THAN_OR_EQUAL': + case 'NOT_EQUAL': + case 'NOT_IN': + return true; + default: + return false; + } + } + + /** + * @private + * @internal + */ + isNanChecking(): boolean { + return typeof this.value === 'number' && isNaN(this.value); + } + + /** + * @private + * @internal + */ + nanOp(): 'IS_NAN' | 'IS_NOT_NAN' { + return this.op === 'EQUAL' ? 'IS_NAN' : 'IS_NOT_NAN'; + } + + /** + * @private + * @internal + */ + isNullChecking(): boolean { + return this.value === null; + } + + /** + * @private + * @internal + */ + nullOp(): 'IS_NULL' | 'IS_NOT_NULL' { + return this.op === 'EQUAL' ? 'IS_NULL' : 'IS_NOT_NULL'; + } + + /** + * Generates the proto representation for this field filter. + * + * @private + * @internal + */ + toProto(): api.StructuredQuery.IFilter { + if (this.isNanChecking()) { + return { + unaryFilter: { + field: { + fieldPath: this.field.formattedName, + }, + op: this.nanOp(), + }, + }; + } + + if (this.isNullChecking()) { + return { + unaryFilter: { + field: { + fieldPath: this.field.formattedName, + }, + op: this.nullOp(), + }, + }; + } + + return { + fieldFilter: { + field: { + fieldPath: this.field.formattedName, + }, + op: this.op, + value: this.serializer.encodeValue(this.value), + }, + }; + } + + isEqual(other: FilterInternal): boolean { + return ( + other instanceof FieldFilterInternal && + this.field.isEqual(other.field) && + this.op === other.op && + deepEqual(this.value, other.value) + ); + } +} diff --git a/handwritten/firestore/dev/src/reference/field-order.ts b/handwritten/firestore/dev/src/reference/field-order.ts new file mode 100644 index 00000000000..90eb23d8a18 --- /dev/null +++ b/handwritten/firestore/dev/src/reference/field-order.ts @@ -0,0 +1,54 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; + +import {FieldPath} from '../path'; + +/** + * A Query order-by field. + * + * @private + * @internal + * @class + */ +export class FieldOrder { + /** + * @param field The name of a document field (member) on which to order query + * results. + * @param direction One of 'ASCENDING' (default) or 'DESCENDING' to + * set the ordering direction to ascending or descending, respectively. + */ + constructor( + readonly field: FieldPath, + readonly direction: api.StructuredQuery.Direction = 'ASCENDING', + ) {} + + /** + * Generates the proto representation for this field order. + * @private + * @internal + */ + toProto(): api.StructuredQuery.IOrder { + return { + field: { + fieldPath: this.field.formattedName, + }, + direction: this.direction, + }; + } +} diff --git a/handwritten/firestore/dev/src/reference/filter-internal.ts b/handwritten/firestore/dev/src/reference/filter-internal.ts new file mode 100644 index 00000000000..50d28df0501 --- /dev/null +++ b/handwritten/firestore/dev/src/reference/filter-internal.ts @@ -0,0 +1,31 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {Filter} from '../filter'; +import {FieldFilterInternal} from './field-filter-internal'; + +export abstract class FilterInternal { + /** Returns a list of all field filters that are contained within this filter */ + abstract getFlattenedFilters(): FieldFilterInternal[]; + + /** Returns a list of all filters that are contained within this filter */ + abstract getFilters(): FilterInternal[]; + + /** Returns the proto representation of this filter */ + abstract toProto(): Filter; + + abstract isEqual(other: FilterInternal): boolean; +} diff --git a/handwritten/firestore/dev/src/reference/helpers.ts b/handwritten/firestore/dev/src/reference/helpers.ts new file mode 100644 index 00000000000..1ed3c6d3390 --- /dev/null +++ b/handwritten/firestore/dev/src/reference/helpers.ts @@ -0,0 +1,138 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; +import {invalidArgumentMessage, validateEnumValue} from '../validate'; +import {validateUserInput} from '../serializer'; +import {DocumentReference} from './document-reference'; +import {comparisonOperators, directionOperators} from './constants'; + +/** + * Validates the input string as a field order direction. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param op Order direction to validate. + * @throws when the direction is invalid + * @returns a validated input value, which may be different from the provided + * value. + */ +export function validateQueryOrder( + arg: string, + op: unknown, +): firestore.OrderByDirection | undefined { + // For backwards compatibility, we support both lower and uppercase values. + op = typeof op === 'string' ? op.toLowerCase() : op; + validateEnumValue(arg, op, Object.keys(directionOperators), {optional: true}); + return op as firestore.OrderByDirection | undefined; +} + +/** + * Validates the input string as a field comparison operator. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param op Field comparison operator to validate. + * @param fieldValue Value that is used in the filter. + * @throws when the comparison operation is invalid + * @returns a validated input value, which may be different from the provided + * value. + */ +export function validateQueryOperator( + arg: string | number, + op: unknown, + fieldValue: unknown, +): firestore.WhereFilterOp { + // For backwards compatibility, we support both `=` and `==` for "equals". + if (op === '=') { + op = '=='; + } + + validateEnumValue(arg, op, Object.keys(comparisonOperators)); + + if ( + typeof fieldValue === 'number' && + isNaN(fieldValue) && + op !== '==' && + op !== '!=' + ) { + throw new Error( + "Invalid query. You can only perform '==' and '!=' comparisons on NaN.", + ); + } + + if (fieldValue === null && op !== '==' && op !== '!=') { + throw new Error( + "Invalid query. You can only perform '==' and '!=' comparisons on Null.", + ); + } + + return op as firestore.WhereFilterOp; +} + +/** + * Validates that 'value' is a DocumentReference. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The argument to validate. + * @returns the DocumentReference if valid + */ +export function validateDocumentReference< + AppModelType, + DbModelType extends firestore.DocumentData, +>( + arg: string | number, + value: firestore.DocumentReference, +): DocumentReference { + if (!(value instanceof DocumentReference)) { + throw new Error(invalidArgumentMessage(arg, 'DocumentReference')); + } + return value; +} + +/** + * Validates that 'value' can be used as a query value. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The argument to validate. + * @param allowUndefined Whether to allow nested properties that are `undefined`. + */ +export function validateQueryValue( + arg: string | number, + value: unknown, + allowUndefined: boolean, +): void { + validateUserInput(arg, value, 'query constraint', { + allowDeletes: 'none', + allowTransforms: false, + allowUndefined, + }); +} + +/** + * Returns the first non-undefined value or `undefined` if no such value exists. + * @private + * @internal + */ +export function coalesce(...values: Array): T | undefined { + return values.find(value => value !== undefined); +} diff --git a/handwritten/firestore/dev/src/reference/query-options.ts b/handwritten/firestore/dev/src/reference/query-options.ts new file mode 100644 index 00000000000..66e949e7031 --- /dev/null +++ b/handwritten/firestore/dev/src/reference/query-options.ts @@ -0,0 +1,232 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import * as deepEqual from 'fast-deep-equal'; + +import * as firestore from '@google-cloud/firestore'; +import {ResourcePath} from '../path'; +import {defaultConverter} from '../types'; +import {FilterInternal} from './filter-internal'; +import {FieldOrder} from './field-order'; +import {LimitType, QueryCursor} from './types'; +import {coalesce} from './helpers'; + +/** + * Internal class representing custom Query options. + * + * These options are immutable. Modified options can be created using `with()`. + * @private + * @internal + */ +export class QueryOptions< + AppModelType, + DbModelType extends firestore.DocumentData, +> { + constructor( + readonly parentPath: ResourcePath, + readonly collectionId: string, + readonly converter: firestore.FirestoreDataConverter< + AppModelType, + DbModelType + >, + readonly allDescendants: boolean, + readonly filters: FilterInternal[], + readonly fieldOrders: FieldOrder[], + readonly startAt?: QueryCursor, + readonly endAt?: QueryCursor, + readonly limit?: number, + readonly limitType?: LimitType, + readonly offset?: number, + readonly projection?: api.StructuredQuery.IProjection, + // Whether to select all documents under `parentPath`. By default, only + // collections that match `collectionId` are selected. + readonly kindless = false, + // Whether to require consistent documents when restarting the query. By + // default, restarting the query uses the readTime offset of the original + // query to provide consistent results. + readonly requireConsistency = true, + ) {} + + /** + * Returns query options for a collection group query. + * @private + * @internal + */ + static forCollectionGroupQuery< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, + >( + collectionId: string, + converter = defaultConverter(), + ): QueryOptions { + return new QueryOptions( + /*parentPath=*/ ResourcePath.EMPTY, + collectionId, + converter, + /*allDescendants=*/ true, + /*fieldFilters=*/ [], + /*fieldOrders=*/ [], + ); + } + + /** + * Returns query options for a single-collection query. + * @private + * @internal + */ + static forCollectionQuery< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, + >( + collectionRef: ResourcePath, + converter = defaultConverter(), + ): QueryOptions { + return new QueryOptions( + collectionRef.parent()!, + collectionRef.id!, + converter, + /*allDescendants=*/ false, + /*fieldFilters=*/ [], + /*fieldOrders=*/ [], + ); + } + + /** + * Returns query options for a query that fetches all descendants under the + * specified reference. + * + * @private + * @internal + */ + static forKindlessAllDescendants( + parent: ResourcePath, + id: string, + requireConsistency = true, + ): QueryOptions { + let options = new QueryOptions< + firestore.DocumentData, + firestore.DocumentData + >( + parent, + id, + defaultConverter(), + /*allDescendants=*/ true, + /*fieldFilters=*/ [], + /*fieldOrders=*/ [], + ); + + options = options.with({ + kindless: true, + requireConsistency, + }); + return options; + } + + /** + * Returns the union of the current and the provided options. + * @private + * @internal + */ + with( + settings: Partial< + Omit, 'converter'> + >, + ): QueryOptions { + return new QueryOptions( + coalesce(settings.parentPath, this.parentPath)!, + coalesce(settings.collectionId, this.collectionId)!, + this.converter, + coalesce(settings.allDescendants, this.allDescendants)!, + coalesce(settings.filters, this.filters)!, + coalesce(settings.fieldOrders, this.fieldOrders)!, + coalesce(settings.startAt, this.startAt), + coalesce(settings.endAt, this.endAt), + coalesce(settings.limit, this.limit), + coalesce(settings.limitType, this.limitType), + coalesce(settings.offset, this.offset), + coalesce(settings.projection, this.projection), + coalesce(settings.kindless, this.kindless), + coalesce(settings.requireConsistency, this.requireConsistency), + ); + } + + withConverter< + NewAppModelType, + NewDbModelType extends firestore.DocumentData = firestore.DocumentData, + >( + converter: firestore.FirestoreDataConverter< + NewAppModelType, + NewDbModelType + >, + ): QueryOptions { + return new QueryOptions( + this.parentPath, + this.collectionId, + converter, + this.allDescendants, + this.filters, + this.fieldOrders, + this.startAt, + this.endAt, + this.limit, + this.limitType, + this.offset, + this.projection, + ); + } + + hasFieldOrders(): boolean { + return this.fieldOrders.length > 0; + } + + isEqual(other: QueryOptions): boolean { + if (this === other) { + return true; + } + + return ( + other instanceof QueryOptions && + this.parentPath.isEqual(other.parentPath) && + this.filtersEqual(other.filters) && + this.collectionId === other.collectionId && + this.converter === other.converter && + this.allDescendants === other.allDescendants && + this.limit === other.limit && + this.offset === other.offset && + deepEqual(this.fieldOrders, other.fieldOrders) && + deepEqual(this.startAt, other.startAt) && + deepEqual(this.endAt, other.endAt) && + deepEqual(this.projection, other.projection) && + this.kindless === other.kindless && + this.requireConsistency === other.requireConsistency + ); + } + + private filtersEqual(other: FilterInternal[]): boolean { + if (this.filters.length !== other.length) { + return false; + } + + for (let i = 0; i < other.length; i++) { + if (!this.filters[i].isEqual(other[i])) { + return false; + } + } + return true; + } +} diff --git a/handwritten/firestore/dev/src/reference/query-snapshot.ts b/handwritten/firestore/dev/src/reference/query-snapshot.ts new file mode 100644 index 00000000000..6316bba2428 --- /dev/null +++ b/handwritten/firestore/dev/src/reference/query-snapshot.ts @@ -0,0 +1,296 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; +import {QueryDocumentSnapshot} from '../document'; +import {DocumentChange} from '../document-change'; +import {Timestamp} from '../timestamp'; +import {validateFunction} from '../validate'; +import {isArrayEqual} from '../util'; +import {Query} from './query'; + +/** + * A QuerySnapshot contains zero or more + * [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} objects + * representing the results of a query. The documents can be accessed as an + * array via the [documents]{@link QuerySnapshot#documents} property + * or enumerated using the [forEach]{@link QuerySnapshot#forEach} + * method. The number of documents can be determined via the + * [empty]{@link QuerySnapshot#empty} and + * [size]{@link QuerySnapshot#size} properties. + * + * @class QuerySnapshot + */ +export class QuerySnapshot< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> implements firestore.QuerySnapshot +{ + private _materializedDocs: Array< + QueryDocumentSnapshot + > | null = null; + private _materializedChanges: Array< + DocumentChange + > | null = null; + private _docs: + | (() => Array>) + | null = null; + private _changes: + | (() => Array>) + | null = null; + + /** + * @private + * + * @param _query The originating query. + * @param _readTime The time when this query snapshot was obtained. + * @param _size The number of documents in the result set. + * @param docs A callback returning a sorted array of documents matching + * this query + * @param changes A callback returning a sorted array of document change + * events for this snapshot. + */ + constructor( + private readonly _query: Query, + private readonly _readTime: Timestamp, + private readonly _size: number, + docs: () => Array>, + changes: () => Array>, + ) { + this._docs = docs; + this._changes = changes; + } + + /** + * The query on which you called get() or onSnapshot() in order to get this + * QuerySnapshot. + * + * @type {Query} + * @name QuerySnapshot#query + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.limit(10).get().then(querySnapshot => { + * console.log(`Returned first batch of results`); + * let query = querySnapshot.query; + * return query.offset(10).get(); + * }).then(() => { + * console.log(`Returned second batch of results`); + * }); + * ``` + */ + get query(): Query { + return this._query; + } + + /** + * An array of all the documents in this QuerySnapshot. + * + * @type {Array.} + * @name QuerySnapshot#docs + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then(querySnapshot => { + * let docs = querySnapshot.docs; + * for (let doc of docs) { + * console.log(`Document found at path: ${doc.ref.path}`); + * } + * }); + * ``` + */ + get docs(): Array> { + if (this._materializedDocs) { + return this._materializedDocs!; + } + this._materializedDocs = this._docs!(); + this._docs = null; + return this._materializedDocs!; + } + + /** + * True if there are no documents in the QuerySnapshot. + * + * @type {boolean} + * @name QuerySnapshot#empty + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then(querySnapshot => { + * if (querySnapshot.empty) { + * console.log('No documents found.'); + * } + * }); + * ``` + */ + get empty(): boolean { + return this._size === 0; + } + + /** + * The number of documents in the QuerySnapshot. + * + * @type {number} + * @name QuerySnapshot#size + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then(querySnapshot => { + * console.log(`Found ${querySnapshot.size} documents.`); + * }); + * ``` + */ + get size(): number { + return this._size; + } + + /** + * The time this query snapshot was obtained. + * + * @type {Timestamp} + * @name QuerySnapshot#readTime + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then((querySnapshot) => { + * let readTime = querySnapshot.readTime; + * console.log(`Query results returned at '${readTime.toDate()}'`); + * }); + * ``` + */ + get readTime(): Timestamp { + return this._readTime; + } + + /** + * Returns an array of the documents changes since the last snapshot. If + * this is the first snapshot, all documents will be in the list as added + * changes. + * + * @returns {Array.} + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.onSnapshot(querySnapshot => { + * let changes = querySnapshot.docChanges(); + * for (let change of changes) { + * console.log(`A document was ${change.type}.`); + * } + * }); + * ``` + */ + docChanges(): Array> { + if (this._materializedChanges) { + return this._materializedChanges!; + } + this._materializedChanges = this._changes!(); + this._changes = null; + return this._materializedChanges!; + } + + /** + * Enumerates all of the documents in the QuerySnapshot. This is a convenience + * method for running the same callback on each {@link QueryDocumentSnapshot} + * that is returned. + * + * @param {function} callback A callback to be called with a + * [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} for each document in + * the snapshot. + * @param {*=} thisArg The `this` binding for the callback.. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Document found at path: ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + forEach( + callback: ( + result: firestore.QueryDocumentSnapshot, + ) => void, + thisArg?: unknown, + ): void { + validateFunction('callback', callback); + + for (const doc of this.docs) { + callback.call(thisArg, doc); + } + } + + /** + * Returns true if the document data in this `QuerySnapshot` is equal to the + * provided value. + * + * @param {*} other The value to compare against. + * @returns {boolean} true if this `QuerySnapshot` is equal to the provided + * value. + */ + isEqual(other: firestore.QuerySnapshot): boolean { + // Since the read time is different on every query read, we explicitly + // ignore all metadata in this comparison. + + if (this === other) { + return true; + } + + if (!(other instanceof QuerySnapshot)) { + return false; + } + + if (this._size !== other._size) { + return false; + } + + if (!this._query.isEqual(other._query)) { + return false; + } + + if (this._materializedDocs && !this._materializedChanges) { + // If we have only materialized the documents, we compare them first. + return ( + isArrayEqual(this.docs, other.docs) && + isArrayEqual(this.docChanges(), other.docChanges()) + ); + } + + // Otherwise, we compare the changes first as we expect there to be fewer. + return ( + isArrayEqual(this.docChanges(), other.docChanges()) && + isArrayEqual(this.docs, other.docs) + ); + } +} diff --git a/handwritten/firestore/dev/src/reference/query-util.ts b/handwritten/firestore/dev/src/reference/query-util.ts new file mode 100644 index 00000000000..c05e84b3972 --- /dev/null +++ b/handwritten/firestore/dev/src/reference/query-util.ts @@ -0,0 +1,416 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; +import {GoogleError} from 'google-gax'; +import {Duplex, Transform} from 'stream'; + +import {Serializer} from '../serializer'; +import {Timestamp} from '../timestamp'; +import {DocumentSnapshotBuilder, QueryDocumentSnapshot} from '../document'; +import { + Deferred, + getTotalTimeout, + isPermanentRpcError, + requestTag, + wrapError, +} from '../util'; +import {DocumentChange} from '../document-change'; +import {ExplainMetrics} from '../query-profile'; +import {logger} from '../logger'; +import {VectorQuery} from './vector-query'; +import {Query} from './query'; +import Firestore from '../index'; +import {QueryOptions} from './query-options'; +import {LimitType, QueryResponse, QueryStreamElement} from './types'; +import {NOOP_MESSAGE} from './constants'; + +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import { + ATTRIBUTE_KEY_IS_RETRY_WITH_CURSOR, + ATTRIBUTE_KEY_IS_TRANSACTIONAL, + SPAN_NAME_RUN_QUERY, +} from '../telemetry/trace-util'; + +export class QueryUtil< + AppModelType, + DbModelType extends firestore.DocumentData, + Template extends + | Query + | VectorQuery, +> { + constructor( + /** @private */ + readonly _firestore: Firestore, + /** @private */ + readonly _queryOptions: QueryOptions, + /** @private */ + readonly _serializer: Serializer, + ) {} + + _getResponse( + query: Template, + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + retryWithCursor = true, + explainOptions?: firestore.ExplainOptions, + ): Promise>> { + // Capture the error stack to preserve stack tracing across async calls. + const stack = Error().stack!; + + return new Promise((resolve, reject) => { + const docs: Array> = []; + const output: Omit, 'result'> & { + readTime?: Timestamp; + } = {}; + + this._stream( + query, + transactionOrReadTime, + retryWithCursor, + explainOptions, + ) + .on('error', err => { + reject(wrapError(err, stack)); + }) + .on('data', (data: QueryStreamElement) => { + if (data.transaction) { + output.transaction = data.transaction; + } + if (data.readTime) { + output.readTime = data.readTime; + } + if (data.explainMetrics) { + output.explainMetrics = data.explainMetrics; + } + if (data.document) { + docs.push(data.document); + } + }) + .on('end', () => { + if (this._queryOptions.limitType === LimitType.Last) { + // The results for limitToLast queries need to be flipped since + // we reversed the ordering constraints before sending the query + // to the backend. + docs.reverse(); + } + + // Only return a snapshot when we have a readTime + // explain queries with analyze !== true will return no documents and no read time + const result = output.readTime + ? (query._createSnapshot( + output.readTime, + docs.length, + () => docs, + () => { + const changes: Array< + DocumentChange + > = []; + for (let i = 0; i < docs.length; ++i) { + changes.push(new DocumentChange('added', docs[i], -1, i)); + } + return changes; + }, + ) as ReturnType) + : undefined; + + resolve({ + transaction: output.transaction, + explainMetrics: output.explainMetrics, + result, + }); + }); + }); + } + + // This method exists solely to enable unit tests to mock it. + _isPermanentRpcError(err: GoogleError, methodName: string): boolean { + return isPermanentRpcError(err, methodName); + } + + _hasRetryTimedOut(methodName: string, startTime: number): boolean { + const totalTimeout = getTotalTimeout(methodName); + if (totalTimeout === 0) { + return false; + } + + return Date.now() - startTime >= totalTimeout; + } + + stream(query: Template): NodeJS.ReadableStream { + if (this._queryOptions.limitType === LimitType.Last) { + throw new Error( + 'Query results for queries that include limitToLast() ' + + 'constraints cannot be streamed. Use Query.get() instead.', + ); + } + + const responseStream = this._stream(query); + const transform = new Transform({ + objectMode: true, + transform(chunk, encoding, callback) { + callback(undefined, chunk.document); + }, + }); + + responseStream.pipe(transform); + responseStream.on('error', e => transform.destroy(e)); + return transform; + } + + _stream( + query: Template, + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + retryWithCursor = true, + explainOptions?: firestore.ExplainOptions, + ): NodeJS.ReadableStream { + const tag = requestTag(); + const startTime = Date.now(); + const isExplain = explainOptions !== undefined; + const methodName = 'runQuery'; + + let numDocumentsReceived = 0; + let lastReceivedDocument: QueryDocumentSnapshot< + AppModelType, + DbModelType + > | null = null; + + let backendStream: Duplex; + const stream = new Transform({ + objectMode: true, + transform: ( + proto: api.RunQueryResponse | typeof NOOP_MESSAGE, + enc, + callback, + ) => { + if (proto === NOOP_MESSAGE) { + callback(undefined); + return; + } + + const output: QueryStreamElement = {}; + + // Proto comes with zero-length buffer by default + if (proto.transaction?.length) { + output.transaction = proto.transaction; + } + + if (proto.readTime) { + output.readTime = Timestamp.fromProto(proto.readTime); + } + + if (proto.document) { + const document = this._firestore.snapshot_( + proto.document, + proto.readTime!, + ); + const finalDoc = new DocumentSnapshotBuilder< + AppModelType, + DbModelType + >(document.ref.withConverter(this._queryOptions.converter)); + // Recreate the QueryDocumentSnapshot with the DocumentReference + // containing the original converter. + finalDoc.fieldsProto = document._fieldsProto; + finalDoc.readTime = document.readTime; + finalDoc.createTime = document.createTime; + finalDoc.updateTime = document.updateTime; + lastReceivedDocument = finalDoc.build() as QueryDocumentSnapshot< + AppModelType, + DbModelType + >; + output.document = lastReceivedDocument; + } + + if (proto.explainMetrics) { + output.explainMetrics = ExplainMetrics._fromProto( + proto.explainMetrics, + this._serializer, + ); + } + + ++numDocumentsReceived; + callback(undefined, output); + + if (proto.done) { + logger('QueryUtil._stream', tag, 'Trigger Logical Termination.'); + this._firestore._traceUtil + .currentSpan() + .addEvent( + `Firestore.${methodName}: Received RunQueryResponse.Done.`, + ); + backendStream.unpipe(stream); + backendStream.resume(); + backendStream.end(); + stream.end(); + } + }, + }); + + this._firestore + .initializeIfNeeded(tag) + .then(async () => { + // `toProto()` might throw an exception. We rely on the behavior of an + // async function to convert this exception into the rejected Promise we + // catch below. + let request = query.toProto(transactionOrReadTime, explainOptions); + + let isRetryRequestWithCursor = false; + let streamActive: Deferred; + do { + streamActive = new Deferred(); + + this._firestore._traceUtil + .currentSpan() + .addEvent(SPAN_NAME_RUN_QUERY, { + [ATTRIBUTE_KEY_IS_TRANSACTIONAL]: !!request.transaction, + [ATTRIBUTE_KEY_IS_RETRY_WITH_CURSOR]: isRetryRequestWithCursor, + }); + + backendStream = await this._firestore.requestStream( + methodName, + /* bidirectional= */ false, + request, + tag, + ); + backendStream.on('error', err => { + backendStream.unpipe(stream); + + // If a non-transactional query failed, attempt to restart. + // Transactional queries are retried via the transaction runner. + // Explain queries are not retried with a cursor. That would produce + // incorrect/partial profiling results. + if ( + !isExplain && + !transactionOrReadTime && + !this._isPermanentRpcError(err, methodName) + ) { + logger( + 'QueryUtil._stream', + tag, + 'Query failed with retryable stream error:', + err, + ); + + this._firestore._traceUtil + .currentSpan() + .addEvent(`${SPAN_NAME_RUN_QUERY}: Retryable Error.`, { + 'error.message': err.message, + }); + + // Enqueue a "no-op" write into the stream and wait for it to be + // read by the downstream consumer. This ensures that all enqueued + // results in the stream are consumed, which will give us an accurate + // value for `lastReceivedDocument`. + stream.write(NOOP_MESSAGE, () => { + if (this._hasRetryTimedOut(methodName, startTime)) { + logger( + 'QueryUtil._stream', + tag, + 'Query failed with retryable stream error but the total retry timeout has exceeded.', + ); + stream.destroy(err); + streamActive.resolve(/* active= */ false); + } else if (lastReceivedDocument && retryWithCursor) { + if (query instanceof VectorQuery) { + throw new Error( + 'Unimplemented: Vector query does not support cursors yet.', + ); + } + + logger( + 'Query._stream', + tag, + 'Query failed with retryable stream error and progress was made receiving ' + + 'documents, so the stream is being retried.', + ); + + isRetryRequestWithCursor = true; + + // Restart the query but use the last document we received as + // the query cursor. Note that we do not use backoff here. The + // call to `requestStream()` will backoff should the restart + // fail before delivering any results. + let newQuery: Query; + if (!this._queryOptions.limit) { + newQuery = query; + } else { + const newLimit = + this._queryOptions.limit - numDocumentsReceived; + if ( + this._queryOptions.limitType === undefined || + this._queryOptions.limitType === LimitType.First + ) { + newQuery = query.limit(newLimit); + } else { + newQuery = query.limitToLast(newLimit); + } + } + + if (this._queryOptions.requireConsistency) { + request = newQuery + .startAfter(lastReceivedDocument) + .toProto(lastReceivedDocument.readTime); + } else { + request = newQuery + .startAfter(lastReceivedDocument) + .toProto(); + } + + // Set lastReceivedDocument to null before each retry attempt to ensure the retry makes progress + lastReceivedDocument = null; + + streamActive.resolve(/* active= */ true); + } else { + logger( + 'QueryUtil._stream', + tag, + `Query failed with retryable stream error however either retryWithCursor="${retryWithCursor}", or ` + + 'no progress was made receiving documents, so the stream is being closed.', + ); + stream.destroy(err); + streamActive.resolve(/* active= */ false); + } + }); + } else { + logger( + 'QueryUtil._stream', + tag, + 'Query failed with stream error:', + err, + ); + + this._firestore._traceUtil + .currentSpan() + .addEvent(`${SPAN_NAME_RUN_QUERY}: Error.`, { + 'error.message': err.message, + }); + + stream.destroy(err); + streamActive.resolve(/* active= */ false); + } + }); + backendStream.on('end', () => { + streamActive.resolve(/* active= */ false); + }); + backendStream.resume(); + backendStream.pipe(stream); + } while (await streamActive.promise); + }) + .catch(e => stream.destroy(e)); + + return stream; + } +} diff --git a/handwritten/firestore/dev/src/reference/query.ts b/handwritten/firestore/dev/src/reference/query.ts new file mode 100644 index 00000000000..49e8e99353f --- /dev/null +++ b/handwritten/firestore/dev/src/reference/query.ts @@ -0,0 +1,1838 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import * as firestore from '@google-cloud/firestore'; +import {GoogleError} from 'google-gax'; +import {Transform} from 'stream'; +import {and, field, Ordering} from '../pipelines'; + +import {CompositeFilter, UnaryFilter} from '../filter'; +import { + AggregateField, + DocumentChange, + DocumentSnapshot, + FieldPath, + Filter, + Firestore, + QueryDocumentSnapshot, + Timestamp, +} from '../index'; +import {compare} from '../order'; +import {validateFieldPath} from '../path'; +import {Pipeline} from '../pipelines'; +import { + reverseOrderings, + toPipelineBooleanExpr, + whereConditionsFromCursor, +} from '../pipelines/pipeline-util'; +import {ExplainResults} from '../query-profile'; +import {Serializer} from '../serializer'; +import {defaultConverter} from '../types'; +import { + invalidArgumentMessage, + validateFunction, + validateInteger, + validateMinNumberOfArguments, +} from '../validate'; +import {QueryWatch} from '../watch'; +import {AggregateQuery} from './aggregate-query'; +import {CompositeFilterInternal} from './composite-filter-internal'; +import {comparisonOperators, directionOperators} from './constants'; +import {DocumentReference} from './document-reference'; +import {FieldFilterInternal} from './field-filter-internal'; +import {FieldOrder} from './field-order'; +import {FilterInternal} from './filter-internal'; +import { + validateQueryOperator, + validateQueryOrder, + validateQueryValue, +} from './helpers'; +import {QueryOptions} from './query-options'; +import {QuerySnapshot} from './query-snapshot'; + +import {QueryUtil} from './query-util'; +import { + LimitType, + QueryCursor, + QueryResponse, + QuerySnapshotResponse, + QueryStreamElement, +} from './types'; +import {VectorQuery} from './vector-query'; +import {VectorQueryOptions} from './vector-query-options'; +import {SPAN_NAME_QUERY_GET} from '../telemetry/trace-util'; + +/** + * A Query refers to a query which you can read or stream from. You can also + * construct refined Query objects by adding filters and ordering. + * + * @class Query + */ +export class Query< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> implements firestore.Query +{ + /** + * @internal + * @private + **/ + readonly _serializer: Serializer; + /** + * @internal + * @private + **/ + protected readonly _allowUndefined: boolean; + /** + * @internal + * @private + **/ + readonly _queryUtil: QueryUtil< + AppModelType, + DbModelType, + Query + >; + + /** + * @internal + * @private + * + * @param _firestore The Firestore Database client. + * @param _queryOptions Options that define the query. + */ + constructor( + /** + * @internal + * @private + **/ + readonly _firestore: Firestore, + /** + * @internal + * @private + **/ + readonly _queryOptions: QueryOptions, + ) { + this._serializer = new Serializer(_firestore); + this._allowUndefined = + !!this._firestore._settings.ignoreUndefinedProperties; + this._queryUtil = new QueryUtil< + AppModelType, + DbModelType, + Query + >(_firestore, _queryOptions, this._serializer); + } + + /** + * Extracts field values from the DocumentSnapshot based on the provided + * field order. + * + * @private + * @internal + * @param documentSnapshot The document to extract the fields from. + * @param fieldOrders The field order that defines what fields we should + * extract. + * @returns {Array.<*>} The field values to use. + */ + static _extractFieldValues( + documentSnapshot: DocumentSnapshot, + fieldOrders: FieldOrder[], + ): unknown[] { + const fieldValues: unknown[] = []; + + for (const fieldOrder of fieldOrders) { + if (FieldPath.documentId().isEqual(fieldOrder.field)) { + fieldValues.push(documentSnapshot.ref); + } else { + const fieldValue = documentSnapshot.get(fieldOrder.field); + if (fieldValue === undefined) { + throw new Error( + `Field "${fieldOrder.field}" is missing in the provided DocumentSnapshot. ` + + 'Please provide a document that contains values for all specified ' + + 'orderBy() and where() constraints.', + ); + } else { + fieldValues.push(fieldValue); + } + } + } + return fieldValues; + } + + /** + * The [Firestore]{@link Firestore} instance for the Firestore + * database (useful for performing transactions, etc.). + * + * @type {Firestore} + * @name Query#firestore + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.add({foo: 'bar'}).then(documentReference => { + * let firestore = documentReference.firestore; + * console.log(`Root location for document is ${firestore.formattedName}`); + * }); + * ``` + */ + get firestore(): Firestore { + return this._firestore; + } + + /** + * Creates and returns a new [Query]{@link Query} with the additional filter + * that documents must contain the specified field and that its value should + * satisfy the relation constraint provided. + * + * This function returns a new (immutable) instance of the Query (rather than + * modify the existing instance) to impose the filter. + * + * @param {string|FieldPath} fieldPath The name of a property value to compare. + * @param {string} opStr A comparison operation in the form of a string. + * Acceptable operator strings are "<", "<=", "==", "!=", ">=", ">", "array-contains", + * "in", "not-in", and "array-contains-any". + * @param {*} value The value to which to compare the field for inclusion in + * a query. + * @returns {Query} The created Query. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.where('foo', '==', 'bar').get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + where( + fieldPath: string | FieldPath, + opStr: firestore.WhereFilterOp, + value: unknown, + ): Query; + + /** + * Creates and returns a new [Query]{@link Query} with the additional filter + * that documents should satisfy the relation constraint(s) provided. + * + * This function returns a new (immutable) instance of the Query (rather than + * modify the existing instance) to impose the filter. + * + * @param {Filter} filter A unary or composite filter to apply to the Query. + * @returns {Query} The created Query. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.where(Filter.and(Filter.where('foo', '==', 'bar'), Filter.where('foo', '!=', 'baz'))).get() + * .then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + where(filter: Filter): Query; + + where( + fieldPathOrFilter: string | firestore.FieldPath | Filter, + opStr?: firestore.WhereFilterOp, + value?: unknown, + ): Query { + let filter: Filter; + + if (fieldPathOrFilter instanceof Filter) { + filter = fieldPathOrFilter; + } else { + filter = Filter.where(fieldPathOrFilter, opStr!, value); + } + + if (this._queryOptions.startAt || this._queryOptions.endAt) { + throw new Error( + 'Cannot specify a where() filter after calling startAt(), ' + + 'startAfter(), endBefore() or endAt().', + ); + } + + const parsedFilter = this._parseFilter(filter); + + if (parsedFilter.getFilters().length === 0) { + // Return the existing query if not adding any more filters (e.g. an empty composite filter). + return this; + } + + const options = this._queryOptions.with({ + filters: this._queryOptions.filters.concat(parsedFilter), + }); + return new Query(this._firestore, options); + } + + /** + * @internal + * @private + */ + _parseFilter(filter: Filter): FilterInternal { + if (filter instanceof UnaryFilter) { + return this._parseFieldFilter(filter); + } + return this._parseCompositeFilter(filter as CompositeFilter); + } + + /** + * @internal + * @private + */ + _parseFieldFilter(fieldFilterData: UnaryFilter): FieldFilterInternal { + let value = fieldFilterData._getValue(); + let operator = fieldFilterData._getOperator(); + const fieldPath = fieldFilterData._getField(); + + validateFieldPath('fieldPath', fieldPath); + + operator = validateQueryOperator('opStr', operator, value); + validateQueryValue('value', value, this._allowUndefined); + + const path = FieldPath.fromArgument(fieldPath); + + if (FieldPath.documentId().isEqual(path)) { + if (operator === 'array-contains' || operator === 'array-contains-any') { + throw new Error( + `Invalid Query. You can't perform '${operator}' ` + + 'queries on FieldPath.documentId().', + ); + } else if (operator === 'in' || operator === 'not-in') { + if (!Array.isArray(value) || value.length === 0) { + throw new Error( + `Invalid Query. A non-empty array is required for '${operator}' filters.`, + ); + } + value = value.map(el => this.validateReference(el)); + } else { + value = this.validateReference(value); + } + } + + return new FieldFilterInternal( + this._serializer, + path, + comparisonOperators[operator], + value, + ); + } + + /** + * @internal + * @private + */ + _parseCompositeFilter(compositeFilterData: CompositeFilter): FilterInternal { + const parsedFilters = compositeFilterData + ._getFilters() + .map(filter => this._parseFilter(filter)) + .filter(parsedFilter => parsedFilter.getFilters().length > 0); + + // For composite filters containing 1 filter, return the only filter. + // For example: AND(FieldFilter1) == FieldFilter1 + if (parsedFilters.length === 1) { + return parsedFilters[0]; + } + return new CompositeFilterInternal( + parsedFilters, + compositeFilterData._getOperator() === 'AND' ? 'AND' : 'OR', + ); + } + + /** + * Creates and returns a new [Query]{@link Query} instance that applies a + * field mask to the result and returns only the specified subset of fields. + * You can specify a list of field paths to return, or use an empty list to + * only return the references of matching documents. + * + * Queries that contain field masks cannot be listened to via `onSnapshot()` + * listeners. + * + * This function returns a new (immutable) instance of the Query (rather than + * modify the existing instance) to impose the field mask. + * + * @param {...(string|FieldPath)} fieldPaths The field paths to return. + * @returns {Query} The created Query. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * let documentRef = collectionRef.doc('doc'); + * + * return documentRef.set({x:10, y:5}).then(() => { + * return collectionRef.where('x', '>', 5).select('y').get(); + * }).then((res) => { + * console.log(`y is ${res.docs[0].get('y')}.`); + * }); + * ``` + */ + select(...fieldPaths: Array): Query { + const fields: api.StructuredQuery.IFieldReference[] = []; + + if (fieldPaths.length === 0) { + fields.push({fieldPath: FieldPath.documentId().formattedName}); + } else { + for (let i = 0; i < fieldPaths.length; ++i) { + validateFieldPath(i, fieldPaths[i]); + fields.push({ + fieldPath: FieldPath.fromArgument(fieldPaths[i]).formattedName, + }); + } + } + + // By specifying a field mask, the query result no longer conforms to type + // `T`. We there return `Query`; + const options = this._queryOptions.with({ + projection: {fields}, + }) as QueryOptions; + return new Query(this._firestore, options); + } + + /** + * Creates and returns a new [Query]{@link Query} that's additionally sorted + * by the specified field, optionally in descending order instead of + * ascending. + * + * This function returns a new (immutable) instance of the Query (rather than + * modify the existing instance) to impose the field mask. + * + * @param {string|FieldPath} fieldPath The field to sort by. + * @param {string=} directionStr Optional direction to sort by ('asc' or + * 'desc'). If not specified, order will be ascending. + * @returns {Query} The created Query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '>', 42); + * + * query.orderBy('foo', 'desc').get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + orderBy( + fieldPath: string | firestore.FieldPath, + directionStr?: firestore.OrderByDirection, + ): Query { + validateFieldPath('fieldPath', fieldPath); + directionStr = validateQueryOrder('directionStr', directionStr); + + if (this._queryOptions.startAt || this._queryOptions.endAt) { + throw new Error( + 'Cannot specify an orderBy() constraint after calling ' + + 'startAt(), startAfter(), endBefore() or endAt().', + ); + } + + const newOrder = new FieldOrder( + FieldPath.fromArgument(fieldPath), + directionOperators[directionStr || 'asc'], + ); + + const options = this._queryOptions.with({ + fieldOrders: this._queryOptions.fieldOrders.concat(newOrder), + }); + return new Query(this._firestore, options); + } + + /** + * Creates and returns a new [Query]{@link Query} that only returns the + * first matching documents. + * + * This function returns a new (immutable) instance of the Query (rather than + * modify the existing instance) to impose the limit. + * + * @param {number} limit The maximum number of items to return. + * @returns {Query} The created Query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '>', 42); + * + * query.limit(1).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + limit(limit: number): Query { + validateInteger('limit', limit); + + const options = this._queryOptions.with({ + limit, + limitType: LimitType.First, + }); + return new Query(this._firestore, options); + } + + /** + * Creates and returns a new [Query]{@link Query} that only returns the + * last matching documents. + * + * You must specify at least one orderBy clause for limitToLast queries, + * otherwise an exception will be thrown during execution. + * + * Results for limitToLast queries cannot be streamed via the `stream()` API. + * + * @param limit The maximum number of items to return. + * @returns The created Query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '>', 42); + * + * query.limitToLast(1).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Last matching document is ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + limitToLast(limit: number): Query { + validateInteger('limitToLast', limit); + + const options = this._queryOptions.with({limit, limitType: LimitType.Last}); + return new Query(this._firestore, options); + } + + /** + * Specifies the offset of the returned results. + * + * This function returns a new (immutable) instance of the + * [Query]{@link Query} (rather than modify the existing instance) + * to impose the offset. + * + * @param {number} offset The offset to apply to the Query results + * @returns {Query} The created Query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '>', 42); + * + * query.limit(10).offset(20).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + offset(offset: number): Query { + validateInteger('offset', offset); + + const options = this._queryOptions.with({offset}); + return new Query(this._firestore, options); + } + + /** + * Returns a query that counts the documents in the result set of this + * query. + * + * The returned query, when executed, counts the documents in the result set + * of this query without actually downloading the documents. + * + * Using the returned query to count the documents is efficient because only + * the final count, not the documents' data, is downloaded. The returned + * query can count the documents in cases where the result set is + * prohibitively large to download entirely (thousands of documents). + * + * @returns a query that counts the documents in the result set of this + * query. The count can be retrieved from `snapshot.data().count`, where + * `snapshot` is the `AggregateQuerySnapshot` resulting from running the + * returned query. + */ + count(): AggregateQuery< + {count: firestore.AggregateField}, + AppModelType, + DbModelType + > { + return this.aggregate({ + count: AggregateField.count(), + }); + } + + /** + * Returns a query that can perform the given aggregations. + * + * The returned query, when executed, calculates the specified aggregations + * over the documents in the result set of this query without actually + * downloading the documents. + * + * Using the returned query to perform aggregations is efficient because only + * the final aggregation values, not the documents' data, is downloaded. The + * returned query can perform aggregations of the documents count the + * documents in cases where the result set is prohibitively large to download + * entirely (thousands of documents). + * + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateQuery = col.aggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const aggregateSnapshot = await aggregateQuery.get(); + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ + aggregate( + aggregateSpec: T, + ): AggregateQuery { + return new AggregateQuery( + this, + aggregateSpec, + ); + } + + /** + * Returns a query that can perform vector distance (similarity) search with given parameters. + * + * The returned query, when executed, performs a distance (similarity) search on the specified + * `vectorField` against the given `queryVector` and returns the top documents that are closest + * to the `queryVector`. + * + * Only documents whose `vectorField` field is a {@link VectorValue} of the same dimension as `queryVector` + * participate in the query, all other documents are ignored. + * + * @example + * ``` + * // Returns the closest 10 documents whose Euclidean distance from their 'embedding' fields are closed to [41, 42]. + * const vectorQuery = col.findNearest('embedding', [41, 42], {limit: 10, distanceMeasure: 'EUCLIDEAN'}); + * + * const querySnapshot = await vectorQuery.get(); + * querySnapshot.forEach(...); + * ``` + * + * @param vectorField - A string or {@link FieldPath} specifying the vector field to search on. + * @param queryVector - The {@link VectorValue} used to measure the distance from `vectorField` values in the documents. + * @param options - Options control the vector query. `limit` specifies the upper bound of documents to return, must + * be a positive integer with a maximum value of 1000. `distanceMeasure` specifies what type of distance is calculated + * when performing the query. + * + * @deprecated Use the new {@link Query.(findNearest:VectorQueryOptions)} implementation + * accepting a single `options` param. + */ + findNearest( + vectorField: string | firestore.FieldPath, + queryVector: firestore.VectorValue | Array, + options: { + limit: number; + distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; + }, + ): VectorQuery; + + /** + * Returns a query that can perform vector distance (similarity) search with given parameters. + * + * The returned query, when executed, performs a distance (similarity) search on the specified + * `vectorField` against the given `queryVector` and returns the top documents that are closest + * to the `queryVector`. + * + * Only documents whose `vectorField` field is a {@link VectorValue} of the same dimension as `queryVector` + * participate in the query, all other documents are ignored. + * + * @example + * ``` + * // Returns the closest 10 documents whose Euclidean distance from their 'embedding' fields are closed to [41, 42]. + * const vectorQuery = col.findNearest({ + * vectorField: 'embedding', + * queryVector: [41, 42], + * limit: 10, + * distanceMeasure: 'EUCLIDEAN', + * distanceResultField: 'distance', + * distanceThreshold: 0.125 + * }); + * + * const querySnapshot = await aggregateQuery.get(); + * querySnapshot.forEach(...); + * ``` + * @param options - An argument specifying the behavior of the {@link VectorQuery} returned by this function. + * See {@link VectorQueryOptions}. + */ + findNearest( + options: VectorQueryOptions, + ): VectorQuery; + + findNearest( + vectorFieldOrOptions: string | firestore.FieldPath | VectorQueryOptions, + queryVector?: firestore.VectorValue | Array, + options?: { + limit?: number; + distanceMeasure?: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; + }, + ): VectorQuery { + if ( + typeof vectorFieldOrOptions === 'string' || + vectorFieldOrOptions instanceof FieldPath + ) { + const vqOptions: VectorQueryOptions = { + distanceMeasure: options!.distanceMeasure!, + limit: options!.limit!, + queryVector: queryVector!, + vectorField: vectorFieldOrOptions, + }; + return this._findNearest(vqOptions); + } else { + return this._findNearest(vectorFieldOrOptions as VectorQueryOptions); + } + } + + _findNearest( + options: VectorQueryOptions, + ): VectorQuery { + validateFieldPath('vectorField', options.vectorField); + + if (options.limit <= 0) { + throw invalidArgumentMessage('limit', 'positive limit number'); + } + + if ( + (Array.isArray(options.queryVector) + ? options.queryVector.length + : options.queryVector.toArray().length) === 0 + ) { + throw invalidArgumentMessage( + 'queryVector', + 'vector size must be larger than 0', + ); + } + + return new VectorQuery(this, options); + } + + /** + * Returns a value indicating if this query is a collection group query + */ + _isCollectionGroupQuery(): boolean { + return this._queryOptions.allDescendants; + } + + /** + * @private + * @internal + */ + _pipeline(): Pipeline { + let pipeline: Pipeline; + const db = this.firestore; + if (this._isCollectionGroupQuery()) { + pipeline = db + .pipeline() + .collectionGroup(this._queryOptions.collectionId!); + } else { + pipeline = db + .pipeline() + .collection( + this._queryOptions.parentPath.append(this._queryOptions.collectionId) + .relativeName, + ); + } + + // filters + for (const filter of this._queryOptions.filters) { + pipeline = pipeline.where( + toPipelineBooleanExpr(filter, this._serializer), + ); + } + + // projections + const projections = this._queryOptions.projection?.fields || []; + if (projections.length > 0) { + const projectionFields = projections.map(p => field(p.fieldPath!)); + pipeline = pipeline.select( + projectionFields[0], + ...projectionFields.slice(1), + ); + } + + // orders + // Ignore inequality fields when creating implicit order-bys + // for generating existsConditions, because existence filters + // will have already been added in the call to `toPipelineBooleanExpr` + const existsConditions = this.createImplicitOrderBy(true).map( + fieldOrder => { + return field(fieldOrder.field).exists(); + }, + ); + if (existsConditions.length > 1) { + const [first, second, ...rest] = existsConditions; + pipeline = pipeline.where(and(first, second, ...rest)); + } else { + pipeline = pipeline.where(existsConditions[0]); + } + + const orderings = this.createImplicitOrderBy().map(fieldOrder => { + let dir: 'ascending' | 'descending' | undefined = undefined; + switch (fieldOrder.direction) { + case 'ASCENDING': { + dir = 'ascending'; + break; + } + case 'DESCENDING': { + dir = 'descending'; + break; + } + } + return new Ordering(field(fieldOrder.field), dir || 'ascending'); + }); + + if (orderings.length > 0) { + if (this._queryOptions.limitType === LimitType.Last) { + const actualOrderings = reverseOrderings(orderings); + pipeline = pipeline.sort( + actualOrderings[0], + ...actualOrderings.slice(1), + ); + // cursors + if (this._queryOptions.startAt !== undefined) { + pipeline = pipeline.where( + whereConditionsFromCursor( + this._queryOptions.startAt, + orderings, + 'after', + ), + ); + } + + if (this._queryOptions.endAt !== undefined) { + pipeline = pipeline.where( + whereConditionsFromCursor( + this._queryOptions.endAt, + orderings, + 'before', + ), + ); + } + + if (this._queryOptions.limit !== undefined) { + pipeline = pipeline.limit(this._queryOptions.limit!); + } + + pipeline = pipeline.sort(orderings[0], ...orderings.slice(1)); + } else { + pipeline = pipeline.sort(orderings[0], ...orderings.slice(1)); + if (this._queryOptions.startAt !== undefined) { + pipeline = pipeline.where( + whereConditionsFromCursor( + this._queryOptions.startAt, + orderings, + 'after', + ), + ); + } + if (this._queryOptions.endAt !== undefined) { + pipeline = pipeline.where( + whereConditionsFromCursor( + this._queryOptions.endAt, + orderings, + 'before', + ), + ); + } + + if (this._queryOptions.limit !== undefined) { + pipeline = pipeline.limit(this._queryOptions.limit); + } + } + } + + // offset + if (this._queryOptions.offset) { + pipeline = pipeline.offset(this._queryOptions.offset); + } + + return pipeline; + } + + /** + * Returns true if this `Query` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @returns {boolean} true if this `Query` is equal to the provided value. + */ + isEqual(other: firestore.Query): boolean { + if (this === other) { + return true; + } + + return ( + other instanceof Query && this._queryOptions.isEqual(other._queryOptions) + ); + } + + /** + * Returns the sorted array of inequality filter fields used in this query. + * + * @returns An array of inequality filter fields sorted lexicographically by FieldPath. + */ + private getInequalityFilterFields(): FieldPath[] { + const inequalityFields: FieldPath[] = []; + + for (const filter of this._queryOptions.filters) { + for (const subFilter of filter.getFlattenedFilters()) { + if (subFilter.isInequalityFilter()) { + inequalityFields.push(subFilter.field); + } + } + } + + return inequalityFields.sort((a, b) => a.compareTo(b)); + } + + /** + * Computes the backend ordering semantics for DocumentSnapshot cursors. + * + * @private + * @internal + * @param cursorValuesOrDocumentSnapshot The snapshot of the document or the + * set of field values to use as the boundary. + * @returns The implicit ordering semantics. + */ + private createImplicitOrderByForCursor( + cursorValuesOrDocumentSnapshot: Array< + DocumentSnapshot | unknown + >, + ): FieldOrder[] { + // Add an implicit orderBy if the only cursor value is a DocumentSnapshot. + if ( + cursorValuesOrDocumentSnapshot.length !== 1 || + !(cursorValuesOrDocumentSnapshot[0] instanceof DocumentSnapshot) + ) { + return this._queryOptions.fieldOrders; + } + + return this.createImplicitOrderBy(); + } + + private createImplicitOrderBy(ignoreInequalityFields = false): FieldOrder[] { + const fieldOrders = this._queryOptions.fieldOrders.slice(); + const fieldsNormalized = new Set([ + ...fieldOrders.map(item => item.field.toString()), + ]); + + /** The order of the implicit ordering always matches the last explicit order by. */ + const lastDirection = + fieldOrders.length === 0 + ? directionOperators.ASC + : fieldOrders[fieldOrders.length - 1].direction; + + if (!ignoreInequalityFields) { + /** + * Any inequality fields not explicitly ordered should be implicitly ordered in a + * lexicographical order. When there are multiple inequality filters on the same field, the + * field should be added only once. + * Note: getInequalityFilterFields function sorts the key field before + * other fields. However, we want the key field to be sorted last. + */ + const inequalityFields = this.getInequalityFilterFields(); + for (const field of inequalityFields) { + if ( + !fieldsNormalized.has(field.toString()) && + !field.isEqual(FieldPath.documentId()) + ) { + fieldOrders.push(new FieldOrder(field, lastDirection)); + fieldsNormalized.add(field.toString()); + } + } + } + + // Add the document key field to the last if it is not explicitly ordered. + if (!fieldsNormalized.has(FieldPath.documentId().toString())) { + fieldOrders.push(new FieldOrder(FieldPath.documentId(), lastDirection)); + } + + return fieldOrders; + } + + /** + * Builds a Firestore 'Position' proto message. + * + * @private + * @internal + * @param {Array.} fieldOrders The field orders to use for this + * cursor. + * @param {Array.} cursorValuesOrDocumentSnapshot The + * snapshot of the document or the set of field values to use as the boundary. + * @param before Whether the query boundary lies just before or after the + * provided data. + * @returns {Object} The proto message. + */ + private createCursor( + fieldOrders: FieldOrder[], + cursorValuesOrDocumentSnapshot: Array, + before: boolean, + ): QueryCursor { + let fieldValues; + + if ( + cursorValuesOrDocumentSnapshot.length === 1 && + cursorValuesOrDocumentSnapshot[0] instanceof DocumentSnapshot + ) { + fieldValues = Query._extractFieldValues( + cursorValuesOrDocumentSnapshot[0] as DocumentSnapshot, + fieldOrders, + ); + } else { + fieldValues = cursorValuesOrDocumentSnapshot; + } + + if (fieldValues.length > fieldOrders.length) { + throw new Error( + 'Too many cursor values specified. The specified ' + + 'values must match the orderBy() constraints of the query.', + ); + } + + const options: QueryCursor = {values: [], before}; + + for (let i = 0; i < fieldValues.length; ++i) { + let fieldValue = fieldValues[i]; + + if (FieldPath.documentId().isEqual(fieldOrders[i].field)) { + fieldValue = this.validateReference(fieldValue); + } + + validateQueryValue(i, fieldValue, this._allowUndefined); + options.values!.push(this._serializer.encodeValue(fieldValue)!); + } + + return options; + } + + /** + * Validates that a value used with FieldValue.documentId() is either a + * string or a DocumentReference that is part of the query`s result set. + * Throws a validation error or returns a DocumentReference that can + * directly be used in the Query. + * + * @param val The value to validate. + * @throws If the value cannot be used for this query. + * @returns If valid, returns a DocumentReference that can be used with the + * query. + * @private + * @internal + */ + private validateReference( + val: unknown, + ): DocumentReference { + const basePath = this._queryOptions.allDescendants + ? this._queryOptions.parentPath + : this._queryOptions.parentPath.append(this._queryOptions.collectionId); + let reference: DocumentReference; + + if (typeof val === 'string') { + const path = basePath.append(val); + + if (this._queryOptions.allDescendants) { + if (!path.isDocument) { + throw new Error( + 'When querying a collection group and ordering by ' + + 'FieldPath.documentId(), the corresponding value must result in ' + + `a valid document path, but '${val}' is not because it ` + + 'contains an odd number of segments.', + ); + } + } else if (val.indexOf('/') !== -1) { + throw new Error( + 'When querying a collection and ordering by FieldPath.documentId(), ' + + `the corresponding value must be a plain document ID, but '${val}' ` + + 'contains a slash.', + ); + } + + reference = new DocumentReference( + this._firestore, + basePath.append(val), + this._queryOptions.converter, + ); + } else if (val instanceof DocumentReference) { + reference = val; + if (!basePath.isPrefixOf(reference._path)) { + throw new Error( + `"${reference.path}" is not part of the query result set and ` + + 'cannot be used as a query boundary.', + ); + } + } else { + throw new Error( + 'The corresponding value for FieldPath.documentId() must be a ' + + `string or a DocumentReference, but was "${val}".`, + ); + } + + if ( + !this._queryOptions.allDescendants && + reference._path.parent()!.compareTo(basePath) !== 0 + ) { + throw new Error( + 'Only a direct child can be used as a query boundary. ' + + `Found: "${reference.path}".`, + ); + } + return reference; + } + + /** + * Creates and returns a new [Query]{@link Query} that starts at the provided + * set of field values relative to the order of the query. The order of the + * provided values must match the order of the order by clauses of the query. + * + * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot The snapshot + * of the document the query results should start at or the field values to + * start this query at, in order of the query's order by. + * @returns {Query} A query with the new starting point. + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.orderBy('foo').startAt(42).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + startAt( + ...fieldValuesOrDocumentSnapshot: Array + ): Query { + validateMinNumberOfArguments( + 'Query.startAt', + fieldValuesOrDocumentSnapshot, + 1, + ); + + const fieldOrders = this.createImplicitOrderByForCursor( + fieldValuesOrDocumentSnapshot, + ); + const startAt = this.createCursor( + fieldOrders, + fieldValuesOrDocumentSnapshot, + true, + ); + + const options = this._queryOptions.with({fieldOrders, startAt}); + return new Query(this._firestore, options); + } + + /** + * Creates and returns a new [Query]{@link Query} that starts after the + * provided set of field values relative to the order of the query. The order + * of the provided values must match the order of the order by clauses of the + * query. + * + * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot The snapshot + * of the document the query results should start after or the field values to + * start this query after, in order of the query's order by. + * @returns {Query} A query with the new starting point. + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.orderBy('foo').startAfter(42).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + startAfter( + ...fieldValuesOrDocumentSnapshot: Array + ): Query { + validateMinNumberOfArguments( + 'Query.startAfter', + fieldValuesOrDocumentSnapshot, + 1, + ); + + const fieldOrders = this.createImplicitOrderByForCursor( + fieldValuesOrDocumentSnapshot, + ); + const startAt = this.createCursor( + fieldOrders, + fieldValuesOrDocumentSnapshot, + false, + ); + + const options = this._queryOptions.with({fieldOrders, startAt}); + return new Query(this._firestore, options); + } + + /** + * Creates and returns a new [Query]{@link Query} that ends before the set of + * field values relative to the order of the query. The order of the provided + * values must match the order of the order by clauses of the query. + * + * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot The snapshot + * of the document the query results should end before or the field values to + * end this query before, in order of the query's order by. + * @returns {Query} A query with the new ending point. + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.orderBy('foo').endBefore(42).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + endBefore( + ...fieldValuesOrDocumentSnapshot: Array + ): Query { + validateMinNumberOfArguments( + 'Query.endBefore', + fieldValuesOrDocumentSnapshot, + 1, + ); + + const fieldOrders = this.createImplicitOrderByForCursor( + fieldValuesOrDocumentSnapshot, + ); + const endAt = this.createCursor( + fieldOrders, + fieldValuesOrDocumentSnapshot, + true, + ); + + const options = this._queryOptions.with({fieldOrders, endAt}); + return new Query(this._firestore, options); + } + + /** + * Creates and returns a new [Query]{@link Query} that ends at the provided + * set of field values relative to the order of the query. The order of the + * provided values must match the order of the order by clauses of the query. + * + * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot The snapshot + * of the document the query results should end at or the field values to end + * this query at, in order of the query's order by. + * @returns {Query} A query with the new ending point. + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.orderBy('foo').endAt(42).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + endAt( + ...fieldValuesOrDocumentSnapshot: Array + ): Query { + validateMinNumberOfArguments( + 'Query.endAt', + fieldValuesOrDocumentSnapshot, + 1, + ); + + const fieldOrders = this.createImplicitOrderByForCursor( + fieldValuesOrDocumentSnapshot, + ); + const endAt = this.createCursor( + fieldOrders, + fieldValuesOrDocumentSnapshot, + false, + ); + + const options = this._queryOptions.with({fieldOrders, endAt}); + return new Query(this._firestore, options); + } + + /** + * Executes the query and returns the results as a + * [QuerySnapshot]{@link QuerySnapshot}. + * + * @returns {Promise.} A Promise that resolves with the results + * of the Query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + async get(): Promise> { + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_QUERY_GET, + async () => { + const {result} = await this._get(); + return result; + }, + ); + } + + /** + * Plans and optionally executes this query. Returns a Promise that will be + * resolved with the planner information, statistics from the query execution (if any), + * and the query results (if any). + * + * @returns A Promise that will be resolved with the planner information, statistics + * from the query execution (if any), and the query results (if any). + */ + async explain( + options?: firestore.ExplainOptions, + ): Promise>> { + if (options === undefined) { + options = {}; + } + const {result, explainMetrics} = await this._getResponse( + undefined, + options, + ); + if (!explainMetrics) { + throw new Error('No explain results'); + } + return new ExplainResults(explainMetrics, result || null); + } + + /** + * Internal get() method that accepts an optional transaction options, and + * returns a query snapshot with transaction and explain metadata. + * + * @private + * @internal + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + */ + async _get( + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + ): Promise>> { + const result = await this._getResponse(transactionOrReadTime); + if (!result.result) { + throw new Error('No QuerySnapshot result'); + } + return result as QuerySnapshotResponse< + QuerySnapshot + >; + } + + _getResponse( + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + explainOptions?: firestore.ExplainOptions, + ): Promise>> { + return this._queryUtil._getResponse( + this, + transactionOrReadTime, + true, + explainOptions, + ); + } + + /** + * Executes the query and streams the results as + * [QueryDocumentSnapshots]{@link QueryDocumentSnapshot}. + * + * @returns {Stream.} A stream of + * QueryDocumentSnapshots. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * let count = 0; + * + * query.stream().on('data', (documentSnapshot) => { + * console.log(`Found document with name '${documentSnapshot.id}'`); + * ++count; + * }).on('end', () => { + * console.log(`Total count is ${count}`); + * }); + * ``` + */ + stream(): NodeJS.ReadableStream { + return this._queryUtil.stream(this); + } + + /** + * Executes the query and streams the results as the following object: + * {document?: DocumentSnapshot, metrics?: ExplainMetrics} + * + * The stream surfaces documents one at a time as they are received from the + * server, and at the end, it will surface the metrics associated with + * executing the query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * let count = 0; + * + * query.explainStream({analyze: true}).on('data', (data) => { + * if (data.document) { + * // Use data.document which is a DocumentSnapshot instance. + * console.log(`Found document with name '${data.document.id}'`); + * ++count; + * } + * if (data.metrics) { + * // Use data.metrics which is an ExplainMetrics instance. + * } + * }).on('end', () => { + * console.log(`Received ${count} documents.`); + * }); + * ``` + */ + explainStream( + explainOptions?: firestore.ExplainOptions, + ): NodeJS.ReadableStream { + if (explainOptions === undefined) { + explainOptions = {}; + } + if (this._queryOptions.limitType === LimitType.Last) { + throw new Error( + 'Query results for queries that include limitToLast() ' + + 'constraints cannot be streamed. Use Query.explain() instead.', + ); + } + + const responseStream = this._stream(undefined, explainOptions); + const transform = new Transform({ + objectMode: true, + transform( + chunk: QueryStreamElement, + encoding, + callback, + ) { + if (chunk.document || chunk.explainMetrics) { + callback(undefined, { + document: chunk.document, + metrics: chunk.explainMetrics, + }); + } + }, + }); + responseStream.pipe(transform); + responseStream.on('error', e => transform.destroy(e)); + return transform; + } + + /** + * Converts a QueryCursor to its proto representation. + * + * @param cursor The original cursor value + * @private + * @internal + */ + private toCursor(cursor: QueryCursor | undefined): api.ICursor | undefined { + if (cursor) { + return cursor.before + ? {before: true, values: cursor.values} + : {values: cursor.values}; + } + + return undefined; + } + + /** + * Internal method for serializing a query to its RunQuery proto + * representation with an optional transaction id or read time. + * + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + * @param explainOptions Options to use for explaining the query (if any). + * @private + * @internal + * @returns Serialized JSON for the query. + */ + toProto( + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + explainOptions?: firestore.ExplainOptions, + ): api.IRunQueryRequest { + const projectId = this.firestore.projectId; + const databaseId = this.firestore.databaseId; + const parentPath = this._queryOptions.parentPath.toQualifiedResourcePath( + projectId, + databaseId, + ); + + const structuredQuery = this.toStructuredQuery(); + + // For limitToLast queries, the structured query has to be translated to a version with + // reversed ordered, and flipped startAt/endAt to work properly. + if (this._queryOptions.limitType === LimitType.Last) { + if (!this._queryOptions.hasFieldOrders()) { + throw new Error( + 'limitToLast() queries require specifying at least one orderBy() clause.', + ); + } + + structuredQuery.orderBy = this._queryOptions.fieldOrders!.map(order => { + // Flip the orderBy directions since we want the last results + const dir = + order.direction === 'DESCENDING' ? 'ASCENDING' : 'DESCENDING'; + return new FieldOrder(order.field, dir).toProto(); + }); + + // Swap the cursors to match the now-flipped query ordering. + structuredQuery.startAt = this._queryOptions.endAt + ? this.toCursor({ + values: this._queryOptions.endAt.values, + before: !this._queryOptions.endAt.before, + }) + : undefined; + structuredQuery.endAt = this._queryOptions.startAt + ? this.toCursor({ + values: this._queryOptions.startAt.values, + before: !this._queryOptions.startAt.before, + }) + : undefined; + } + + const runQueryRequest: api.IRunQueryRequest = { + parent: parentPath.formattedName, + structuredQuery, + }; + + if (transactionOrReadTime instanceof Uint8Array) { + runQueryRequest.transaction = transactionOrReadTime; + } else if (transactionOrReadTime instanceof Timestamp) { + runQueryRequest.readTime = transactionOrReadTime.toProto().timestampValue; + } else if (transactionOrReadTime) { + runQueryRequest.newTransaction = transactionOrReadTime; + } + + if (explainOptions) { + runQueryRequest.explainOptions = explainOptions; + } + + return runQueryRequest; + } + + /** + * Converts current Query to an IBundledQuery. + * + * @private + * @internal + */ + _toBundledQuery(): protos.firestore.IBundledQuery { + const projectId = this.firestore.projectId; + const databaseId = this.firestore.databaseId; + const parentPath = this._queryOptions.parentPath.toQualifiedResourcePath( + projectId, + databaseId, + ); + const structuredQuery = this.toStructuredQuery(); + + const bundledQuery: protos.firestore.IBundledQuery = { + parent: parentPath.formattedName, + structuredQuery, + }; + if (this._queryOptions.limitType === LimitType.First) { + bundledQuery.limitType = 'FIRST'; + } else if (this._queryOptions.limitType === LimitType.Last) { + bundledQuery.limitType = 'LAST'; + } + + return bundledQuery; + } + + private toStructuredQuery(): api.IStructuredQuery { + const structuredQuery: api.IStructuredQuery = { + from: [{}], + }; + + if (this._queryOptions.allDescendants) { + structuredQuery.from![0].allDescendants = true; + } + + // Kindless queries select all descendant documents, so we remove the + // collectionId field. + if (!this._queryOptions.kindless) { + structuredQuery.from![0].collectionId = this._queryOptions.collectionId; + } + + if (this._queryOptions.filters.length >= 1) { + structuredQuery.where = new CompositeFilterInternal( + this._queryOptions.filters, + 'AND', + ).toProto(); + } + + if (this._queryOptions.hasFieldOrders()) { + structuredQuery.orderBy = this._queryOptions.fieldOrders.map(o => + o.toProto(), + ); + } + + structuredQuery.startAt = this.toCursor(this._queryOptions.startAt); + structuredQuery.endAt = this.toCursor(this._queryOptions.endAt); + + if (this._queryOptions.limit) { + structuredQuery.limit = {value: this._queryOptions.limit}; + } + + structuredQuery.offset = this._queryOptions.offset; + structuredQuery.select = this._queryOptions.projection; + + return structuredQuery; + } + + /** + * @internal + * @private + * This method exists solely to maintain backward compatability. + */ + _isPermanentRpcError(err: GoogleError, methodName: string): boolean { + return this._queryUtil._isPermanentRpcError(err, methodName); + } + + /** + * @internal + * @private + * This method exists solely to maintain backward compatability. + */ + _hasRetryTimedOut(methodName: string, startTime: number): boolean { + return this._queryUtil._hasRetryTimedOut(methodName, startTime); + } + + /** + * Internal streaming method that accepts an optional transaction ID. + * + * BEWARE: If `transactionOrReadTime` is `ITransactionOptions`, then the first + * response in the stream will be a transaction response. + * + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + * @param explainOptions Options to use for explaining the query (if any). + * @private + * @internal + * @returns A stream of document results, optionally preceded by a transaction response. + */ + _stream( + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + explainOptions?: firestore.ExplainOptions, + ): NodeJS.ReadableStream { + return this._queryUtil._stream( + this, + transactionOrReadTime, + true, + explainOptions, + ); + } + + /** + * Attaches a listener for QuerySnapshot events. + * + * @param {querySnapshotCallback} onNext A callback to be called every time + * a new [QuerySnapshot]{@link QuerySnapshot} is available. + * @param {errorCallback=} onError A callback to be called if the listen + * fails or is cancelled. No further callbacks will occur. + * + * @returns {function()} An unsubscribe function that can be called to cancel + * the snapshot listener. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * let unsubscribe = query.onSnapshot(querySnapshot => { + * console.log(`Received query snapshot of size ${querySnapshot.size}`); + * }, err => { + * console.log(`Encountered error: ${err}`); + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + onSnapshot( + onNext: (snapshot: QuerySnapshot) => void, + onError?: (error: Error) => void, + ): () => void { + validateFunction('onNext', onNext); + validateFunction('onError', onError, {optional: true}); + + const watch: QueryWatch = + new (require('../watch').QueryWatch)( + this.firestore, + this, + this._queryOptions.converter, + ); + + return watch.onSnapshot((readTime, size, docs, changes) => { + onNext(new QuerySnapshot(this, readTime, size, docs, changes)); + }, onError || console.error); + } + + /** + * Returns a function that can be used to sort QueryDocumentSnapshots + * according to the sort criteria of this query. + * + * @private + * @internal + */ + comparator(): ( + s1: QueryDocumentSnapshot, + s2: QueryDocumentSnapshot, + ) => number { + return (doc1, doc2) => { + // Add implicit sorting by name, using the last specified direction. + const lastDirection = this._queryOptions.hasFieldOrders() + ? this._queryOptions.fieldOrders[ + this._queryOptions.fieldOrders.length - 1 + ].direction + : 'ASCENDING'; + const orderBys = this._queryOptions.fieldOrders.concat( + new FieldOrder(FieldPath.documentId(), lastDirection), + ); + + for (const orderBy of orderBys) { + let comp; + if (FieldPath.documentId().isEqual(orderBy.field)) { + comp = doc1.ref._path.compareTo(doc2.ref._path); + } else { + const v1 = doc1.protoField(orderBy.field); + const v2 = doc2.protoField(orderBy.field); + if (v1 === undefined || v2 === undefined) { + throw new Error( + 'Trying to compare documents on fields that ' + + "don't exist. Please include the fields you are ordering on " + + 'in your select() call.', + ); + } + comp = compare(v1, v2); + } + + if (comp !== 0) { + const direction = orderBy.direction === 'ASCENDING' ? 1 : -1; + return direction * comp; + } + } + + return 0; + }; + } + + withConverter< + NewAppModelType, + NewDbModelType extends firestore.DocumentData = firestore.DocumentData, + >( + converter: firestore.FirestoreDataConverter< + NewAppModelType, + NewDbModelType + > | null, + ): Query; + /** + * Applies a custom data converter to this Query, allowing you to use your + * own custom model objects with Firestore. When you call get() on the + * returned Query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * Passing in `null` as the converter parameter removes the current + * converter. + * + * @example + * ``` + * class Post { + * constructor(readonly title: string, readonly author: string) {} + * + * toString(): string { + * return this.title + ', by ' + this.author; + * } + * } + * + * const postConverter = { + * toFirestore(post: Post): FirebaseFirestore.DocumentData { + * return {title: post.title, author: post.author}; + * }, + * fromFirestore( + * snapshot: FirebaseFirestore.QueryDocumentSnapshot + * ): Post { + * const data = snapshot.data(); + * return new Post(data.title, data.author); + * } + * }; + * + * const postSnap = await Firestore() + * .collection('posts') + * .withConverter(postConverter) + * .doc().get(); + * const post = postSnap.data(); + * if (post !== undefined) { + * post.title; // string + * post.toString(); // Should be defined + * post.someNonExistentProperty; // TS error + * } + * + * ``` + * @param {FirestoreDataConverter | null} converter Converts objects to and + * from Firestore. Passing in `null` removes the current converter. + * @returns A Query that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends firestore.DocumentData = firestore.DocumentData, + >( + converter: firestore.FirestoreDataConverter< + NewAppModelType, + NewDbModelType + > | null, + ): Query { + return new Query( + this.firestore, + this._queryOptions.withConverter(converter ?? defaultConverter()), + ); + } + + /** + * Construct the resulting snapshot for this query with given documents. + * + * @private + * @internal + */ + _createSnapshot( + readTime: Timestamp, + size: number, + docs: () => Array>, + changes: () => Array>, + ): QuerySnapshot { + return new QuerySnapshot( + this, + readTime, + size, + docs, + changes, + ); + } +} diff --git a/handwritten/firestore/dev/src/reference/types.ts b/handwritten/firestore/dev/src/reference/types.ts new file mode 100644 index 00000000000..884eb8bc2be --- /dev/null +++ b/handwritten/firestore/dev/src/reference/types.ts @@ -0,0 +1,97 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as protos from '../../protos/firestore_v1_proto_api'; +import {PipelineResult} from '../pipelines'; +import api = protos.google.firestore.v1; + +import {Timestamp} from '../timestamp'; +import {ExplainMetrics} from '../query-profile'; +import {QueryDocumentSnapshot} from '../document'; + +import * as firestore from '@google-cloud/firestore'; +import {ExplainStats} from '../pipelines/pipelines'; + +export interface QueryStreamElement< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> { + transaction?: Uint8Array; + readTime?: Timestamp; + explainMetrics?: ExplainMetrics; + document?: QueryDocumentSnapshot; +} + +export interface QueryResponse { + transaction?: Uint8Array; + explainMetrics?: ExplainMetrics; + result?: TSnapshot; +} + +export interface QuerySnapshotResponse + extends QueryResponse { + result: TSnapshot; +} + +/** Internal representation of a query cursor before serialization. */ +export interface QueryCursor { + before: boolean; + values: api.IValue[]; +} + +/*! + * Denotes whether a provided limit is applied to the beginning or the end of + * the result set. + */ +export enum LimitType { + First, + Last, +} + +export interface PipelineStreamElement { + transaction?: Uint8Array; + executionTime?: Timestamp; + explainStats?: ExplainStats; + result?: PipelineResult; +} + +export interface PipelineResponse { + transaction?: Uint8Array; + executionTime?: Timestamp; + result?: Array; + explainStats?: ExplainStats; +} + +/** + * onSnapshot() callback that receives a QuerySnapshot. + * + * @callback querySnapshotCallback + * @param {QuerySnapshot} snapshot A query snapshot. + */ + +/** + * onSnapshot() callback that receives a DocumentSnapshot. + * + * @callback documentSnapshotCallback + * @param {DocumentSnapshot} snapshot A document snapshot. + */ + +/** + * onSnapshot() callback that receives an error. + * + * @callback errorCallback + * @param {Error} err An error from a listen. + */ diff --git a/handwritten/firestore/dev/src/reference/vector-query-options.ts b/handwritten/firestore/dev/src/reference/vector-query-options.ts new file mode 100644 index 00000000000..7aa1a982346 --- /dev/null +++ b/handwritten/firestore/dev/src/reference/vector-query-options.ts @@ -0,0 +1,61 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; + +/** + * Specifies the behavior of the {@link VectorQuery} generated by a call to {@link Query.findNearest:VectorQueryOptions}. + */ +export interface VectorQueryOptions { + /** + * A string or {@link FieldPath} specifying the vector field to search on. + */ + vectorField: string | firestore.FieldPath; + + /** + * The {@link VectorValue} used to measure the distance from `vectorField` values in the documents. + */ + queryVector: firestore.VectorValue | Array; + + /** + * Specifies the upper bound of documents to return, must be a positive integer with a maximum value of 1000. + */ + limit: number; + + /** + * Specifies what type of distance is calculated when performing the query. + */ + distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; + + /** + * Optionally specifies the name of a field that will be set on each returned DocumentSnapshot, + * which will contain the computed distance for the document. + */ + distanceResultField?: string | firestore.FieldPath; + + /** + * Specifies a threshold for which no less similar documents will be returned. The behavior + * of the specified `distanceMeasure` will affect the meaning of the distance threshold. + * + * - For `distanceMeasure: "EUCLIDEAN"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE euclidean_distance <= distanceThreshold + * - For `distanceMeasure: "COSINE"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE cosine_distance <= distanceThreshold + * - For `distanceMeasure: "DOT_PRODUCT"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE dot_product_distance >= distanceThreshold + */ + distanceThreshold?: number; +} diff --git a/handwritten/firestore/dev/src/reference/vector-query-snapshot.ts b/handwritten/firestore/dev/src/reference/vector-query-snapshot.ts new file mode 100644 index 00000000000..fda124374b9 --- /dev/null +++ b/handwritten/firestore/dev/src/reference/vector-query-snapshot.ts @@ -0,0 +1,290 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; +import {QueryDocumentSnapshot} from '../document'; +import {DocumentChange} from '../document-change'; +import {Timestamp} from '../timestamp'; +import {validateFunction} from '../validate'; +import {isArrayEqual} from '../util'; +import {VectorQuery} from './vector-query'; + +/** + * A `VectorQuerySnapshot` contains zero or more `QueryDocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export class VectorQuerySnapshot< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> implements firestore.VectorQuerySnapshot +{ + private _materializedDocs: Array< + QueryDocumentSnapshot + > | null = null; + private _materializedChanges: Array< + DocumentChange + > | null = null; + private _docs: + | (() => Array>) + | null = null; + private _changes: + | (() => Array>) + | null = null; + + /** + * @private + * @internal + * + * @param _query - The originating query. + * @param _readTime - The time when this query snapshot was obtained. + * @param _size - The number of documents in the result set. + * @param docs - A callback returning a sorted array of documents matching + * this query + * @param changes - A callback returning a sorted array of document change + * events for this snapshot. + */ + constructor( + private readonly _query: VectorQuery, + private readonly _readTime: Timestamp, + private readonly _size: number, + docs: () => Array>, + changes: () => Array>, + ) { + this._docs = docs; + this._changes = changes; + } + + /** + * The `VectorQuery` on which you called get() in order to get this + * `VectorQuerySnapshot`. + * + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}) + * .get().then(querySnapshot => { + * console.log(`Returned first batch of results`); + * let query = querySnapshot.query; + * return query.offset(10).get(); + * }).then(() => { + * console.log(`Returned second batch of results`); + * }); + * ``` + */ + get query(): VectorQuery { + return this._query; + } + + /** + * An array of all the documents in this `VectorQuerySnapshot`. + * + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then(querySnapshot => { + * let docs = querySnapshot.docs; + * for (let doc of docs) { + * console.log(`Document found at path: ${doc.ref.path}`); + * } + * }); + * ``` + */ + get docs(): Array> { + if (this._materializedDocs) { + return this._materializedDocs!; + } + this._materializedDocs = this._docs!(); + this._docs = null; + return this._materializedDocs!; + } + + /** + * `true` if there are no documents in the `VectorQuerySnapshot`. + * + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then(querySnapshot => { + * if (querySnapshot.empty) { + * console.log('No documents found.'); + * } + * }); + * ``` + */ + get empty(): boolean { + return this._size === 0; + } + + /** + * The number of documents in the `VectorQuerySnapshot`. + * + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then(querySnapshot => { + * console.log(`Found ${querySnapshot.size} documents.`); + * }); + * ``` + */ + get size(): number { + return this._size; + } + + /** + * The time this `VectorQuerySnapshot` was obtained. + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then((querySnapshot) => { + * let readTime = querySnapshot.readTime; + * console.log(`Query results returned at '${readTime.toDate()}'`); + * }); + * ``` + */ + get readTime(): Timestamp { + return this._readTime; + } + + /** + * Returns an array of the documents changes since the last snapshot. If + * this is the first snapshot, all documents will be in the list as added + * changes. + * + * @returns An array of the documents changes since the last snapshot. + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then(querySnapshot => { + * let changes = querySnapshot.docChanges(); + * for (let change of changes) { + * console.log(`A document was ${change.type}.`); + * } + * }); + * ``` + */ + docChanges(): Array> { + if (this._materializedChanges) { + return this._materializedChanges!; + } + this._materializedChanges = this._changes!(); + this._changes = null; + return this._materializedChanges!; + } + + /** + * Enumerates all of the documents in the `VectorQuerySnapshot`. This is a convenience + * method for running the same callback on each {@link QueryDocumentSnapshot} + * that is returned. + * + * @param callback - A callback to be called with a + * {@link QueryDocumentSnapshot} for each document in + * the snapshot. + * @param thisArg - The `this` binding for the callback.. + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Document found at path: ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + forEach( + callback: ( + result: firestore.QueryDocumentSnapshot, + ) => void, + thisArg?: unknown, + ): void { + validateFunction('callback', callback); + + for (const doc of this.docs) { + callback.call(thisArg, doc); + } + } + + /** + * Returns true if the document data in this `VectorQuerySnapshot` is equal to the + * provided value. + * + * @param other - The value to compare against. + * @returns true if this `VectorQuerySnapshot` is equal to the provided + * value. + */ + isEqual( + other: firestore.VectorQuerySnapshot, + ): boolean { + // Since the read time is different on every query read, we explicitly + // ignore all metadata in this comparison. + + if (this === other) { + return true; + } + + if (!(other instanceof VectorQuerySnapshot)) { + return false; + } + + if (this._size !== other._size) { + return false; + } + + if (!this._query.isEqual(other._query)) { + return false; + } + + if (this._materializedDocs && !this._materializedChanges) { + // If we have only materialized the documents, we compare them first. + return ( + isArrayEqual(this.docs, other.docs) && + isArrayEqual(this.docChanges(), other.docChanges()) + ); + } + + // Otherwise, we compare the changes first as we expect there to be fewer. + return ( + isArrayEqual(this.docChanges(), other.docChanges()) && + isArrayEqual(this.docs, other.docs) + ); + } +} diff --git a/handwritten/firestore/dev/src/reference/vector-query.ts b/handwritten/firestore/dev/src/reference/vector-query.ts new file mode 100644 index 00000000000..d702d9423aa --- /dev/null +++ b/handwritten/firestore/dev/src/reference/vector-query.ts @@ -0,0 +1,302 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import * as firestore from '@google-cloud/firestore'; +import {field} from '../pipelines'; +import {Pipeline} from '../pipelines'; + +import {Timestamp} from '../timestamp'; +import {VectorValue} from '../field-value'; +import {FieldPath} from '../path'; +import {QueryDocumentSnapshot} from '../document'; +import {DocumentChange} from '../document-change'; +import {isPrimitiveArrayEqual} from '../util'; +import {QueryUtil} from './query-util'; +import {Query} from './query'; +import {VectorQueryOptions} from './vector-query-options'; +import {VectorQuerySnapshot} from './vector-query-snapshot'; +import {ExplainResults} from '../query-profile'; +import {QueryResponse} from './types'; + +/** + * A query that finds the documents whose vector fields are closest to a certain query vector. + * Create an instance of `VectorQuery` with {@link Query.findNearest:VectorQueryOptions}. + */ +export class VectorQuery< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> implements firestore.VectorQuery +{ + /** + * @internal + * @private + **/ + readonly _queryUtil: QueryUtil< + AppModelType, + DbModelType, + VectorQuery + >; + + /** + * @private + * @internal + */ + constructor( + private readonly _query: Query, + private readonly _options: VectorQueryOptions, + ) { + this._queryUtil = new QueryUtil< + AppModelType, + DbModelType, + VectorQuery + >(_query._firestore, _query._queryOptions, _query._serializer); + } + + /** The query whose results participants in the vector search. Filtering + * performed by the query will apply before the vector search. + **/ + get query(): Query { + return this._query; + } + + /** + * @private + * @internal + */ + private get _rawVectorField(): string { + return typeof this._options.vectorField === 'string' + ? this._options.vectorField + : this._options.vectorField.toString(); + } + + /** + * @private + * @internal + */ + private get _rawDistanceResultField(): string | undefined { + if (typeof this._options.distanceResultField === 'undefined') return; + + return typeof this._options.distanceResultField === 'string' + ? this._options.distanceResultField + : this._options.distanceResultField.toString(); + } + + /** + * @private + * @internal + */ + private get _rawQueryVector(): Array { + return Array.isArray(this._options.queryVector) + ? this._options.queryVector + : this._options.queryVector.toArray(); + } + + /** + * Plans and optionally executes this vector search query. Returns a Promise that will be + * resolved with the planner information, statistics from the query execution (if any), + * and the query results (if any). + * + * @returns A Promise that will be resolved with the planner information, statistics + * from the query execution (if any), and the query results (if any). + */ + async explain( + options?: firestore.ExplainOptions, + ): Promise>> { + if (options === undefined) { + options = {}; + } + const {result, explainMetrics} = await this._getResponse(options); + if (!explainMetrics) { + throw new Error('No explain results'); + } + return new ExplainResults(explainMetrics, result || null); + } + + /** + * Executes this vector search query. + * + * @returns A promise that will be resolved with the results of the query. + */ + async get(): Promise> { + const {result} = await this._getResponse(); + if (!result) { + throw new Error('No VectorQuerySnapshot result'); + } + return result; + } + + /** + * @private + * @internal + */ + _pipeline(): Pipeline { + const options: firestore.Pipelines.FindNearestStageOptions = { + field: field(this._options.vectorField), + vectorValue: this._options.queryVector, + limit: this._options.limit, + distanceMeasure: this._options.distanceMeasure.toLowerCase() as + | 'cosine' + | 'euclidean' + | 'dot_product', + }; + return this.query + ._pipeline() + .where(field(this._options.vectorField).exists()) + .findNearest(options); + } + + _getResponse( + explainOptions?: firestore.ExplainOptions, + ): Promise>> { + return this._queryUtil._getResponse( + this, + /*transactionOrReadTime*/ undefined, + // VectorQuery cannot be retried with cursors as they do not support cursors yet. + /*retryWithCursor*/ false, + explainOptions, + ); + } + + /** + * Internal streaming method that accepts an optional transaction ID. + * + * @param transactionId - A transaction ID. + * @private + * @internal + * @returns A stream of document results. + */ + _stream(transactionId?: Uint8Array): NodeJS.ReadableStream { + return this._queryUtil._stream( + this, + transactionId, + /*retryWithCursor*/ false, + ); + } + + /** + * Internal method for serializing a query to its proto + * representation with an optional transaction id. + * + * @private + * @internal + * @returns Serialized JSON for the query. + */ + toProto( + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + explainOptions?: firestore.ExplainOptions, + ): api.IRunQueryRequest { + const queryProto = this._query.toProto(transactionOrReadTime); + + const queryVector = Array.isArray(this._options.queryVector) + ? new VectorValue(this._options.queryVector) + : (this._options.queryVector as VectorValue); + + queryProto.structuredQuery!.findNearest = { + limit: {value: this._options.limit}, + distanceMeasure: this._options.distanceMeasure, + vectorField: { + fieldPath: FieldPath.fromArgument(this._options.vectorField) + .formattedName, + }, + queryVector: queryVector._toProto(this._query._serializer), + distanceResultField: this._options?.distanceResultField + ? FieldPath.fromArgument(this._options.distanceResultField!) + .formattedName + : undefined, + distanceThreshold: this._options?.distanceThreshold + ? {value: this._options?.distanceThreshold} + : undefined, + }; + + if (explainOptions) { + queryProto.explainOptions = explainOptions; + } + + return queryProto; + } + + /** + * Construct the resulting vector snapshot for this query with given documents. + * + * @private + * @internal + */ + _createSnapshot( + readTime: Timestamp, + size: number, + docs: () => Array>, + changes: () => Array>, + ): VectorQuerySnapshot { + return new VectorQuerySnapshot( + this, + readTime, + size, + docs, + changes, + ); + } + + /** + * Construct a new vector query whose result will start after To support stream(). + * This now throws an exception because cursors are not supported from the backend for vector queries yet. + * + * @private + * @internal + * @returns Serialized JSON for the query. + */ + startAfter( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + ...fieldValuesOrDocumentSnapshot: Array + ): VectorQuery { + throw new Error( + 'Unimplemented: Vector query does not support cursors yet.', + ); + } + + /** + * Compares this object with the given object for equality. + * + * This object is considered "equal" to the other object if and only if + * `other` performs the same vector distance search as this `VectorQuery` and + * the underlying Query of `other` compares equal to that of this object + * using `Query.isEqual()`. + * + * @param other - The object to compare to this object for equality. + * @returns `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual(other: firestore.VectorQuery): boolean { + if (this === other) { + return true; + } + if (!(other instanceof VectorQuery)) { + return false; + } + if (!this.query.isEqual(other.query)) { + return false; + } + return ( + this._rawVectorField === other._rawVectorField && + isPrimitiveArrayEqual(this._rawQueryVector, other._rawQueryVector) && + this._options.limit === other._options.limit && + this._options.distanceMeasure === other._options.distanceMeasure && + this._options.distanceThreshold === other._options.distanceThreshold && + this._rawDistanceResultField === other._rawDistanceResultField + ); + } +} diff --git a/handwritten/firestore/dev/src/serializer.ts b/handwritten/firestore/dev/src/serializer.ts new file mode 100644 index 00000000000..d5164a8d571 --- /dev/null +++ b/handwritten/firestore/dev/src/serializer.ts @@ -0,0 +1,760 @@ +/*! + * Copyright 2019 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; + +import * as proto from '../protos/firestore_v1_proto_api'; + +import {DeleteTransform, FieldTransform, VectorValue} from './field-value'; +import {detectGoogleProtobufValueType, detectValueType} from './convert'; +import {GeoPoint} from './geo-point'; +import {DocumentReference, Firestore} from './index'; +import {FieldPath, ObjectValueFieldPath, QualifiedResourcePath} from './path'; +import {Timestamp} from './timestamp'; +import {ApiMapValue, ValidationOptions} from './types'; +import {forEach, isEmpty, isObject, isPlainObject} from './util'; +import {customObjectMessage, invalidArgumentMessage} from './validate'; +import {Pipeline} from './pipelines'; + +import api = proto.google.firestore.v1; +import { + RESERVED_MAP_KEY, + RESERVED_MAP_KEY_VECTOR_VALUE, + VECTOR_MAP_VECTORS_KEY, +} from './map-type'; +import {google} from '../protos/firestore_v1_proto_api'; +import IMapValue = google.firestore.v1.IMapValue; +import IValue = google.firestore.v1.IValue; +import Value = google.firestore.v1.Value; +import {isString} from './pipelines/pipeline-util'; + +/** + * The maximum depth of a Firestore object. + * + * @private + * @internal + */ +const MAX_DEPTH = 20; + +/** + * An interface for Firestore types that can be serialized to Protobuf. + * + * @private + * @internal + */ +export interface Serializable { + toProto(): api.IValue; +} + +/** + * Serializer that is used to convert between JavaScript types and their + * Firestore Protobuf representation. + * + * @private + * @internal + */ +export class Serializer { + private allowUndefined: boolean; + private createDocumentReference: (path: string) => DocumentReference; + private createInteger: (n: number | string) => number | BigInt; + + constructor(private firestore: Firestore) { + // Instead of storing the `firestore` object, we store just a reference to + // its `.doc()` method. This avoid a circular reference, which breaks + // JSON.stringify(). + this.createDocumentReference = path => firestore.doc(path); + this.createInteger = n => + firestore._settings.useBigInt ? BigInt(n) : Number(n); + this.allowUndefined = !!firestore._settings.ignoreUndefinedProperties; + } + + /** + * Encodes a JavaScript object into the Firestore 'Fields' representation. + * + * @private + * @internal + * @param obj The object to encode. + * @returns The Firestore 'Fields' representation + */ + encodeFields(obj: firestore.DocumentData): ApiMapValue { + const fields: ApiMapValue = {}; + + for (const prop of Object.keys(obj)) { + const val = this.encodeValue(obj[prop]); + + if (val) { + fields[prop] = val; + } + } + + return fields; + } + + /** + * Encodes a JavaScript value into the Firestore 'Value' representation. + * + * @private + * @internal + * @param val The object to encode + * @returns The Firestore Proto or null if we are deleting a field. + */ + encodeValue(val: FieldTransform | undefined): null; + encodeValue( + val: + | string + | boolean + | number + | bigint + | Date + | null + | Buffer + | Uint8Array + | VectorValue + | Map + | Pipeline, + ): api.IValue; + encodeValue(val: unknown): api.IValue | null; + encodeValue(val: unknown): api.IValue | null { + if (val instanceof FieldTransform) { + return null; + } + + if (typeof val === 'string') { + return { + stringValue: val as string, + }; + } + + if (typeof val === 'boolean') { + return { + booleanValue: val as boolean, + }; + } + + if (typeof val === 'number') { + const isNegativeZero = val === 0 && 1 / val === 1 / -0; + if (Number.isSafeInteger(val) && !isNegativeZero) { + return { + integerValue: val as number, + }; + } else { + return { + doubleValue: val as number, + }; + } + } + + if (typeof val === 'bigint') { + return { + integerValue: val.toString(), + }; + } + + if (val instanceof Date) { + const timestamp = Timestamp.fromDate(val); + return { + timestampValue: { + seconds: timestamp.seconds, + nanos: timestamp.nanoseconds, + }, + }; + } + + if (isMomentJsType(val)) { + const timestamp = Timestamp.fromDate(val.toDate()); + return { + timestampValue: { + seconds: timestamp.seconds, + nanos: timestamp.nanoseconds, + }, + }; + } + + if (val === null) { + return { + nullValue: 'NULL_VALUE', + }; + } + + if (val instanceof Buffer || val instanceof Uint8Array) { + return { + bytesValue: val, + }; + } + + if (val instanceof VectorValue) { + return val._toProto(this); + } + + if (val instanceof Pipeline) { + return { + pipelineValue: val._toProto(), + }; + } + + if (isObject(val)) { + const toProto = val['toProto']; + if (typeof toProto === 'function') { + return toProto.bind(val)(); + } + } + + if (isObject(val)) { + const _toProto = val['_toProto']; + if (typeof _toProto === 'function') { + return _toProto.bind(val)(this); + } + } + + if (Array.isArray(val)) { + const array: api.IValue = { + arrayValue: {}, + }; + + if (val.length > 0) { + array.arrayValue!.values = []; + for (let i = 0; i < val.length; ++i) { + const enc = this.encodeValue(val[i]); + if (enc) { + array.arrayValue!.values!.push(enc); + } + } + } + + return array; + } + + if (val instanceof Map) { + const map: api.IMapValue = {fields: {}}; + for (const [key, value] of val.entries()) { + if (typeof key !== 'string') { + throw new Error(`Cannot encode map with non-string key: ${key}`); + } + + map.fields![key] = this.encodeValue(value)!; + } + + return { + mapValue: map, + }; + } + + if (typeof val === 'object' && isPlainObject(val)) { + const map: api.IValue = { + mapValue: {}, + }; + + // If we encounter an empty object, we always need to send it to make sure + // the server creates a map entry. + if (!isEmpty(val)) { + map.mapValue!.fields = this.encodeFields(val); + if (isEmpty(map.mapValue!.fields!)) { + return null; + } + } + + return map; + } + + if (val === undefined && this.allowUndefined) { + return null; + } + + throw new Error(`Cannot encode value: ${val}`); + } + + encodeReference( + path: string | firestore.DocumentReference | firestore.CollectionReference, + ): api.IValue { + return { + referenceValue: isString(path) ? path : path.path, + }; + } + + /** + * @private + */ + encodeVector(rawVector: number[]): api.IValue { + // A Firestore Vector is a map with reserved key/value pairs. + return { + mapValue: { + fields: { + [RESERVED_MAP_KEY]: { + stringValue: RESERVED_MAP_KEY_VECTOR_VALUE, + }, + [VECTOR_MAP_VECTORS_KEY]: { + arrayValue: { + values: rawVector.map(value => { + return { + doubleValue: value, + }; + }), + }, + }, + }, + }, + }; + } + + /** + * Decodes a single Firestore 'Value' Protobuf. + * + * @private + * @internal + * @param proto A Firestore 'Value' Protobuf. + * @returns The converted JS type. + */ + decodeValue(proto: api.IValue): unknown { + const valueType = detectValueType(proto); + + switch (valueType) { + case 'stringValue': { + return proto.stringValue; + } + case 'booleanValue': { + return proto.booleanValue; + } + case 'integerValue': { + return this.createInteger(proto.integerValue!); + } + case 'doubleValue': { + return proto.doubleValue; + } + case 'timestampValue': { + return Timestamp.fromProto(proto.timestampValue!); + } + case 'referenceValue': { + const resourcePath = QualifiedResourcePath.fromSlashSeparatedString( + proto.referenceValue!, + ); + if (resourcePath.isDocument) { + return this.createDocumentReference(resourcePath.relativeName); + } else { + throw new Error( + `The SDK does not currently support decoding referenceValues for collections or partitions. Actual path value: '${proto.referenceValue!}'`, + ); + } + } + case 'arrayValue': { + const array: unknown[] = []; + if (Array.isArray(proto.arrayValue!.values)) { + for (const value of proto.arrayValue!.values!) { + array.push(this.decodeValue(value)); + } + } + return array; + } + case 'nullValue': { + return null; + } + case 'mapValue': { + const fields = proto.mapValue!.fields; + if (fields) { + const obj: firestore.DocumentData = {}; + for (const prop of Object.keys(fields)) { + obj[prop] = this.decodeValue(fields[prop]); + } + return obj; + } else { + return {}; + } + } + case 'vectorValue': { + const fields = proto.mapValue!.fields!; + return VectorValue._fromProto(fields[VECTOR_MAP_VECTORS_KEY]); + } + case 'geoPointValue': { + return GeoPoint.fromProto(proto.geoPointValue!); + } + case 'bytesValue': { + return proto.bytesValue; + } + default: { + throw new Error( + 'Cannot decode type from Firestore Value: ' + JSON.stringify(proto), + ); + } + } + } + + /** + * Decodes a google.protobuf.Value + * + * @private + * @internal + * @param proto A Google Protobuf 'Value'. + * @returns The converted JS type. + */ + decodeGoogleProtobufValue(proto: proto.google.protobuf.IValue): unknown { + switch (detectGoogleProtobufValueType(proto)) { + case 'nullValue': { + return null; + } + case 'numberValue': { + return proto.numberValue; + } + case 'stringValue': { + return proto.stringValue; + } + case 'boolValue': { + return proto.boolValue; + } + case 'listValue': { + return this.decodeGoogleProtobufList(proto.listValue); + } + case 'structValue': { + return this.decodeGoogleProtobufStruct(proto.structValue); + } + default: { + throw new Error( + 'Cannot decode type from google.protobuf.Value: ' + + JSON.stringify(proto), + ); + } + } + } + + /** + * Decodes a google.protobuf.ListValue + * + * @private + * @internal + * @param proto A Google Protobuf 'ListValue'. + * @returns The converted JS type. + */ + decodeGoogleProtobufList( + proto: proto.google.protobuf.IListValue | null | undefined, + ): unknown[] { + const result: unknown[] = []; + if (proto && proto.values && Array.isArray(proto.values)) { + for (const value of proto.values) { + result.push(this.decodeGoogleProtobufValue(value)); + } + } + return result; + } + + /** + * Decodes a google.protobuf.Struct + * + * @private + * @internal + * @param proto A Google Protobuf 'Struct'. + * @returns The converted JS type. + */ + decodeGoogleProtobufStruct( + proto: proto.google.protobuf.IStruct | null | undefined, + ): Record { + const result: Record = {}; + if (proto && proto.fields) { + for (const prop of Object.keys(proto.fields)) { + result[prop] = this.decodeGoogleProtobufValue(proto.fields[prop]); + } + } + return result; + } +} + +/** + * Validates a JavaScript value for usage as a Firestore value. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value JavaScript value to validate. + * @param desc A description of the expected type. + * @param path The field path to validate. + * @param options Validation options + * @param level The current depth of the traversal. This is used to decide + * whether undefined values or deletes are allowed. + * @param inArray Whether we are inside an array. + * @throws when the object is invalid. + */ +export function validateUserInput( + arg: string | number, + value: unknown, + desc: string, + options: ValidationOptions, + path?: FieldPath, + level?: number, + inArray?: boolean, +): void { + if (path && path.size - 1 > MAX_DEPTH) { + throw new Error( + `${invalidArgumentMessage( + arg, + desc, + )} Input object is deeper than ${MAX_DEPTH} levels or contains a cycle.`, + ); + } + + level = level || 0; + inArray = inArray || false; + + const fieldPathMessage = path ? ` (found in field "${path}")` : ''; + + if (Array.isArray(value)) { + for (let i = 0; i < value.length; ++i) { + validateUserInput( + arg, + value[i]!, + desc, + options, + path ? path.append(String(i)) : new FieldPath(String(i)), + level + 1, + /* inArray= */ true, + ); + } + } else if (isPlainObject(value)) { + for (const prop of Object.keys(value)) { + validateUserInput( + arg, + value[prop]!, + desc, + options, + path ? path.append(new FieldPath(prop)) : new FieldPath(prop), + level + 1, + inArray, + ); + } + } else if (value === undefined) { + if (options.allowUndefined && level === 0) { + throw new Error( + `${invalidArgumentMessage( + arg, + desc, + )} "undefined" values are only ignored inside of objects.`, + ); + } else if (!options.allowUndefined) { + throw new Error( + `${invalidArgumentMessage( + arg, + desc, + )} Cannot use "undefined" as a Firestore value${fieldPathMessage}. ` + + 'If you want to ignore undefined values, enable `ignoreUndefinedProperties`.', + ); + } + } else if (value instanceof VectorValue) { + // OK + } else if (value instanceof DeleteTransform) { + if (inArray) { + throw new Error( + `${invalidArgumentMessage(arg, desc)} ${ + value.methodName + }() cannot be used inside of an array${fieldPathMessage}.`, + ); + } else if (options.allowDeletes === 'none') { + throw new Error( + `${invalidArgumentMessage(arg, desc)} ${ + value.methodName + }() must appear at the top-level and can only be used in update() ` + + `or set() with {merge:true}${fieldPathMessage}.`, + ); + } else if (options.allowDeletes === 'root') { + if (level === 0) { + // Ok (update() with UpdateData). + } else if (level === 1 && path?.size === 1) { + // Ok (update with varargs). + } else { + throw new Error( + `${invalidArgumentMessage(arg, desc)} ${ + value.methodName + }() must appear at the top-level and can only be used in update() ` + + `or set() with {merge:true}${fieldPathMessage}.`, + ); + } + } + } else if (value instanceof FieldTransform) { + if (inArray) { + throw new Error( + `${invalidArgumentMessage(arg, desc)} ${ + value.methodName + }() cannot be used inside of an array${fieldPathMessage}.`, + ); + } else if (!options.allowTransforms) { + throw new Error( + `${invalidArgumentMessage(arg, desc)} ${ + value.methodName + }() can only be used in set(), create() or update()${fieldPathMessage}.`, + ); + } + } else if (value instanceof FieldPath) { + throw new Error( + `${invalidArgumentMessage( + arg, + desc, + )} Cannot use object of type "FieldPath" as a Firestore value${fieldPathMessage}.`, + ); + } else if (value instanceof DocumentReference) { + // Ok. + } else if (value instanceof GeoPoint) { + // Ok. + } else if (value instanceof Timestamp || value instanceof Date) { + // Ok. + } else if (isMomentJsType(value)) { + // Ok. + } else if (value instanceof Buffer || value instanceof Uint8Array) { + // Ok. + } else if (value === null) { + // Ok. + } else if (isProtoValueSerializable(value)) { + // Ok. + } else if (typeof value === 'object') { + throw new Error(customObjectMessage(arg, value, path)); + } +} + +/** + * Returns true if value is a MomentJs date object. + * @private + * @internal + */ +function isMomentJsType(value: unknown): value is {toDate(): Date} { + return ( + typeof value === 'object' && + value !== null && + value.constructor && + value.constructor.name === 'Moment' && + typeof (value as {toDate: unknown}).toDate === 'function' + ); +} + +export function isProtoValueSerializable( + value: unknown, +): value is ProtoValueSerializable { + return ( + !!value && + typeof (value as ProtoValueSerializable)._toProto === 'function' && + (value as ProtoValueSerializable)._protoValueType === 'ProtoValue' + ); +} + +export interface ProtoSerializable { + _toProto(serializer: Serializer): ProtoType; +} + +export interface ProtoValueSerializable extends ProtoSerializable { + // Supports runtime identification of the ProtoSerializable type. + _protoValueType: 'ProtoValue'; +} + +export interface HasUserData { + _validateUserData(ignoreUndefinedProperties: boolean): void; +} + +export function hasUserData(value: unknown): value is HasUserData { + return typeof (value as HasUserData)._validateUserData === 'function'; +} + +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields. + */ +export class ObjectValue { + constructor(readonly value: {mapValue: IMapValue}) {} + + static empty(): ObjectValue { + return new ObjectValue({mapValue: {}}); + } + + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path: ObjectValueFieldPath, value: IValue): void { + const fieldsMap = this.getFieldsMap(path.popLast()); + fieldsMap[path.lastSegment()] = Value.fromObject(value).toJSON(); + } + + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data: Map): void { + let parent = new ObjectValueFieldPath(); + + let upserts: {[key: string]: IValue} = {}; + let deletes: string[] = []; + + data.forEach((value, path) => { + if (!parent.isImmediateParentOf(path)) { + // Insert the accumulated changes at this parent location + const fieldsMap = this.getFieldsMap(parent); + this.applyChanges(fieldsMap, upserts, deletes); + upserts = {}; + deletes = []; + parent = path.popLast(); + } + + if (value) { + upserts[path.lastSegment()] = Value.fromObject(value).toJSON(); + } else { + deletes.push(path.lastSegment()); + } + }); + + const fieldsMap = this.getFieldsMap(parent); + this.applyChanges(fieldsMap, upserts, deletes); + } + + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + private getFieldsMap(path: ObjectValueFieldPath): Record { + let current = this.value; + + if (!current.mapValue!.fields) { + current.mapValue = {fields: {}}; + } + + for (let i = 0; i < path.size; ++i) { + let next = current.mapValue!.fields![path.get(i)]; + if (!isMapValue(next) || !next.mapValue.fields) { + next = {mapValue: {fields: {}}}; + current.mapValue!.fields![path.get(i)] = next; + } + current = next as {mapValue: IMapValue}; + } + + return current.mapValue!.fields!; + } + + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + private applyChanges( + fieldsMap: Record, + inserts: {[key: string]: IValue}, + deletes: string[], + ): void { + forEach(inserts, (key, val) => (fieldsMap[key] = val)); + for (const field of deletes) { + delete fieldsMap[field]; + } + } +} + +/** Returns true if `value` is a MapValue. */ +export function isMapValue( + value?: IValue | null, +): value is {mapValue: IMapValue} { + return !!value && 'mapValue' in value; +} diff --git a/handwritten/firestore/dev/src/status-code.ts b/handwritten/firestore/dev/src/status-code.ts new file mode 100644 index 00000000000..a93837d2de6 --- /dev/null +++ b/handwritten/firestore/dev/src/status-code.ts @@ -0,0 +1,39 @@ +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Internal copy of GRPC status code. Copied to prevent loading of google-gax + * at SDK startup. + */ +export const enum StatusCode { + OK = 0, + CANCELLED = 1, + UNKNOWN = 2, + INVALID_ARGUMENT = 3, + DEADLINE_EXCEEDED = 4, + NOT_FOUND = 5, + ALREADY_EXISTS = 6, + PERMISSION_DENIED = 7, + RESOURCE_EXHAUSTED = 8, + FAILED_PRECONDITION = 9, + ABORTED = 10, + OUT_OF_RANGE = 11, + UNIMPLEMENTED = 12, + INTERNAL = 13, + UNAVAILABLE = 14, + DATA_LOSS = 15, + UNAUTHENTICATED = 16, +} diff --git a/handwritten/firestore/dev/src/telemetry/disabled-trace-util.ts b/handwritten/firestore/dev/src/telemetry/disabled-trace-util.ts new file mode 100644 index 00000000000..dbd9c423d92 --- /dev/null +++ b/handwritten/firestore/dev/src/telemetry/disabled-trace-util.ts @@ -0,0 +1,46 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import {Attributes, TraceUtil} from './trace-util'; +import {Span} from './span'; + +/** + * @private + * @internal + */ +export class DisabledTraceUtil implements TraceUtil { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + startSpan(name: string): Span { + return new Span(); + } + + startActiveSpan unknown>( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + name: string, + fn: F, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + attributes?: Attributes, + ): ReturnType { + const emptySpan = new Span(); + return fn(emptySpan) as ReturnType; + } + + currentSpan(): Span { + return new Span(); + } + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + recordProjectIdAndResourceName(projectId: string, databaseId: string): void {} +} diff --git a/handwritten/firestore/dev/src/telemetry/enabled-trace-util.ts b/handwritten/firestore/dev/src/telemetry/enabled-trace-util.ts new file mode 100644 index 00000000000..a74eeb65d0d --- /dev/null +++ b/handwritten/firestore/dev/src/telemetry/enabled-trace-util.ts @@ -0,0 +1,227 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {Settings} from '@google-cloud/firestore'; + +import { + context, + SpanStatusCode, + trace, + Tracer, + Span as OpenTelemetrySpan, + TracerProvider, +} from '@opentelemetry/api'; + +import {Span} from './span'; +import { + ATTRIBUTE_GCP_RESOURCE_NAME, + ATTRIBUTE_SETTINGS_PREFIX, + Attributes, + TraceUtil, +} from './trace-util'; + +import {interfaces} from '../v1/firestore_client_config.json'; +import {FirestoreClient} from '../v1'; +import {DEFAULT_DATABASE_ID} from '../path'; +import {DEFAULT_MAX_IDLE_CHANNELS} from '../index'; +const serviceConfig = interfaces['google.firestore.v1.Firestore']; + +/** + * @private + * @internal + */ +export class EnabledTraceUtil implements TraceUtil { + private tracer: Tracer; + private settingsAttributes: Attributes; + + // Visible for testing + tracerProvider: TracerProvider; + + constructor(settings: Settings) { + let provider: TracerProvider | undefined = + settings.openTelemetry?.tracerProvider; + + // If a TracerProvider has not been given to us, we try to use the global one. + if (!provider) { + const {trace} = require('@opentelemetry/api'); + provider = trace.getTracerProvider(); + } + + // At this point provider is guaranteed to be defined because + // `trace.getTracerProvider()` does not return null or undefined. + this.tracerProvider = provider!; + + const libVersion = require('../../../package.json').version; + const libName = require('../../../package.json').name; + try { + this.tracer = this.tracerProvider.getTracer(libName, libVersion); + } catch (e) { + throw new Error( + "The object provided for 'tracerProvider' does not conform to the TracerProvider interface.", + ); + } + + const databaseId: string = settings.databaseId || DEFAULT_DATABASE_ID; + this.settingsAttributes = {}; + this.settingsAttributes['otel.scope.name'] = libName; + this.settingsAttributes['otel.scope.version'] = libVersion; + + if (settings.projectId) { + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.project_id`] = + settings.projectId; + + this.settingsAttributes[ATTRIBUTE_GCP_RESOURCE_NAME] = + `//firestore.googleapis.com/projects/${settings.projectId}/databases/${databaseId}`; + } + + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.database_id`] = + databaseId; + + const host = + settings.servicePath ?? settings.host ?? 'firestore.googleapis.com'; + const port = settings.port ?? FirestoreClient.port; + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.host`] = + `${host}:${port}`; + + if (settings.preferRest !== undefined) { + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.prefer_REST`] = + settings.preferRest; + } + + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.max_idle_channels`] = + settings.maxIdleChannels ?? DEFAULT_MAX_IDLE_CHANNELS; + + const defaultRetrySettings = serviceConfig.retry_params.default; + const customRetrySettings = + settings.clientConfig?.interfaces?.['google.firestore.v1.Firestore']?.[ + 'retry_params' + ]?.['default']; + this.settingsAttributes[ + `${ATTRIBUTE_SETTINGS_PREFIX}.initial_retry_delay` + ] = this.millisToSecondString( + customRetrySettings?.initial_retry_delay_millis ?? + defaultRetrySettings.initial_retry_delay_millis, + ); + this.settingsAttributes[ + `${ATTRIBUTE_SETTINGS_PREFIX}.initial_rpc_timeout` + ] = this.millisToSecondString( + customRetrySettings?.initial_rpc_timeout_millis ?? + defaultRetrySettings.initial_rpc_timeout_millis, + ); + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.total_timeout`] = + this.millisToSecondString( + customRetrySettings?.total_timeout_millis ?? + defaultRetrySettings.total_timeout_millis, + ); + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.max_retry_delay`] = + this.millisToSecondString( + customRetrySettings?.max_retry_delay_millis ?? + defaultRetrySettings.max_retry_delay_millis, + ); + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.max_rpc_timeout`] = + this.millisToSecondString( + customRetrySettings?.max_rpc_timeout_millis ?? + defaultRetrySettings.max_rpc_timeout_millis, + ); + this.settingsAttributes[ + `${ATTRIBUTE_SETTINGS_PREFIX}.retry_delay_multiplier` + ] = + customRetrySettings?.retry_delay_multiplier.toString() ?? + defaultRetrySettings.retry_delay_multiplier.toString(); + this.settingsAttributes[ + `${ATTRIBUTE_SETTINGS_PREFIX}.rpc_timeout_multiplier` + ] = + customRetrySettings?.rpc_timeout_multiplier.toString() ?? + defaultRetrySettings.rpc_timeout_multiplier.toString(); + } + + recordProjectIdAndResourceName(projectId: string, databaseId: string): void { + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.project_id`] = + projectId; + this.settingsAttributes[ATTRIBUTE_GCP_RESOURCE_NAME] = + `//firestore.googleapis.com/projects/${projectId}/databases/${databaseId}`; + this.currentSpan().setAttributes(this.settingsAttributes); + } + + private millisToSecondString(millis: number): string { + return `${millis / 1000}s`; + } + + private endSpan(otelSpan: OpenTelemetrySpan, error: Error): void { + otelSpan.setStatus({ + code: SpanStatusCode.ERROR, + message: error.message, + }); + otelSpan.recordException(error); + otelSpan.end(); + } + + startActiveSpan unknown>( + name: string, + fn: F, + attributes?: Attributes, + ): ReturnType { + return this.tracer.startActiveSpan( + name, + { + attributes: attributes, + }, + (otelSpan: OpenTelemetrySpan) => { + this.addCommonAttributes(otelSpan); + + // Note that if `fn` returns a `Promise`, we want the otelSpan to end + // after the `Promise` has resolved, NOT after the `fn` has returned. + // Therefore, we should not use a `finally` clause to end the otelSpan. + try { + let result = fn(new Span(otelSpan)); + if (result instanceof Promise) { + result = result + .then(value => { + otelSpan.end(); + return value; + }) + .catch(error => { + this.endSpan(otelSpan, error); + // Returns a Promise.reject the same as the underlying function. + return Promise.reject(error); + }); + } else { + otelSpan.end(); + } + return result as ReturnType; + } catch (error) { + this.endSpan(otelSpan, error); + // Re-throw the exception to maintain normal error handling. + throw error; + } + }, + ); + } + + startSpan(name: string): Span { + const otelSpan = this.tracer.startSpan(name, undefined, context.active()); + this.addCommonAttributes(otelSpan); + return new Span(otelSpan); + } + + currentSpan(): Span { + return new Span(trace.getActiveSpan()); + } + + addCommonAttributes(otelSpan: OpenTelemetrySpan): void { + otelSpan.setAttributes(this.settingsAttributes); + } +} diff --git a/handwritten/firestore/dev/src/telemetry/span.ts b/handwritten/firestore/dev/src/telemetry/span.ts new file mode 100644 index 00000000000..c4ed1ed0af8 --- /dev/null +++ b/handwritten/firestore/dev/src/telemetry/span.ts @@ -0,0 +1,40 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {Span as OpenTelemetrySpan} from '@opentelemetry/api'; +import {Attributes} from './trace-util'; + +/** + * @private + * @internal + */ +export class Span { + constructor(private span?: OpenTelemetrySpan) {} + + end(): void { + this.span?.end(); + } + + addEvent(name: string, attributes?: Attributes): this { + this.span = this.span?.addEvent(name, attributes); + return this; + } + + setAttributes(attributes: Attributes): this { + this.span = this.span?.setAttributes(attributes); + return this; + } +} diff --git a/handwritten/firestore/dev/src/telemetry/trace-util.ts b/handwritten/firestore/dev/src/telemetry/trace-util.ts new file mode 100644 index 00000000000..9edbdc06c85 --- /dev/null +++ b/handwritten/firestore/dev/src/telemetry/trace-util.ts @@ -0,0 +1,95 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {Span} from './span'; + +/** + * @private + * @internal + */ +export interface Attributes { + [attributeKey: string]: AttributeValue | undefined; +} + +/** + * @private + * @internal + */ +export declare type AttributeValue = + | string + | number + | boolean + | Array + | Array + | Array; + +/** + * Span names for instrumented operations. + */ +export const SERVICE = 'google.firestore.v1.Firestore/'; +export const SPAN_NAME_BATCH_GET_DOCUMENTS = 'BatchGetDocuments'; +export const SPAN_NAME_RUN_QUERY = 'RunQuery'; +export const SPAN_NAME_RUN_AGGREGATION_QUERY = 'RunAggregationQuery'; +export const SPAN_NAME_DOC_REF_CREATE = 'DocumentReference.Create'; +export const SPAN_NAME_DOC_REF_SET = 'DocumentReference.Set'; +export const SPAN_NAME_DOC_REF_UPDATE = 'DocumentReference.Update'; +export const SPAN_NAME_DOC_REF_DELETE = 'DocumentReference.Delete'; +export const SPAN_NAME_DOC_REF_GET = 'DocumentReference.Get'; +export const SPAN_NAME_DOC_REF_LIST_COLLECTIONS = + 'DocumentReference.ListCollections'; +export const SPAN_NAME_COL_REF_ADD = 'CollectionReference.Add'; +export const SPAN_NAME_COL_REF_LIST_DOCUMENTS = + 'CollectionReference.ListDocuments'; +export const SPAN_NAME_QUERY_GET = 'Query.Get'; +export const SPAN_NAME_AGGREGATION_QUERY_GET = 'AggregationQuery.Get'; +export const SPAN_NAME_TRANSACTION_RUN = 'Transaction.Run'; +export const SPAN_NAME_TRANSACTION_GET_QUERY = 'Transaction.Get.Query'; +export const SPAN_NAME_TRANSACTION_GET_AGGREGATION_QUERY = + 'Transaction.Get.AggregationQuery'; +export const SPAN_NAME_TRANSACTION_GET_DOCUMENT = 'Transaction.Get.Document'; +export const SPAN_NAME_TRANSACTION_GET_DOCUMENTS = 'Transaction.Get.Documents'; +export const SPAN_NAME_TRANSACTION_ROLLBACK = 'Transaction.Rollback'; +export const SPAN_NAME_TRANSACTION_COMMIT = 'Transaction.Commit'; +export const SPAN_NAME_BATCH_COMMIT = 'Batch.Commit'; +export const SPAN_NAME_PARTITION_QUERY = 'PartitionQuery'; +export const SPAN_NAME_BULK_WRITER_COMMIT = 'BulkWriter.Commit'; +export const ATTRIBUTE_SERVICE_PREFIX = 'gcp.firestore'; +export const ATTRIBUTE_SETTINGS_PREFIX = `${ATTRIBUTE_SERVICE_PREFIX}.settings`; +export const ATTRIBUTE_KEY_DOC_COUNT = 'doc_count'; +export const ATTRIBUTE_KEY_IS_TRANSACTIONAL = 'transactional'; +export const ATTRIBUTE_KEY_NUM_RESPONSES = 'response_count'; +export const ATTRIBUTE_KEY_IS_RETRY_WITH_CURSOR = 'retry_query_with_cursor'; +export const ATTRIBUTE_KEY_TRANSACTION_TYPE = 'transaction_type'; +export const ATTRIBUTE_KEY_ATTEMPTS_ALLOWED = 'attempts_allowed'; +export const ATTRIBUTE_KEY_ATTEMPTS_REMAINING = 'attempts_remaining'; +export const ATTRIBUTE_GCP_RESOURCE_NAME = 'gcp.resource.name'; + +/** + * @private + * @internal + */ +export interface TraceUtil { + startActiveSpan unknown>( + name: string, + fn: F, + attributes?: Attributes, + ): ReturnType; + startSpan(name: string): Span; + + currentSpan(): Span; + + recordProjectIdAndResourceName(projectId: string, databaseId: string): void; +} diff --git a/handwritten/firestore/dev/src/timestamp.ts b/handwritten/firestore/dev/src/timestamp.ts new file mode 100644 index 00000000000..09ff1d086be --- /dev/null +++ b/handwritten/firestore/dev/src/timestamp.ts @@ -0,0 +1,311 @@ +/*! + * Copyright 2018 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; + +import {google} from '../protos/firestore_v1_proto_api'; +import {validateInteger} from './validate'; + +import api = google.firestore.v1; + +/*! + * Number of nanoseconds in a millisecond. + * + * @type {number} + */ +const MS_TO_NANOS = 1000000; + +/*! + * The minimum legal value for the "seconds" property of a Timestamp object. + * + * This value corresponds to 0001-01-01T00:00:00Z. + * + * @type {number} + */ +const MIN_SECONDS = -62135596800; + +/*! + * The maximum legal value for the "seconds" property of a Timestamp object. + * + * This value corresponds to 9999-12-31T23:59:59.999999999Z. + * + * @type {number} + */ +const MAX_SECONDS = 253402300799; + +/** + * A Timestamp represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian + * Calendar which extends the Gregorian calendar backwards to year one. It is + * encoded assuming all minutes are 60 seconds long, i.e. leap seconds are + * "smeared" so that no leap second table is needed for interpretation. Range is + * from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. + * + * @see https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto + */ +export class Timestamp implements firestore.Timestamp { + private readonly _seconds: number; + private readonly _nanoseconds: number; + + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({ updateTime:Firestore.Timestamp.now() }); + * + * ``` + * @returns {Timestamp} A new `Timestamp` representing the current date. + */ + static now(): Timestamp { + return Timestamp.fromMillis(Date.now()); + } + + /** + * Creates a new timestamp from the given date. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * let date = Date.parse('01 Jan 2000 00:00:00 GMT'); + * documentRef.set({ startTime:Firestore.Timestamp.fromDate(date) }); + * + * ``` + * @param {Date} date The date to initialize the `Timestamp` from. + * @returns {Timestamp} A new `Timestamp` representing the same point in time + * as the given date. + */ + static fromDate(date: Date): Timestamp { + return Timestamp.fromMillis(date.getTime()); + } + + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({ startTime:Firestore.Timestamp.fromMillis(42) }); + * + * ``` + * @param {number} milliseconds Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns {Timestamp} A new `Timestamp` representing the same point in time + * as the given number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp { + const seconds = Math.floor(milliseconds / 1000); + const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS); + return new Timestamp(seconds, nanos); + } + + /** + * Generates a `Timestamp` object from a Timestamp proto. + * + * @private + * @internal + * @param {Object} timestamp The `Timestamp` Protobuf object. + */ + static fromProto(timestamp: google.protobuf.ITimestamp): Timestamp { + return new Timestamp(Number(timestamp.seconds || 0), timestamp.nanos || 0); + } + + /** + * Creates a new timestamp. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({ startTime:new Firestore.Timestamp(42, 0) }); + * + * ``` + * @param {number} seconds The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param {number} nanoseconds The non-negative fractions of a second at + * nanosecond resolution. Negative second values with fractions must still + * have non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor(seconds: number, nanoseconds: number) { + validateInteger('seconds', seconds, { + minValue: MIN_SECONDS, + maxValue: MAX_SECONDS, + }); + validateInteger('nanoseconds', nanoseconds, { + minValue: 0, + maxValue: 999999999, + }); + + this._seconds = seconds; + this._nanoseconds = nanoseconds; + } + + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(snap => { + * let updated = snap.updateTime; + * console.log(`Updated at ${updated.seconds}s ${updated.nanoseconds}ns`); + * }); + * + * ``` + * @type {number} + */ + get seconds(): number { + return this._seconds; + } + + /** + * The non-negative fractions of a second at nanosecond resolution. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(snap => { + * let updated = snap.updateTime; + * console.log(`Updated at ${updated.seconds}s ${updated.nanoseconds}ns`); + * }); + * + * ``` + * @type {number} + */ + get nanoseconds(): number { + return this._nanoseconds; + } + + /** + * Returns a new `Date` corresponding to this timestamp. This may lose + * precision. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(snap => { + * console.log(`Document updated at: ${snap.updateTime.toDate()}`); + * }); + * + * ``` + * @returns {Date} JavaScript `Date` object representing the same point in time + * as this `Timestamp`, with millisecond precision. + */ + toDate(): Date { + return new Date( + this._seconds * 1000 + Math.round(this._nanoseconds / MS_TO_NANOS), + ); + } + + /** + * Returns the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(snap => { + * let startTime = snap.get('startTime'); + * let endTime = snap.get('endTime'); + * console.log(`Duration: ${endTime - startTime}`); + * }); + * + * ``` + * @returns {number} The point in time corresponding to this timestamp, + * represented as the number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + */ + toMillis(): number { + return this._seconds * 1000 + Math.floor(this._nanoseconds / MS_TO_NANOS); + } + + /** + * Returns 'true' if this `Timestamp` is equal to the provided one. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(snap => { + * if (snap.createTime.isEqual(snap.updateTime)) { + * console.log('Document is in its initial state.'); + * } + * }); + * + * ``` + * @param {any} other The `Timestamp` to compare against. + * @returns {boolean} 'true' if this `Timestamp` is equal to the provided one. + */ + isEqual(other: firestore.Timestamp): boolean { + return ( + this === other || + (other instanceof Timestamp && + this._seconds === other.seconds && + this._nanoseconds === other.nanoseconds) + ); + } + + /** + * Generates the Protobuf `Timestamp` object for this timestamp. + * + * @private + * @internal + * @returns {Object} The `Timestamp` Protobuf object. + */ + toProto(): api.IValue { + const timestamp: google.protobuf.ITimestamp = {}; + + if (this.seconds) { + timestamp.seconds = this.seconds.toString(); + } + + if (this.nanoseconds) { + timestamp.nanos = this.nanoseconds; + } + + return {timestampValue: timestamp}; + } + + /** + * Converts this object to a primitive `string`, which allows `Timestamp` objects to be compared + * using the `>`, `<=`, `>=` and `>` operators. + * + * @returns {string} a string encoding of this object. + */ + valueOf(): string { + // This method returns a string of the form . where is + // translated to have a non-negative value and both and are left-padded + // with zeroes to be a consistent length. Strings with this format then have a lexicographical + // ordering that matches the expected ordering. The translation is done to avoid + // having a leading negative sign (i.e. a leading '-' character) in its string representation, + // which would affect its lexicographical ordering. + const adjustedSeconds = this.seconds - MIN_SECONDS; + // Note: Up to 12 decimal digits are required to represent all valid 'seconds' values. + const formattedSeconds = String(adjustedSeconds).padStart(12, '0'); + const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0'); + return formattedSeconds + '.' + formattedNanoseconds; + } +} diff --git a/handwritten/firestore/dev/src/transaction.ts b/handwritten/firestore/dev/src/transaction.ts new file mode 100644 index 00000000000..968fb771d0f --- /dev/null +++ b/handwritten/firestore/dev/src/transaction.ts @@ -0,0 +1,1025 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; + +import {GoogleError} from 'google-gax'; +import * as proto from '../protos/firestore_v1_proto_api'; + +import {ExponentialBackoff} from './backoff'; +import {DocumentSnapshot} from './document'; +import {DEFAULT_MAX_TRANSACTION_ATTEMPTS, Firestore, WriteBatch} from './index'; +import {Pipeline, PipelineResult, PipelineSnapshot} from './pipelines'; +import {Timestamp} from './timestamp'; +import {logger} from './logger'; +import {FieldPath, validateFieldPath} from './path'; +import {StatusCode} from './status-code'; +import {AggregateQuery} from './reference/aggregate-query'; +import {AggregateQuerySnapshot} from './reference/aggregate-query-snapshot'; +import {DocumentReference} from './reference/document-reference'; +import {Query} from './reference/query'; +import {QuerySnapshot} from './reference/query-snapshot'; +import {validateDocumentReference} from './reference/helpers'; + +import {isObject, isPlainObject} from './util'; +import { + invalidArgumentMessage, + RequiredArgumentOptions, + validateMinNumberOfArguments, + validateOptional, +} from './validate'; +import {DocumentReader} from './document-reader'; +import api = proto.google.firestore.v1; +import { + ATTRIBUTE_KEY_ATTEMPTS_ALLOWED, + ATTRIBUTE_KEY_ATTEMPTS_REMAINING, + ATTRIBUTE_KEY_DOC_COUNT, + ATTRIBUTE_KEY_IS_TRANSACTIONAL, + ATTRIBUTE_KEY_TRANSACTION_TYPE, + SPAN_NAME_TRANSACTION_COMMIT, + SPAN_NAME_TRANSACTION_GET_AGGREGATION_QUERY, + SPAN_NAME_TRANSACTION_GET_DOCUMENT, + SPAN_NAME_TRANSACTION_GET_DOCUMENTS, + SPAN_NAME_TRANSACTION_GET_QUERY, + SPAN_NAME_TRANSACTION_ROLLBACK, + SPAN_NAME_TRANSACTION_RUN, +} from './telemetry/trace-util'; + +/*! + * Error message for transactional reads that were executed after performing + * writes. + */ +const READ_AFTER_WRITE_ERROR_MSG = + 'Firestore transactions require all reads to be executed before all writes.'; + +const READ_ONLY_WRITE_ERROR_MSG = + 'Firestore read-only transactions cannot execute writes.'; + +/** + * A reference to a transaction. + * + * The Transaction object passed to a transaction's updateFunction provides + * the methods to read and write data within the transaction context. See + * [runTransaction()]{@link Firestore#runTransaction}. + * + * @class Transaction + */ +export class Transaction implements firestore.Transaction { + private readonly _firestore: Firestore; + private readonly _maxAttempts: number = DEFAULT_MAX_TRANSACTION_ATTEMPTS; + private readonly _requestTag: string; + + /** Optional, could be set only if transaction is read only */ + private readonly _readOnlyReadTime: Timestamp | undefined; + /** `undefined` if transaction is read only */ + private readonly _writeBatch: WriteBatch | undefined; + /** `undefined` if transaction is read only */ + private readonly _backoff: ExponentialBackoff | undefined; + + /** + * Promise that resolves to the transaction ID of the current attempt. + * It is lazily initialised upon the first read. Upon retry, it is reset and + * `_prevTransactionId` is set + */ + private _transactionIdPromise?: Promise; + private _prevTransactionId?: Uint8Array; + + /** + * @private + * + * @param firestore The Firestore Database client. + * @param requestTag A unique client-assigned identifier for the scope of + * this transaction. + * @param transactionOptions The user-defined options for this transaction. + */ + constructor( + firestore: Firestore, + requestTag: string, + transactionOptions?: + | firestore.ReadWriteTransactionOptions + | firestore.ReadOnlyTransactionOptions, + ) { + this._firestore = firestore; + this._requestTag = requestTag; + if (transactionOptions?.readOnly) { + // Avoid initialising write batch and backoff unnecessarily for read-only transactions + this._maxAttempts = 1; + this._readOnlyReadTime = transactionOptions.readTime as + | Timestamp + | undefined; + } else { + this._maxAttempts = + transactionOptions?.maxAttempts || DEFAULT_MAX_TRANSACTION_ATTEMPTS; + this._writeBatch = firestore.batch(); + this._backoff = new ExponentialBackoff(); + } + } + + /** + * Retrieves a query result. Holds a pessimistic lock on all returned + * documents. + * + * @param {Query} query A query to execute. + * @returns {Promise} A QuerySnapshot for the retrieved data. + */ + get( + query: firestore.Query, + ): Promise>; + + /** + * Reads the document referenced by the provided `DocumentReference.` + * Holds a pessimistic lock on the returned document. + * + * @param {DocumentReference} documentRef A reference to the document to be read. + * @returns {Promise} A DocumentSnapshot for the read data. + */ + get( + documentRef: firestore.DocumentReference, + ): Promise>; + + /** + * Retrieves an aggregate query result. Holds a pessimistic lock on all + * documents that were matched by the underlying query. + * + * @param aggregateQuery An aggregate query to execute. + * @returns An AggregateQuerySnapshot for the retrieved data. + */ + get< + AppModelType, + DbModelType extends firestore.DocumentData, + AggregateSpecType extends firestore.AggregateSpec, + >( + aggregateQuery: firestore.AggregateQuery< + AggregateSpecType, + AppModelType, + DbModelType + >, + ): Promise< + AggregateQuerySnapshot + >; + + /** + * Retrieve a document or a query result from the database. Holds a + * pessimistic lock on all returned documents. + * + * @param {DocumentReference|Query} refOrQuery The document or query to + * return. + * @returns {Promise} A Promise that resolves with a DocumentSnapshot or + * QuerySnapshot for the returned documents. + * + * @example + * ``` + * firestore.runTransaction(transaction => { + * let documentRef = firestore.doc('col/doc'); + * return transaction.get(documentRef).then(doc => { + * if (doc.exists) { + * transaction.update(documentRef, { count: doc.get('count') + 1 }); + * } else { + * transaction.create(documentRef, { count: 1 }); + * } + * }); + * }); + * ``` + */ + get< + AppModelType, + DbModelType extends firestore.DocumentData, + AggregateSpecType extends firestore.AggregateSpec, + >( + refOrQuery: + | firestore.DocumentReference + | firestore.Query + | firestore.AggregateQuery, + ): Promise< + | DocumentSnapshot + | QuerySnapshot + | AggregateQuerySnapshot + > { + if (this._writeBatch && !this._writeBatch.isEmpty) { + throw new Error(READ_AFTER_WRITE_ERROR_MSG); + } + + if (refOrQuery instanceof DocumentReference) { + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_TRANSACTION_GET_DOCUMENT, + () => { + return this.withLazyStartedTransaction(refOrQuery, this.getSingleFn); + }, + ); + } + + if (refOrQuery instanceof Query || refOrQuery instanceof AggregateQuery) { + return this._firestore._traceUtil.startActiveSpan( + refOrQuery instanceof Query + ? SPAN_NAME_TRANSACTION_GET_QUERY + : SPAN_NAME_TRANSACTION_GET_AGGREGATION_QUERY, + () => { + return this.withLazyStartedTransaction(refOrQuery, this.getQueryFn); + }, + ); + } + + throw new Error( + 'Value for argument "refOrQuery" must be a DocumentReference, Query, or AggregateQuery.', + ); + } + + /** + * Retrieves multiple documents from Firestore. Holds a pessimistic lock on + * all returned documents. + * + * The first argument is required and must be of type `DocumentReference` + * followed by any additional `DocumentReference` documents. If used, the + * optional `ReadOptions` must be the last argument. + * + * @param {...DocumentReference|ReadOptions} documentRefsOrReadOptions The + * `DocumentReferences` to receive, followed by an optional field mask. + * @returns {Promise>} A Promise that + * contains an array with the resulting document snapshots. + * + * @example + * ``` + * let firstDoc = firestore.doc('col/doc1'); + * let secondDoc = firestore.doc('col/doc2'); + * let resultDoc = firestore.doc('col/doc3'); + * + * firestore.runTransaction(transaction => { + * return transaction.getAll(firstDoc, secondDoc).then(docs => { + * transaction.set(resultDoc, { + * sum: docs[0].get('count') + docs[1].get('count') + * }); + * }); + * }); + * ``` + */ + getAll( + ...documentRefsOrReadOptions: Array< + | firestore.DocumentReference + | firestore.ReadOptions + > + ): Promise>> { + if (this._writeBatch && !this._writeBatch.isEmpty) { + throw new Error(READ_AFTER_WRITE_ERROR_MSG); + } + + validateMinNumberOfArguments( + 'Transaction.getAll', + documentRefsOrReadOptions, + 1, + ); + + return this.withLazyStartedTransaction( + parseGetAllArguments(documentRefsOrReadOptions), + this.getBatchFn, + ); + } + + /** + * Executes this pipeline and returns a Promise to represent the asynchronous operation. + * + *

The returned Promise can be used to track the progress of the pipeline execution + * and retrieve the results (or handle any errors) asynchronously. + * + *

The pipeline results are returned in a `PipelineSnapshot` object, which contains a list of + * `PipelineResult` objects. Each `PipelineResult` typically represents a single key/value map that + * has passed through all the stages of the pipeline, however this might differ depending on the stages involved + * in the pipeline. For example: + * + *

    + *
  • If there are no stages or only transformation stages, each `PipelineResult` + * represents a single document.
  • + *
  • If there is an aggregation, only a single `PipelineResult` is returned, + * representing the aggregated results over the entire dataset .
  • + *
  • If there is an aggregation stage with grouping, each `PipelineResult` represents a + * distinct group and its associated aggregated values.
  • + *
+ * + * + * @example + * ```typescript + * const futureResults = await transaction + * .execute( + * firestore.pipeline().collection("books") + * .where(greaterThan(field("rating"), 4.5)) + * .select("title", "author", "rating")); + * ``` + * + * @returns A Promise representing the asynchronous pipeline execution. + */ + execute(pipeline: Pipeline): Promise { + if (this._writeBatch && !this._writeBatch.isEmpty) { + throw new Error(READ_AFTER_WRITE_ERROR_MSG); + } + + if (pipeline instanceof Pipeline) { + return this.withLazyStartedTransaction( + pipeline, + this.executePipelineFn, + ).then(results => { + const executionTime = results.reduce((maxTime, result) => { + return result._executionTime && + result._executionTime?.valueOf() > maxTime.valueOf() + ? result._executionTime + : maxTime; + }, Timestamp.fromMillis(0)); + + return new PipelineSnapshot(pipeline, results, executionTime); + }); + } + + throw new Error('Value for argument "pipeline" must be a Pipeline'); + } + + /** + * Create the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. The operation will + * fail the transaction if a document exists at the specified location. + * + * @param {DocumentReference} documentRef A reference to the document to be + * created. + * @param {DocumentData} data The object data to serialize as the document. + * @returns {Transaction} This Transaction instance. Used for + * chaining method calls. + * + * @example + * ``` + * firestore.runTransaction(transaction => { + * let documentRef = firestore.doc('col/doc'); + * return transaction.get(documentRef).then(doc => { + * if (!doc.exists) { + * transaction.create(documentRef, { foo: 'bar' }); + * } + * }); + * }); + * ``` + */ + create( + documentRef: firestore.DocumentReference, + data: firestore.WithFieldValue, + ): Transaction { + if (!this._writeBatch) { + throw new Error(READ_ONLY_WRITE_ERROR_MSG); + } + this._writeBatch.create(documentRef, data); + return this; + } + + set( + documentRef: firestore.DocumentReference, + data: firestore.PartialWithFieldValue, + options: firestore.SetOptions, + ): Transaction; + set( + documentRef: firestore.DocumentReference, + data: firestore.WithFieldValue, + ): Transaction; + /** + * Writes to the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document + * does not exist yet, it will be created. If you pass + * [SetOptions]{@link SetOptions}, the provided data can be merged into the + * existing document. + * + * @param {DocumentReference} documentRef A reference to the document to be + * set. + * @param {T|Partial} data The object to serialize as the document. + * @param {SetOptions=} options An object to configure the set behavior. + * @param {boolean=} options.merge - If true, set() merges the values + * specified in its data argument. Fields omitted from this set() call remain + * untouched. If your input sets any field to an empty map, all nested fields + * are overwritten. + * @param {Array.=} options.mergeFields - If provided, + * set() only replaces the specified field paths. Any field path that is not + * specified is ignored and remains untouched. If your input sets any field to + * an empty map, all nested fields are overwritten. + * @throws {Error} If the provided input is not a valid Firestore document. + * @returns {Transaction} This Transaction instance. Used for + * chaining method calls. + * + * @example + * ``` + * firestore.runTransaction(transaction => { + * let documentRef = firestore.doc('col/doc'); + * transaction.set(documentRef, { foo: 'bar' }); + * return Promise.resolve(); + * }); + * ``` + */ + set( + documentRef: firestore.DocumentReference, + data: firestore.PartialWithFieldValue, + options?: firestore.SetOptions, + ): Transaction { + if (!this._writeBatch) { + throw new Error(READ_ONLY_WRITE_ERROR_MSG); + } + if (options) { + this._writeBatch.set(documentRef, data, options); + } else { + this._writeBatch.set( + documentRef, + data as firestore.WithFieldValue, + ); + } + return this; + } + + /** + * Updates fields in the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. The update will + * fail if applied to a document that does not exist. + * + * The update() method accepts either an object with field paths encoded as + * keys and field values encoded as values, or a variable number of arguments + * that alternate between field paths and field values. Nested fields can be + * updated by providing dot-separated field path strings or by providing + * FieldPath objects. + * + * A Precondition restricting this update can be specified as the last + * argument. + * + * @param {DocumentReference} documentRef A reference to the document to be + * updated. + * @param {UpdateData|string|FieldPath} dataOrField An object + * containing the fields and values with which to update the document + * or the path of the first field to update. + * @param { + * ...(Precondition|*|string|FieldPath)} preconditionOrValues - + * An alternating list of field paths and values to update or a Precondition + * to to enforce on this update. + * @throws {Error} If the provided input is not valid Firestore data. + * @returns {Transaction} This Transaction instance. Used for + * chaining method calls. + * + * @example + * ``` + * firestore.runTransaction(transaction => { + * let documentRef = firestore.doc('col/doc'); + * return transaction.get(documentRef).then(doc => { + * if (doc.exists) { + * transaction.update(documentRef, { count: doc.get('count') + 1 }); + * } else { + * transaction.create(documentRef, { count: 1 }); + * } + * }); + * }); + * ``` + */ + update( + documentRef: firestore.DocumentReference, + dataOrField: + | firestore.UpdateData + | string + | firestore.FieldPath, + ...preconditionOrValues: Array< + firestore.Precondition | unknown | string | firestore.FieldPath + > + ): Transaction { + if (!this._writeBatch) { + throw new Error(READ_ONLY_WRITE_ERROR_MSG); + } + + // eslint-disable-next-line prefer-rest-params + validateMinNumberOfArguments('Transaction.update', arguments, 2); + + this._writeBatch.update(documentRef, dataOrField, ...preconditionOrValues); + return this; + } + + /** + * Deletes the document referred to by the provided [DocumentReference] + * {@link DocumentReference}. + * + * @param {DocumentReference} documentRef A reference to the document to be + * deleted. + * @param {Precondition=} precondition A precondition to enforce for this + * delete. + * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the + * document was last updated at lastUpdateTime. Fails the transaction if the + * document doesn't exist or was last updated at a different time. + * @param {boolean=} precondition.exists If set, enforces that the target + * document must or must not exist. + * @returns {Transaction} This Transaction instance. Used for + * chaining method calls. + * + * @example + * ``` + * firestore.runTransaction(transaction => { + * let documentRef = firestore.doc('col/doc'); + * transaction.delete(documentRef); + * return Promise.resolve(); + * }); + * ``` + */ + delete( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + documentRef: DocumentReference, + precondition?: firestore.Precondition, + ): this { + if (!this._writeBatch) { + throw new Error(READ_ONLY_WRITE_ERROR_MSG); + } + this._writeBatch.delete(documentRef, precondition); + return this; + } + + /** + * Commits all queued-up changes in this transaction and releases all locks. + * + * @private + * @internal + */ + async commit(): Promise { + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_TRANSACTION_COMMIT, + async () => { + if (!this._writeBatch) { + throw new Error(READ_ONLY_WRITE_ERROR_MSG); + } + + // If we have not performed any reads in this particular attempt + // then the writes will be atomically committed without a transaction ID + let transactionId: Uint8Array | undefined; + if (this._transactionIdPromise) { + transactionId = await this._transactionIdPromise; + } else if (this._writeBatch.isEmpty) { + // If we have not started a transaction (no reads) and we have no writes + // then the commit is a no-op (success) + return; + } + + await this._writeBatch._commit({ + transactionId, + requestTag: this._requestTag, + }); + this._transactionIdPromise = undefined; + this._prevTransactionId = transactionId; + }, + { + [ATTRIBUTE_KEY_IS_TRANSACTIONAL]: true, + [ATTRIBUTE_KEY_DOC_COUNT]: this._writeBatch?._opCount, + }, + ); + } + + /** + * Releases all locks and rolls back this transaction. The rollback process + * is completed asynchronously and this function resolves before the operation + * is completed. + * + * @private + * @internal + */ + async rollback(): Promise { + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_TRANSACTION_ROLLBACK, + async () => { + // No need to roll back if we have not lazily started the transaction + // or if we are read only + if (!this._transactionIdPromise || !this._writeBatch) { + return; + } + + let transactionId: Uint8Array; + try { + transactionId = await this._transactionIdPromise; + } catch { + // This means the initial read operation rejected + // and we do not have a transaction ID to roll back + this._transactionIdPromise = undefined; + return; + } + + const request: api.IRollbackRequest = { + database: this._firestore.formattedName, + transaction: transactionId, + }; + this._transactionIdPromise = undefined; + this._prevTransactionId = transactionId; + + // We don't need to wait for rollback to completed before continuing. + // If there are any locks held, then rollback will eventually release them. + // Rollback can be done concurrently thereby reducing latency caused by + // otherwise blocking. + this._firestore + .request('rollback', request, this._requestTag) + .catch(err => { + logger( + 'Firestore.runTransaction', + this._requestTag, + 'Best effort to rollback failed with error:', + err, + ); + }); + }, + ); + } + + /** + * Executes `updateFunction()` and commits the transaction with retry. + * + * @private + * @internal + * @param updateFunction The user function to execute within the transaction + * context. + */ + async runTransaction( + updateFunction: (transaction: Transaction) => Promise, + ): Promise { + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_TRANSACTION_RUN, + async span => { + // No backoff is set for readonly transactions (i.e. attempts == 1) + if (!this._writeBatch) { + return this.runTransactionOnce(updateFunction); + } + + let lastError: GoogleError | undefined = undefined; + for (let attempt = 0; attempt < this._maxAttempts; ++attempt) { + span.setAttributes({ + [ATTRIBUTE_KEY_TRANSACTION_TYPE]: this._writeBatch + ? 'READ_WRITE' + : 'READ_ONLY', + [ATTRIBUTE_KEY_ATTEMPTS_ALLOWED]: this._maxAttempts, + [ATTRIBUTE_KEY_ATTEMPTS_REMAINING]: this._maxAttempts - attempt - 1, + }); + + try { + if (lastError) { + logger( + 'Firestore.runTransaction', + this._requestTag, + 'Retrying transaction after error:', + lastError, + ); + + span.addEvent('Initiate transaction retry'); + } + + this._writeBatch._reset(); + + await maybeBackoff(this._backoff!, lastError); + + return await this.runTransactionOnce(updateFunction); + } catch (err) { + lastError = err; + + if (!isRetryableTransactionError(err)) { + break; + } + } + } + + logger( + 'Firestore.runTransaction', + this._requestTag, + 'Transaction not eligible for retry, returning error: %s', + lastError, + ); + + return Promise.reject(lastError); + }, + ); + } + + /** + * Make single attempt to execute `updateFunction()` and commit the + * transaction. Will rollback upon error. + * + * @private + * @internal + * @param updateFunction The user function to execute within the transaction + * context. + */ + async runTransactionOnce( + updateFunction: (transaction: Transaction) => Promise, + ): Promise { + try { + const promise = updateFunction(this); + if (!(promise instanceof Promise)) { + throw new Error( + 'You must return a Promise in your transaction()-callback.', + ); + } + const result = await promise; + if (this._writeBatch) { + await this.commit(); + } + return result; + } catch (err) { + logger( + 'Firestore.runTransaction', + this._requestTag, + 'Rolling back transaction after callback error:', + err, + ); + await this.rollback(); + return Promise.reject(err); + } + } + + /** + * Given a function that performs a read operation, ensures that the first one + * is provided with new transaction options and all subsequent ones are queued + * upon the resulting transaction ID. + */ + private withLazyStartedTransaction( + param: TParam, + resultFn: ( + this: typeof this, + param: TParam, + opts: Uint8Array | api.ITransactionOptions | Timestamp, + ) => Promise<{transaction?: Uint8Array; result: TResult}>, + ): Promise { + if (this._transactionIdPromise) { + // Simply queue this subsequent read operation after the first read + // operation has resolved and we don't expect a transaction ID in the + // response because we are not starting a new transaction + return this._transactionIdPromise + .then(opts => resultFn.call(this, param, opts)) + .then(r => r.result); + } else { + if (this._readOnlyReadTime) { + // We do not start a transaction for read-only transactions + // do not set _prevTransactionId + return resultFn + .call(this, param, this._readOnlyReadTime) + .then(r => r.result); + } else { + // This is the first read of the transaction so we create the appropriate + // options for lazily starting the transaction inside this first read op + const opts: api.ITransactionOptions = {}; + if (this._writeBatch) { + opts.readWrite = this._prevTransactionId + ? {retryTransaction: this._prevTransactionId} + : {}; + } else { + opts.readOnly = {}; + } + + const resultPromise = resultFn.call(this, param, opts); + + // Ensure the _transactionIdPromise is set synchronously so that + // subsequent operations will not race to start another transaction + this._transactionIdPromise = resultPromise.then(r => { + if (!r.transaction) { + // Illegal state + // The read operation was provided with new transaction options but did not return a transaction ID + // Rejecting here will cause all queued reads to reject + throw new Error('Transaction ID was missing from server response'); + } + return r.transaction; + }); + + return resultPromise.then(r => r.result); + } + } + } + + private async getSingleFn< + AppModelType, + DbModelType extends firestore.DocumentData, + >( + document: DocumentReference, + opts: Uint8Array | api.ITransactionOptions | Timestamp, + ): Promise<{ + transaction?: Uint8Array; + result: DocumentSnapshot; + }> { + const documentReader = new DocumentReader( + this._firestore, + [document], + undefined, + opts, + ); + const { + transaction, + result: [result], + } = await documentReader._get(this._requestTag); + return {transaction, result}; + } + + private async getBatchFn< + AppModelType, + DbModelType extends firestore.DocumentData, + >( + { + documents, + fieldMask, + }: { + documents: Array>; + fieldMask?: FieldPath[]; + }, + opts: Uint8Array | api.ITransactionOptions | Timestamp, + ): Promise<{ + transaction?: Uint8Array; + result: DocumentSnapshot[]; + }> { + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_TRANSACTION_GET_DOCUMENTS, + async () => { + const documentReader = new DocumentReader( + this._firestore, + documents, + fieldMask, + opts, + ); + return documentReader._get(this._requestTag); + }, + ); + } + + private async getQueryFn< + // eslint-disable-next-line @typescript-eslint/no-explicit-any + TQuery extends Query | AggregateQuery, + >( + query: TQuery, + opts: Uint8Array | api.ITransactionOptions | Timestamp, + ): Promise<{ + transaction?: Uint8Array; + result: Awaited>['result']; + }> { + return query._get(opts); + } + + private async executePipelineFn( + pipeline: Pipeline, + opts: Uint8Array | api.ITransactionOptions | Timestamp, + ): Promise<{ + transaction?: Uint8Array; + result: Array; + }> { + const {transaction, result} = await pipeline._execute(opts); + return {transaction, result: result || []}; + } +} + +/** + * Parses the arguments for the `getAll()` call supported by both the Firestore + * and Transaction class. + * + * @private + * @internal + * @param documentRefsOrReadOptions An array of document references followed by + * an optional ReadOptions object. + */ +export function parseGetAllArguments< + AppModelType, + DbModelType extends firestore.DocumentData, +>( + documentRefsOrReadOptions: Array< + | firestore.DocumentReference + | firestore.ReadOptions + >, +): { + documents: Array>; + fieldMask: FieldPath[] | undefined; +} { + let documents: Array>; + let readOptions: firestore.ReadOptions | undefined = undefined; + + if (Array.isArray(documentRefsOrReadOptions[0])) { + throw new Error( + 'getAll() no longer accepts an array as its first argument. ' + + 'Please unpack your array and call getAll() with individual arguments.', + ); + } + + if ( + documentRefsOrReadOptions.length > 0 && + isPlainObject( + documentRefsOrReadOptions[documentRefsOrReadOptions.length - 1], + ) + ) { + readOptions = documentRefsOrReadOptions.pop() as firestore.ReadOptions; + documents = documentRefsOrReadOptions as Array< + DocumentReference + >; + } else { + documents = documentRefsOrReadOptions as Array< + DocumentReference + >; + } + + for (let i = 0; i < documents.length; ++i) { + validateDocumentReference(i, documents[i]); + } + + validateReadOptions('options', readOptions, {optional: true}); + const fieldMask = + readOptions && readOptions.fieldMask + ? readOptions.fieldMask.map(fieldPath => + FieldPath.fromArgument(fieldPath), + ) + : undefined; + return {fieldMask, documents}; +} + +/** + * Validates the use of 'options' as ReadOptions and enforces that 'fieldMask' + * is an array of strings or field paths. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the ReadOptions can be omitted. + */ +function validateReadOptions( + arg: number | string, + value: unknown, + options?: RequiredArgumentOptions, +): void { + if (!validateOptional(value, options)) { + if (!isObject(value)) { + throw new Error( + `${invalidArgumentMessage(arg, 'read option')} Input is not an object.'`, + ); + } + + const options = value as {[k: string]: unknown}; + + if (options.fieldMask !== undefined) { + if (!Array.isArray(options.fieldMask)) { + throw new Error( + `${invalidArgumentMessage( + arg, + 'read option', + )} "fieldMask" is not an array.`, + ); + } + + for (let i = 0; i < options.fieldMask.length; ++i) { + try { + validateFieldPath(i, options.fieldMask[i]); + } catch (err) { + throw new Error( + `${invalidArgumentMessage( + arg, + 'read option', + )} "fieldMask" is not valid: ${err.message}`, + ); + } + } + } + } +} + +function isRetryableTransactionError(error: GoogleError): boolean { + if (error.code !== undefined) { + // This list is based on https://github.com/firebase/firebase-js-sdk/blob/master/packages/firestore/src/core/transaction_runner.ts#L112 + switch (error.code as number) { + case StatusCode.ABORTED: + case 409: // GAXIOS may now return HTTP 409 instead of Aborted + case StatusCode.CANCELLED: + case StatusCode.UNKNOWN: + case StatusCode.DEADLINE_EXCEEDED: + case StatusCode.INTERNAL: + case StatusCode.UNAVAILABLE: + case StatusCode.UNAUTHENTICATED: + case StatusCode.RESOURCE_EXHAUSTED: + return true; + case StatusCode.INVALID_ARGUMENT: + // The Firestore backend uses "INVALID_ARGUMENT" for transactions + // IDs that have expired. While INVALID_ARGUMENT is generally not + // retryable, we retry this specific case. + return !!error.message.match(/transaction has expired/); + default: + return false; + } + } + return false; +} + +/** + * Delays further operations based on the provided error. + * + * @private + * @internal + * @returns A Promise that resolves after the delay expired. + */ +async function maybeBackoff( + backoff: ExponentialBackoff, + error?: GoogleError, +): Promise { + if ( + (error?.code as number | undefined) === StatusCode.RESOURCE_EXHAUSTED || + (error?.code as number | undefined) === 409 + ) { + backoff.resetToMax(); + } + await backoff.backoffAndWait(); +} diff --git a/handwritten/firestore/dev/src/types.ts b/handwritten/firestore/dev/src/types.ts new file mode 100644 index 00000000000..94a7e8f5259 --- /dev/null +++ b/handwritten/firestore/dev/src/types.ts @@ -0,0 +1,185 @@ +/*! + * Copyright 2018 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + FirestoreDataConverter, + QueryDocumentSnapshot, + DocumentData, + WithFieldValue, +} from '@google-cloud/firestore'; + +import {CallOptions} from 'google-gax'; +import {Duplex} from 'stream'; + +import {google} from '../protos/firestore_v1_proto_api'; +import {FieldPath} from './path'; + +import api = google.firestore.v1; + +/** + * A map in the format of the Proto API + */ +export interface ApiMapValue { + [k: string]: google.firestore.v1.IValue; +} + +/** + * The subset of methods we use from FirestoreClient. + * + * We don't depend on the actual Gapic client to avoid loading the GAX stack at + * module initialization time. + */ +export interface GapicClient { + getProjectId(): Promise; + beginTransaction( + request: api.IBeginTransactionRequest, + options?: CallOptions, + ): Promise<[api.IBeginTransactionResponse, unknown, unknown]>; + commit( + request: api.ICommitRequest, + options?: CallOptions, + ): Promise<[api.ICommitResponse, unknown, unknown]>; + batchWrite( + request: api.IBatchWriteRequest, + options?: CallOptions, + ): Promise<[api.IBatchWriteResponse, unknown, unknown]>; + rollback( + request: api.IRollbackRequest, + options?: CallOptions, + ): Promise<[google.protobuf.IEmpty, unknown, unknown]>; + batchGetDocuments( + request?: api.IBatchGetDocumentsRequest, + options?: CallOptions, + ): Duplex; + executePipeline( + request?: api.IExecutePipelineRequest, + options?: CallOptions, + ): Duplex; + runQuery(request?: api.IRunQueryRequest, options?: CallOptions): Duplex; + runAggregationQuery( + request?: api.IRunAggregationQueryRequest, + options?: CallOptions, + ): Duplex; + listDocuments( + request: api.IListDocumentsRequest, + options?: CallOptions, + ): Promise<[api.IDocument[], unknown, unknown]>; + listCollectionIds( + request: api.IListCollectionIdsRequest, + options?: CallOptions, + ): Promise<[string[], unknown, unknown]>; + listen(options?: CallOptions): Duplex; + partitionQueryStream( + request?: api.IPartitionQueryRequest, + options?: CallOptions, + ): Duplex; + close(): Promise; +} + +/** Request/response methods used in the Firestore SDK. */ +export type FirestoreUnaryMethod = + | 'listDocuments' + | 'listCollectionIds' + | 'rollback' + | 'beginTransaction' + | 'commit' + | 'batchWrite'; + +/** Streaming methods used in the Firestore SDK. */ +export type FirestoreStreamingMethod = + | 'executePipeline' + | 'listen' + | 'partitionQueryStream' + | 'runQuery' + | 'runAggregationQuery' + | 'batchGetDocuments'; + +/** Type signature for the unary methods in the GAPIC layer. */ +export type UnaryMethod = ( + request: Req, + callOptions: CallOptions, +) => Promise<[Resp, unknown, unknown]>; + +// We don't have type information for the npm package +// `functional-red-black-tree`. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type RBTree = any; + +/** + * A default converter to use when none is provided. + * + * By declaring the converter as a variable instead of creating the object + * inside defaultConverter(), object equality when comparing default converters + * is preserved. + * @private + * @internal + */ +const defaultConverterObj: FirestoreDataConverter = { + toFirestore(modelObject: WithFieldValue): DocumentData { + return modelObject; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): DocumentData { + return snapshot.data()!; + }, +}; + +/** + * A default converter to use when none is provided. + * @private + * @internal + */ +export function defaultConverter< + AppModelType, + DbModelType extends DocumentData, +>(): FirestoreDataConverter { + return defaultConverterObj as FirestoreDataConverter< + AppModelType, + DbModelType + >; +} + +/** + * Update data that has been resolved to a mapping of FieldPaths to values. + */ +export type UpdateMap = Map; + +/** + * Internal user data validation options. + * @private + * @internal + */ +export interface ValidationOptions { + /** At what level field deletes are supported. */ + allowDeletes: 'none' | 'root' | 'all'; + + /** Whether server transforms are supported. */ + allowTransforms: boolean; + + /** + * Whether undefined values are allowed. Undefined values cannot appear at + * the root. + */ + allowUndefined: boolean; +} + +/** + * A Firestore Proto value in ProtoJs format. + * @private + * @internal + */ +export interface ProtobufJsValue extends api.IValue { + valueType?: string; +} diff --git a/handwritten/firestore/dev/src/util.ts b/handwritten/firestore/dev/src/util.ts new file mode 100644 index 00000000000..d8ef4fd4f71 --- /dev/null +++ b/handwritten/firestore/dev/src/util.ts @@ -0,0 +1,391 @@ +/*! + * Copyright 2018 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {DocumentData} from '@google-cloud/firestore'; + +import {randomBytes} from 'crypto'; +import type {CallSettings, ClientConfig, GoogleError} from 'google-gax'; +import type {BackoffSettings} from 'google-gax/build/src/gax'; +import * as gapicConfig from './v1/firestore_client_config.json'; +import Dict = NodeJS.Dict; + +/** + * A Promise implementation that supports deferred resolution. + * @private + * @internal + */ +export class Deferred { + promise: Promise; + resolve: (value: R | Promise) => void = () => {}; + reject: (reason: Error) => void = () => {}; + + constructor() { + this.promise = new Promise( + ( + resolve: (value: R | Promise) => void, + reject: (reason: Error) => void, + ) => { + this.resolve = resolve; + this.reject = reject; + }, + ); + } +} + +/** + * Generate a unique client-side identifier. + * + * Used for the creation of new documents. + * + * @private + * @internal + * @returns {string} A unique 20-character wide identifier. + */ +export function autoId(): string { + const chars = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + let autoId = ''; + while (autoId.length < 20) { + const bytes = randomBytes(40); + bytes.forEach(b => { + // Length of `chars` is 62. We only take bytes between 0 and 62*4-1 + // (both inclusive). The value is then evenly mapped to indices of `char` + // via a modulo operation. + const maxValue = 62 * 4 - 1; + if (autoId.length < 20 && b <= maxValue) { + autoId += chars.charAt(b % 62); + } + }); + } + return autoId; +} + +/** + * Generate a short and semi-random client-side identifier. + * + * Used for the creation of request tags. + * + * @private + * @internal + * @returns {string} A random 5-character wide identifier. + */ +export function requestTag(): string { + return autoId().substr(0, 5); +} + +/** + * Determines whether `value` is a JavaScript object. + * + * @private + * @internal + */ +export function isObject(value: unknown): value is {[k: string]: unknown} { + return Object.prototype.toString.call(value) === '[object Object]'; +} + +/** + * Verifies that 'obj' is a plain JavaScript object that can be encoded as a + * 'Map' in Firestore. + * + * @private + * @internal + * @param input The argument to verify. + * @returns 'true' if the input can be a treated as a plain object. + */ +export function isPlainObject(input: unknown): input is DocumentData { + return ( + isObject(input) && + (Object.getPrototypeOf(input) === Object.prototype || + Object.getPrototypeOf(input) === null || + input.constructor.name === 'Object') + ); +} + +/** + * Returns whether `value` has no custom properties. + * + * @private + * @internal + */ +export function isEmpty(value: {}): boolean { + return Object.keys(value).length === 0; +} + +/** + * Determines whether `value` is a JavaScript function. + * + * @private + * @internal + */ +export function isFunction(value: unknown): boolean { + return typeof value === 'function'; +} + +/** + * Determines whether the provided error is considered permanent for the given + * RPC. + * + * @private + * @internal + */ +export function isPermanentRpcError( + err: GoogleError, + methodName: string, +): boolean { + if (err.code !== undefined) { + const retryCodes = getRetryCodes(methodName); + return retryCodes.indexOf(err.code) === -1; + } else { + return false; + } +} + +let serviceConfig: Record | undefined; + +/** + * Lazy-loads the service config when first accessed. + * @private + * @internal + **/ +function getServiceConfig(methodName: string): CallSettings | undefined { + if (!serviceConfig) { + serviceConfig = require('google-gax/fallback').constructSettings( + 'google.firestore.v1.Firestore', + gapicConfig as ClientConfig, + {}, + require('google-gax').Status, + ) as {[k: string]: CallSettings}; + } + return serviceConfig[methodName]; +} + +/** + * Returns the list of retryable error codes specified in the service + * configuration. + * @private + * @internal + */ +export function getRetryCodes(methodName: string): number[] { + return getServiceConfig(methodName)?.retry?.retryCodes ?? []; +} + +/** + * Gets the total timeout in milliseconds from the retry settings in + * the service config for the given RPC. If the total timeout is not + * set, then `0` is returned. + * + * @private + * @internal + */ +export function getTotalTimeout(methodName: string): number { + return ( + getServiceConfig(methodName)?.retry?.backoffSettings?.totalTimeoutMillis ?? + 0 + ); +} + +/** + * Returns the backoff setting from the service configuration. + * @private + * @internal + */ +export function getRetryParams(methodName: string): BackoffSettings { + return ( + getServiceConfig(methodName)?.retry?.backoffSettings ?? + require('google-gax/fallback').createDefaultBackoffSettings() + ); +} + +/** + * Returns a promise with a void return type. The returned promise swallows all + * errors and never throws. + * + * This is primarily used to wait for a promise to complete when the result of + * the promise will be discarded. + * + * @private + * @internal + */ +export function silencePromise(promise: Promise): Promise { + return promise.then( + () => {}, + () => {}, + ); +} + +/** + * Wraps the provided error in a new error that includes the provided stack. + * + * Used to preserve stack traces across async calls. + * @private + * @internal + */ +export function wrapError(err: Error, stack: string): Error { + err.stack += '\nCaused by: ' + stack; + return err; +} + +/** + * Parses the value of the environment variable FIRESTORE_PREFER_REST, and + * returns a value indicating if the environment variable enables or disables + * preferRest. + * + * This function will warn to the console if the environment variable is set + * to an unsupported value. + * + * @returns `true` if the environment variable enables `preferRest`, + * `false` if the environment variable disables `preferRest`, or `undefined` + * if the environment variable is not set or is set to an unsupported value. + * + * @internal + * @private + */ +export function tryGetPreferRestEnvironmentVariable(): boolean | undefined { + const rawValue = process.env.FIRESTORE_PREFER_REST?.trim().toLowerCase(); + if (rawValue === undefined) { + return undefined; + } else if (rawValue === '1' || rawValue === 'true') { + return true; + } else if (rawValue === '0' || rawValue === 'false') { + return false; + } else { + // eslint-disable-next-line no-console + console.warn( + `An unsupported value was specified for the environment variable FIRESTORE_PREFER_REST. Value ${rawValue} is unsupported.`, + ); + return undefined; + } +} + +/** + * Returns an array of values that are calculated by performing the given `fn` + * on all keys in the given `obj` dictionary. + * + * @private + * @internal + */ +export function mapToArray( + obj: Dict, + fn: (element: V, key: string, obj: Dict) => R, +): R[] { + const result: R[] = []; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + result.push(fn(obj[key]!, key, obj)); + } + } + return result; +} + +/** + * Verifies equality for an array of objects using the `isEqual` interface. + * + * @private + * @internal + * @param left Array of objects supporting `isEqual`. + * @param right Array of objects supporting `isEqual`. + * @returns True if arrays are equal. + */ +export function isArrayEqual boolean}>( + left: T[], + right: T[], +): boolean { + if (left.length !== right.length) { + return false; + } + + for (let i = 0; i < left.length; ++i) { + if (!left[i].isEqual(right[i])) { + return false; + } + } + + return true; +} + +/** + * Verifies equality for an optional type using the `isEqual` interface. + * + * @private + * @internal + * @param left Optional object supporting `isEqual`. + * @param right Optional object supporting `isEqual`. + * @returns True if equal. + */ +export function isOptionalEqual boolean}>( + left: T | undefined, + right: T | undefined, +): boolean { + if (left === undefined && right === undefined) { + return true; + } + + if (left === undefined || right === undefined) { + return false; + } + + return left.isEqual(right); +} + +/** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @returns True if arrays are equal. + */ +export function isPrimitiveArrayEqual( + left: T[], + right: T[], +): boolean { + if (left.length !== right.length) { + return false; + } + + for (let i = 0; i < left.length; ++i) { + if (left[i] !== right[i]) { + return false; + } + } + + return true; +} + +export function cast( + val: unknown, + constructor?: {new (...args: unknown[]): T}, +): T { + if (!constructor) { + return val as T; + } else if (val instanceof constructor) { + return val; + } + + throw new Error(`${val} not instance of ${constructor}`); +} + +export function forEach( + obj: Record | undefined, + fn: (key: string, val: V) => void, +): void { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn(key, obj[key]); + } + } +} diff --git a/handwritten/firestore/dev/src/v1/firestore_admin_client.ts b/handwritten/firestore/dev/src/v1/firestore_admin_client.ts new file mode 100644 index 00000000000..50570635fa6 --- /dev/null +++ b/handwritten/firestore/dev/src/v1/firestore_admin_client.ts @@ -0,0 +1,6512 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, + LocationsClient, + LocationProtos, +} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../../protos/firestore_admin_v1_proto_api'; +import jsonProtos = require('../../protos/admin_v1.json'); +import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1/firestore_admin_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './firestore_admin_client_config.json'; +const version = require('../../../package.json').version; + +/** + * The Cloud Firestore Admin API. + * + * This API provides several administrative services for Cloud Firestore. + * + * Project, Database, Namespace, Collection, Collection Group, and Document are + * used as defined in the Google Cloud Firestore API. + * + * Operation: An Operation represents work being performed in the background. + * + * The index service manages Cloud Firestore indexes. + * + * Index creation is performed asynchronously. + * An Operation resource is created for each such asynchronous operation. + * The state of the operation (including any errors encountered) + * may be queried via the Operation resource. + * + * The Operations collection provides a record of actions performed for the + * specified Project (including any Operations in progress). Operations are not + * created directly but through calls on other collections or resources. + * + * An Operation that is done may be deleted so that it is no longer listed as + * part of the Operation collection. Operations are garbage collected after + * 30 days. By default, ListOperations will only return in progress and failed + * operations. To list completed operation, issue a ListOperations request with + * the filter `done: true`. + * + * Operations are created by service `FirestoreAdmin`, but are accessed via + * service `google.longrunning.Operations`. + * @class + * @memberof v1 + */ +export class FirestoreAdminClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('firestore-admin'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: {[name: string]: Function}; + locationsClient: LocationsClient; + pathTemplates: {[name: string]: gax.PathTemplate}; + operationsClient: gax.OperationsClient; + firestoreAdminStub?: Promise<{[name: string]: Function}>; + + /** + * Construct an instance of FirestoreAdminClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://cloud.google.com/docs/authentication/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreAdminClient({fallback: true}, gax); + * ``` + */ + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof FirestoreAdminClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); + } + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; + this._servicePath = 'firestore.' + this._universeDomain; + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); + const port = opts?.port || staticMembers.port; + const clientConfig = opts?.clientConfig ?? {}; + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + + // Request numeric enum values if REST transport is used. + opts.numericEnums = true; + + // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. + if (servicePath !== this._servicePath && !('scopes' in opts)) { + opts['scopes'] = staticMembers.scopes; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; + + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + this.locationsClient = new this._gaxModule.LocationsClient( + this._gaxGrpc, + opts, + ); + + // Determine the client header string. + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // This API contains "path templates"; forward-slash-separated + // identifiers to uniquely identify resources within the API. + // Create useful helper objects for these. + this.pathTemplates = { + backupPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/locations/{location}/backups/{backup}', + ), + backupSchedulePathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/databases/{database}/backupSchedules/{backup_schedule}', + ), + collectionGroupPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/databases/{database}/collectionGroups/{collection}', + ), + databasePathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/databases/{database}', + ), + fieldPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}', + ), + indexPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/databases/{database}/collectionGroups/{collection}/indexes/{index}', + ), + locationPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/locations/{location}', + ), + projectPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}', + ), + userCredsPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/databases/{database}/userCreds/{user_creds}', + ), + }; + + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + listIndexes: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'indexes', + ), + listFields: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'fields', + ), + }; + + const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); + // This API contains "long-running operations", which return a + // an Operation object that allows for tracking of the operation, + // rather than holding a request open. + const lroOptions: GrpcClientOptions = { + auth: this.auth, + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, + }; + if (opts.fallback) { + lroOptions.protoJson = protoFilesRoot; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.CancelOperation', + post: '/v1/{name=projects/*/databases/*/operations/*}:cancel', + body: '*', + }, + { + selector: 'google.longrunning.Operations.DeleteOperation', + delete: '/v1/{name=projects/*/databases/*/operations/*}', + }, + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v1/{name=projects/*/databases/*/operations/*}', + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v1/{name=projects/*/databases/*}/operations', + }, + ]; + } + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); + const createIndexResponse = protoFilesRoot.lookup( + '.google.firestore.admin.v1.Index', + ) as gax.protobuf.Type; + const createIndexMetadata = protoFilesRoot.lookup( + '.google.firestore.admin.v1.IndexOperationMetadata', + ) as gax.protobuf.Type; + const updateFieldResponse = protoFilesRoot.lookup( + '.google.firestore.admin.v1.Field', + ) as gax.protobuf.Type; + const updateFieldMetadata = protoFilesRoot.lookup( + '.google.firestore.admin.v1.FieldOperationMetadata', + ) as gax.protobuf.Type; + const exportDocumentsResponse = protoFilesRoot.lookup( + '.google.firestore.admin.v1.ExportDocumentsResponse', + ) as gax.protobuf.Type; + const exportDocumentsMetadata = protoFilesRoot.lookup( + '.google.firestore.admin.v1.ExportDocumentsMetadata', + ) as gax.protobuf.Type; + const importDocumentsResponse = protoFilesRoot.lookup( + '.google.protobuf.Empty', + ) as gax.protobuf.Type; + const importDocumentsMetadata = protoFilesRoot.lookup( + '.google.firestore.admin.v1.ImportDocumentsMetadata', + ) as gax.protobuf.Type; + const bulkDeleteDocumentsResponse = protoFilesRoot.lookup( + '.google.firestore.admin.v1.BulkDeleteDocumentsResponse', + ) as gax.protobuf.Type; + const bulkDeleteDocumentsMetadata = protoFilesRoot.lookup( + '.google.firestore.admin.v1.BulkDeleteDocumentsMetadata', + ) as gax.protobuf.Type; + const createDatabaseResponse = protoFilesRoot.lookup( + '.google.firestore.admin.v1.Database', + ) as gax.protobuf.Type; + const createDatabaseMetadata = protoFilesRoot.lookup( + '.google.firestore.admin.v1.CreateDatabaseMetadata', + ) as gax.protobuf.Type; + const updateDatabaseResponse = protoFilesRoot.lookup( + '.google.firestore.admin.v1.Database', + ) as gax.protobuf.Type; + const updateDatabaseMetadata = protoFilesRoot.lookup( + '.google.firestore.admin.v1.UpdateDatabaseMetadata', + ) as gax.protobuf.Type; + const deleteDatabaseResponse = protoFilesRoot.lookup( + '.google.firestore.admin.v1.Database', + ) as gax.protobuf.Type; + const deleteDatabaseMetadata = protoFilesRoot.lookup( + '.google.firestore.admin.v1.DeleteDatabaseMetadata', + ) as gax.protobuf.Type; + const restoreDatabaseResponse = protoFilesRoot.lookup( + '.google.firestore.admin.v1.Database', + ) as gax.protobuf.Type; + const restoreDatabaseMetadata = protoFilesRoot.lookup( + '.google.firestore.admin.v1.RestoreDatabaseMetadata', + ) as gax.protobuf.Type; + const cloneDatabaseResponse = protoFilesRoot.lookup( + '.google.firestore.admin.v1.Database', + ) as gax.protobuf.Type; + const cloneDatabaseMetadata = protoFilesRoot.lookup( + '.google.firestore.admin.v1.CloneDatabaseMetadata', + ) as gax.protobuf.Type; + + this.descriptors.longrunning = { + createIndex: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + createIndexResponse.decode.bind(createIndexResponse), + createIndexMetadata.decode.bind(createIndexMetadata), + ), + updateField: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + updateFieldResponse.decode.bind(updateFieldResponse), + updateFieldMetadata.decode.bind(updateFieldMetadata), + ), + exportDocuments: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + exportDocumentsResponse.decode.bind(exportDocumentsResponse), + exportDocumentsMetadata.decode.bind(exportDocumentsMetadata), + ), + importDocuments: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + importDocumentsResponse.decode.bind(importDocumentsResponse), + importDocumentsMetadata.decode.bind(importDocumentsMetadata), + ), + bulkDeleteDocuments: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + bulkDeleteDocumentsResponse.decode.bind(bulkDeleteDocumentsResponse), + bulkDeleteDocumentsMetadata.decode.bind(bulkDeleteDocumentsMetadata), + ), + createDatabase: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + createDatabaseResponse.decode.bind(createDatabaseResponse), + createDatabaseMetadata.decode.bind(createDatabaseMetadata), + ), + updateDatabase: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + updateDatabaseResponse.decode.bind(updateDatabaseResponse), + updateDatabaseMetadata.decode.bind(updateDatabaseMetadata), + ), + deleteDatabase: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + deleteDatabaseResponse.decode.bind(deleteDatabaseResponse), + deleteDatabaseMetadata.decode.bind(deleteDatabaseMetadata), + ), + restoreDatabase: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + restoreDatabaseResponse.decode.bind(restoreDatabaseResponse), + restoreDatabaseMetadata.decode.bind(restoreDatabaseMetadata), + ), + cloneDatabase: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + cloneDatabaseResponse.decode.bind(cloneDatabaseResponse), + cloneDatabaseMetadata.decode.bind(cloneDatabaseMetadata), + ), + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.firestore.admin.v1.FirestoreAdmin', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + {'x-goog-api-client': clientHeader.join(' ')}, + ); + + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.firestoreAdminStub) { + return this.firestoreAdminStub; + } + + // Put together the "service stub" for + // google.firestore.admin.v1.FirestoreAdmin. + this.firestoreAdminStub = this._gaxGrpc.createStub( + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.firestore.admin.v1.FirestoreAdmin', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.firestore.admin.v1.FirestoreAdmin, + this._opts, + this._providedCustomServicePath, + ) as Promise<{[method: string]: Function}>; + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const firestoreAdminStubMethods = [ + 'createIndex', + 'listIndexes', + 'getIndex', + 'deleteIndex', + 'getField', + 'updateField', + 'listFields', + 'exportDocuments', + 'importDocuments', + 'bulkDeleteDocuments', + 'createDatabase', + 'getDatabase', + 'listDatabases', + 'updateDatabase', + 'deleteDatabase', + 'createUserCreds', + 'getUserCreds', + 'listUserCreds', + 'enableUserCreds', + 'disableUserCreds', + 'resetUserPassword', + 'deleteUserCreds', + 'getBackup', + 'listBackups', + 'deleteBackup', + 'restoreDatabase', + 'createBackupSchedule', + 'getBackupSchedule', + 'listBackupSchedules', + 'updateBackupSchedule', + 'deleteBackupSchedule', + 'cloneDatabase', + ]; + for (const methodName of firestoreAdminStubMethods) { + const callPromise = this.firestoreAdminStub.then( + stub => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { + throw err; + }, + ); + + const descriptor = + this.descriptors.page[methodName] || + this.descriptors.longrunning[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback, + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.firestoreAdminStub; + } + + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'firestore.googleapis.com'; + } + + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'firestore.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/datastore', + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId( + callback?: Callback, + ): Promise | void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- + /** + * Gets a composite index. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Index|Index}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example
+ * region_tag:firestore_v1_generated_FirestoreAdmin_GetIndex_async + */ + getIndex( + request?: protos.google.firestore.admin.v1.IGetIndexRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | undefined, + {} | undefined, + ] + >; + getIndex( + request: protos.google.firestore.admin.v1.IGetIndexRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, + {} | null | undefined + >, + ): void; + getIndex( + request: protos.google.firestore.admin.v1.IGetIndexRequest, + callback: Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, + {} | null | undefined + >, + ): void; + getIndex( + request?: protos.google.firestore.admin.v1.IGetIndexRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getIndex request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getIndex response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getIndex(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getIndex response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Deletes a composite index. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteIndex_async + */ + deleteIndex( + request?: protos.google.firestore.admin.v1.IDeleteIndexRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | undefined, + {} | undefined, + ] + >; + deleteIndex( + request: protos.google.firestore.admin.v1.IDeleteIndexRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | null | undefined, + {} | null | undefined + >, + ): void; + deleteIndex( + request: protos.google.firestore.admin.v1.IDeleteIndexRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | null | undefined, + {} | null | undefined + >, + ): void; + deleteIndex( + request?: protos.google.firestore.admin.v1.IDeleteIndexRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteIndexRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteIndex request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteIndexRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteIndex response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteIndex(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteIndex response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Gets the metadata and configuration for a Field. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Field|Field}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetField_async + */ + getField( + request?: protos.google.firestore.admin.v1.IGetFieldRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | undefined, + {} | undefined, + ] + >; + getField( + request: protos.google.firestore.admin.v1.IGetFieldRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, + {} | null | undefined + >, + ): void; + getField( + request: protos.google.firestore.admin.v1.IGetFieldRequest, + callback: Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, + {} | null | undefined + >, + ): void; + getField( + request?: protos.google.firestore.admin.v1.IGetFieldRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getField request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getField response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getField(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getField response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Gets information about a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Database|Database}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetDatabase_async + */ + getDatabase( + request?: protos.google.firestore.admin.v1.IGetDatabaseRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | undefined, + {} | undefined, + ] + >; + getDatabase( + request: protos.google.firestore.admin.v1.IGetDatabaseRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | null | undefined, + {} | null | undefined + >, + ): void; + getDatabase( + request: protos.google.firestore.admin.v1.IGetDatabaseRequest, + callback: Callback< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | null | undefined, + {} | null | undefined + >, + ): void; + getDatabase( + request?: protos.google.firestore.admin.v1.IGetDatabaseRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.admin.v1.IDatabase, + | protos.google.firestore.admin.v1.IGetDatabaseRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getDatabase request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IDatabase, + | protos.google.firestore.admin.v1.IGetDatabaseRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getDatabase response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getDatabase(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getDatabase response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * List all the databases in the project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}` + * @param {boolean} request.showDeleted + * If true, also returns deleted resources. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListDatabasesResponse|ListDatabasesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListDatabases_async + */ + listDatabases( + request?: protos.google.firestore.admin.v1.IListDatabasesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | undefined, + {} | undefined, + ] + >; + listDatabases( + request: protos.google.firestore.admin.v1.IListDatabasesRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | null | undefined, + {} | null | undefined + >, + ): void; + listDatabases( + request: protos.google.firestore.admin.v1.IListDatabasesRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | null | undefined, + {} | null | undefined + >, + ): void; + listDatabases( + request?: protos.google.firestore.admin.v1.IListDatabasesRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + | protos.google.firestore.admin.v1.IListDatabasesRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listDatabases request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + | protos.google.firestore.admin.v1.IListDatabasesRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('listDatabases response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .listDatabases(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | undefined, + {} | undefined, + ]) => { + this._log.info('listDatabases response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Create a user creds. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {google.firestore.admin.v1.UserCreds} request.userCreds + * Required. The user creds to create. + * @param {string} request.userCredsId + * Required. The ID to use for the user creds, which will become the final + * component of the user creds's resource name. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateUserCreds_async + */ + createUserCreds( + request?: protos.google.firestore.admin.v1.ICreateUserCredsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.ICreateUserCredsRequest | undefined, + {} | undefined, + ] + >; + createUserCreds( + request: protos.google.firestore.admin.v1.ICreateUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.ICreateUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + createUserCreds( + request: protos.google.firestore.admin.v1.ICreateUserCredsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.ICreateUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + createUserCreds( + request?: protos.google.firestore.admin.v1.ICreateUserCredsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.ICreateUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.ICreateUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.ICreateUserCredsRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('createUserCreds request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.ICreateUserCredsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createUserCreds response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createUserCreds(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.ICreateUserCredsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createUserCreds response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Gets a user creds resource. Note that the returned resource does not + * contain the secret value itself. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetUserCreds_async + */ + getUserCreds( + request?: protos.google.firestore.admin.v1.IGetUserCredsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest | undefined, + {} | undefined, + ] + >; + getUserCreds( + request: protos.google.firestore.admin.v1.IGetUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest | null | undefined, + {} | null | undefined + >, + ): void; + getUserCreds( + request: protos.google.firestore.admin.v1.IGetUserCredsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest | null | undefined, + {} | null | undefined + >, + ): void; + getUserCreds( + request?: protos.google.firestore.admin.v1.IGetUserCredsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IGetUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getUserCreds request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IGetUserCredsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getUserCreds response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getUserCreds(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getUserCreds response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * List all user creds in the database. Note that the returned resource + * does not contain the secret value itself. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent database name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListUserCredsResponse|ListUserCredsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListUserCreds_async + */ + listUserCreds( + request?: protos.google.firestore.admin.v1.IListUserCredsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest | undefined, + {} | undefined, + ] + >; + listUserCreds( + request: protos.google.firestore.admin.v1.IListUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest | null | undefined, + {} | null | undefined + >, + ): void; + listUserCreds( + request: protos.google.firestore.admin.v1.IListUserCredsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest | null | undefined, + {} | null | undefined + >, + ): void; + listUserCreds( + request?: protos.google.firestore.admin.v1.IListUserCredsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.admin.v1.IListUserCredsResponse, + | protos.google.firestore.admin.v1.IListUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listUserCreds request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IListUserCredsResponse, + | protos.google.firestore.admin.v1.IListUserCredsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('listUserCreds response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .listUserCreds(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('listUserCreds response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Enables a user creds. No-op if the user creds are already enabled. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_EnableUserCreds_async + */ + enableUserCreds( + request?: protos.google.firestore.admin.v1.IEnableUserCredsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IEnableUserCredsRequest | undefined, + {} | undefined, + ] + >; + enableUserCreds( + request: protos.google.firestore.admin.v1.IEnableUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IEnableUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + enableUserCreds( + request: protos.google.firestore.admin.v1.IEnableUserCredsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IEnableUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + enableUserCreds( + request?: protos.google.firestore.admin.v1.IEnableUserCredsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IEnableUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IEnableUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IEnableUserCredsRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('enableUserCreds request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IEnableUserCredsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('enableUserCreds response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .enableUserCreds(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IEnableUserCredsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('enableUserCreds response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Disables a user creds. No-op if the user creds are already disabled. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DisableUserCreds_async + */ + disableUserCreds( + request?: protos.google.firestore.admin.v1.IDisableUserCredsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IDisableUserCredsRequest | undefined, + {} | undefined, + ] + >; + disableUserCreds( + request: protos.google.firestore.admin.v1.IDisableUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IDisableUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + disableUserCreds( + request: protos.google.firestore.admin.v1.IDisableUserCredsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IDisableUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + disableUserCreds( + request?: protos.google.firestore.admin.v1.IDisableUserCredsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IDisableUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IDisableUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IDisableUserCredsRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('disableUserCreds request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IDisableUserCredsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('disableUserCreds response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .disableUserCreds(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IDisableUserCredsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('disableUserCreds response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Resets the password of a user creds. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ResetUserPassword_async + */ + resetUserPassword( + request?: protos.google.firestore.admin.v1.IResetUserPasswordRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IResetUserPasswordRequest | undefined, + {} | undefined, + ] + >; + resetUserPassword( + request: protos.google.firestore.admin.v1.IResetUserPasswordRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IResetUserPasswordRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + resetUserPassword( + request: protos.google.firestore.admin.v1.IResetUserPasswordRequest, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IResetUserPasswordRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + resetUserPassword( + request?: protos.google.firestore.admin.v1.IResetUserPasswordRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IResetUserPasswordRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IResetUserPasswordRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IResetUserPasswordRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('resetUserPassword request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IResetUserPasswordRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('resetUserPassword response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .resetUserPassword(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IUserCreds, + ( + | protos.google.firestore.admin.v1.IResetUserPasswordRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('resetUserPassword response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Deletes a user creds. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteUserCreds_async + */ + deleteUserCreds( + request?: protos.google.firestore.admin.v1.IDeleteUserCredsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteUserCredsRequest | undefined, + {} | undefined, + ] + >; + deleteUserCreds( + request: protos.google.firestore.admin.v1.IDeleteUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + deleteUserCreds( + request: protos.google.firestore.admin.v1.IDeleteUserCredsRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + deleteUserCreds( + request?: protos.google.firestore.admin.v1.IDeleteUserCredsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteUserCredsRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteUserCreds request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteUserCredsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteUserCreds response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteUserCreds(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteUserCredsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteUserCreds response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Gets information about a backup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the backup to fetch. + * + * Format is `projects/{project}/locations/{location}/backups/{backup}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Backup|Backup}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackup_async + */ + getBackup( + request?: protos.google.firestore.admin.v1.IGetBackupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | undefined, + {} | undefined, + ] + >; + getBackup( + request: protos.google.firestore.admin.v1.IGetBackupRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, + {} | null | undefined + >, + ): void; + getBackup( + request: protos.google.firestore.admin.v1.IGetBackupRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, + {} | null | undefined + >, + ): void; + getBackup( + request?: protos.google.firestore.admin.v1.IGetBackupRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getBackup request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getBackup response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getBackup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getBackup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Lists all the backups. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The location to list backups from. + * + * Format is `projects/{project}/locations/{location}`. + * Use `{location} = '-'` to list backups from all locations for the given + * project. This allows listing backups from a single location or from all + * locations. + * @param {string} request.filter + * An expression that filters the list of returned backups. + * + * A filter expression consists of a field name, a comparison operator, and a + * value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the {@link protos.google.firestore.admin.v1.Backup|Backup} are + * eligible for filtering: + * + * * `database_uid` (supports `=` only) + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupsResponse|ListBackupsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackups_async + */ + listBackups( + request?: protos.google.firestore.admin.v1.IListBackupsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | undefined, + {} | undefined, + ] + >; + listBackups( + request: protos.google.firestore.admin.v1.IListBackupsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | null | undefined, + {} | null | undefined + >, + ): void; + listBackups( + request: protos.google.firestore.admin.v1.IListBackupsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | null | undefined, + {} | null | undefined + >, + ): void; + listBackups( + request?: protos.google.firestore.admin.v1.IListBackupsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + | protos.google.firestore.admin.v1.IListBackupsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listBackups request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + | protos.google.firestore.admin.v1.IListBackupsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('listBackups response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .listBackups(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('listBackups response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Deletes a backup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the backup to delete. + * + * format is `projects/{project}/locations/{location}/backups/{backup}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackup_async + */ + deleteBackup( + request?: protos.google.firestore.admin.v1.IDeleteBackupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | undefined, + {} | undefined, + ] + >; + deleteBackup( + request: protos.google.firestore.admin.v1.IDeleteBackupRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | null | undefined, + {} | null | undefined + >, + ): void; + deleteBackup( + request: protos.google.firestore.admin.v1.IDeleteBackupRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | null | undefined, + {} | null | undefined + >, + ): void; + deleteBackup( + request?: protos.google.firestore.admin.v1.IDeleteBackupRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteBackup request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteBackup response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteBackup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteBackup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Creates a backup schedule on a database. + * At most two backup schedules can be configured on a database, one daily + * backup schedule and one weekly backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent database. + * + * Format `projects/{project}/databases/{database}` + * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule + * Required. The backup schedule to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateBackupSchedule_async + */ + createBackupSchedule( + request?: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.ICreateBackupScheduleRequest | undefined, + {} | undefined, + ] + >; + createBackupSchedule( + request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + createBackupSchedule( + request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + createBackupSchedule( + request?: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.ICreateBackupScheduleRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('createBackupSchedule request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createBackupSchedule response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createBackupSchedule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IBackupSchedule, + ( + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createBackupSchedule response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Gets information about a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the backup schedule. + * + * Format + * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackupSchedule_async + */ + getBackupSchedule( + request?: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IGetBackupScheduleRequest | undefined, + {} | undefined, + ] + >; + getBackupSchedule( + request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getBackupSchedule( + request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getBackupSchedule( + request?: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IGetBackupScheduleRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getBackupSchedule request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getBackupSchedule response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getBackupSchedule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IBackupSchedule, + ( + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getBackupSchedule response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * List backup schedules. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent database. + * + * Format is `projects/{project}/databases/{database}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupSchedulesResponse|ListBackupSchedulesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackupSchedules_async + */ + listBackupSchedules( + request?: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + protos.google.firestore.admin.v1.IListBackupSchedulesRequest | undefined, + {} | undefined, + ] + >; + listBackupSchedules( + request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + listBackupSchedules( + request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + listBackupSchedules( + request?: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + protos.google.firestore.admin.v1.IListBackupSchedulesRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listBackupSchedules request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('listBackupSchedules response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .listBackupSchedules(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + ( + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('listBackupSchedules response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Updates a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule + * Required. The backup schedule to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The list of fields to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateBackupSchedule_async + */ + updateBackupSchedule( + request?: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest | undefined, + {} | undefined, + ] + >; + updateBackupSchedule( + request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + updateBackupSchedule( + request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + updateBackupSchedule( + request?: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'backup_schedule.name': request.backupSchedule!.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('updateBackupSchedule request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateBackupSchedule response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .updateBackupSchedule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IBackupSchedule, + ( + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateBackupSchedule response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Deletes a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the backup schedule. + * + * Format + * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackupSchedule_async + */ + deleteBackupSchedule( + request?: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest | undefined, + {} | undefined, + ] + >; + deleteBackupSchedule( + request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + deleteBackupSchedule( + request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + deleteBackupSchedule( + request?: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteBackupSchedule request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteBackupSchedule response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteBackupSchedule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteBackupSchedule response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + + /** + * Creates a composite index. This returns a + * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be + * used to track the status of the creation. The metadata for the operation + * will be the type + * {@link protos.google.firestore.admin.v1.IndexOperationMetadata|IndexOperationMetadata}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {google.firestore.admin.v1.Index} request.index + * Required. The composite index to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async + */ + createIndex( + request?: protos.google.firestore.admin.v1.ICreateIndexRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + createIndex( + request: protos.google.firestore.admin.v1.ICreateIndexRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + createIndex( + request: protos.google.firestore.admin.v1.ICreateIndexRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + createIndex( + request?: protos.google.firestore.admin.v1.ICreateIndexRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('createIndex response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('createIndex request %j', request); + return this.innerApiCalls + .createIndex(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createIndex response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `createIndex()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async + */ + async checkCreateIndexProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Index, + protos.google.firestore.admin.v1.IndexOperationMetadata + > + > { + this._log.info('createIndex long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createIndex, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.Index, + protos.google.firestore.admin.v1.IndexOperationMetadata + >; + } + /** + * Updates a field configuration. Currently, field updates apply only to + * single field index configuration. However, calls to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.UpdateField|FirestoreAdmin.UpdateField} + * should provide a field mask to avoid changing any configuration that the + * caller isn't aware of. The field mask should be specified as: `{ paths: + * "index_config" }`. + * + * This call returns a + * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be + * used to track the status of the field update. The metadata for the + * operation will be the type + * {@link protos.google.firestore.admin.v1.FieldOperationMetadata|FieldOperationMetadata}. + * + * To configure the default field settings for the database, use + * the special `Field` with resource name: + * `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.Field} request.field + * Required. The field to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * A mask, relative to the field. If specified, only configuration specified + * by this field_mask will be updated in the field. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async + */ + updateField( + request?: protos.google.firestore.admin.v1.IUpdateFieldRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + updateField( + request: protos.google.firestore.admin.v1.IUpdateFieldRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + updateField( + request: protos.google.firestore.admin.v1.IUpdateFieldRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + updateField( + request?: protos.google.firestore.admin.v1.IUpdateFieldRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'field.name': request.field!.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('updateField response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('updateField request %j', request); + return this.innerApiCalls + .updateField(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('updateField response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `updateField()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async + */ + async checkUpdateFieldProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Field, + protos.google.firestore.admin.v1.FieldOperationMetadata + > + > { + this._log.info('updateField long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.updateField, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.Field, + protos.google.firestore.admin.v1.FieldOperationMetadata + >; + } + /** + * Exports a copy of all or a subset of documents from Google Cloud Firestore + * to another storage system, such as Google Cloud Storage. Recent updates to + * documents may not be reflected in the export. The export occurs in the + * background and its progress can be monitored and managed via the + * Operation resource that is created. The output of an export may only be + * used once the associated operation is done. If an export operation is + * cancelled before completion it may leave partial data behind in Google + * Cloud Storage. + * + * For more details on export behavior and output format, refer to: + * https://cloud.google.com/firestore/docs/manage-data/export-import + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to export. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.collectionIds + * Which collection IDs to export. Unspecified means all collections. Each + * collection ID in this list must be unique. + * @param {string} request.outputUriPrefix + * The output URI. Currently only supports Google Cloud Storage URIs of the + * form: `gs://BUCKET_NAME[/NAMESPACE_PATH]`, where `BUCKET_NAME` is the name + * of the Google Cloud Storage bucket and `NAMESPACE_PATH` is an optional + * Google Cloud Storage namespace path. When + * choosing a name, be sure to consider Google Cloud Storage naming + * guidelines: https://cloud.google.com/storage/docs/naming. + * If the URI is a bucket (without a namespace path), a prefix will be + * generated based on the start time. + * @param {string[]} request.namespaceIds + * An empty list represents all namespaces. This is the preferred + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to include them. Each namespace in this list must be unique. + * @param {google.protobuf.Timestamp} request.snapshotTime + * The timestamp that corresponds to the version of the database to be + * exported. The timestamp must be in the past, rounded to the minute and not + * older than + * {@link protos.google.firestore.admin.v1.Database.earliest_version_time|earliestVersionTime}. + * If specified, then the exported documents will represent a consistent view + * of the database at the provided time. Otherwise, there are no guarantees + * about the consistency of the exported documents. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async + */ + exportDocuments( + request?: protos.google.firestore.admin.v1.IExportDocumentsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + exportDocuments( + request: protos.google.firestore.admin.v1.IExportDocumentsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + exportDocuments( + request: protos.google.firestore.admin.v1.IExportDocumentsRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + exportDocuments( + request?: protos.google.firestore.admin.v1.IExportDocumentsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('exportDocuments response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('exportDocuments request %j', request); + return this.innerApiCalls + .exportDocuments(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('exportDocuments response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `exportDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async + */ + async checkExportDocumentsProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.ExportDocumentsResponse, + protos.google.firestore.admin.v1.ExportDocumentsMetadata + > + > { + this._log.info('exportDocuments long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.exportDocuments, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.ExportDocumentsResponse, + protos.google.firestore.admin.v1.ExportDocumentsMetadata + >; + } + /** + * Imports documents into Google Cloud Firestore. Existing documents with the + * same name are overwritten. The import occurs in the background and its + * progress can be monitored and managed via the Operation resource that is + * created. If an ImportDocuments operation is cancelled, it is possible + * that a subset of the data has already been imported to Cloud Firestore. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to import into. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.collectionIds + * Which collection IDs to import. Unspecified means all collections included + * in the import. Each collection ID in this list must be unique. + * @param {string} request.inputUriPrefix + * Location of the exported files. + * This must match the output_uri_prefix of an ExportDocumentsResponse from + * an export that has completed successfully. + * See: + * {@link protos.google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix|google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix}. + * @param {string[]} request.namespaceIds + * An empty list represents all namespaces. This is the preferred + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to include them. Each namespace in this list must be unique. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async + */ + importDocuments( + request?: protos.google.firestore.admin.v1.IImportDocumentsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + importDocuments( + request: protos.google.firestore.admin.v1.IImportDocumentsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + importDocuments( + request: protos.google.firestore.admin.v1.IImportDocumentsRequest, + callback: Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + importDocuments( + request?: protos.google.firestore.admin.v1.IImportDocumentsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('importDocuments response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('importDocuments request %j', request); + return this.innerApiCalls + .importDocuments(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('importDocuments response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `importDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async + */ + async checkImportDocumentsProgress( + name: string, + ): Promise< + LROperation< + protos.google.protobuf.Empty, + protos.google.firestore.admin.v1.ImportDocumentsMetadata + > + > { + this._log.info('importDocuments long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.importDocuments, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.protobuf.Empty, + protos.google.firestore.admin.v1.ImportDocumentsMetadata + >; + } + /** + * Bulk deletes a subset of documents from Google Cloud Firestore. + * Documents created or updated after the underlying system starts to process + * the request will not be deleted. The bulk delete occurs in the background + * and its progress can be monitored and managed via the Operation resource + * that is created. + * + * For more details on bulk delete behavior, refer to: + * https://cloud.google.com/firestore/docs/manage-data/bulk-delete + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to operate. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} [request.collectionIds] + * Optional. IDs of the collection groups to delete. Unspecified means all + * collection groups. + * + * Each collection group in this list must be unique. + * @param {string[]} [request.namespaceIds] + * Optional. Namespaces to delete. + * + * An empty list means all namespaces. This is the recommended + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to delete from them. + * + * Each namespace in this list must be unique. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async + */ + bulkDeleteDocuments( + request?: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + bulkDeleteDocuments( + request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + bulkDeleteDocuments( + request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + bulkDeleteDocuments( + request?: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('bulkDeleteDocuments response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('bulkDeleteDocuments request %j', request); + return this.innerApiCalls + .bulkDeleteDocuments(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('bulkDeleteDocuments response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `bulkDeleteDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async + */ + async checkBulkDeleteDocumentsProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.BulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.BulkDeleteDocumentsMetadata + > + > { + this._log.info('bulkDeleteDocuments long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.bulkDeleteDocuments, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.BulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.BulkDeleteDocumentsMetadata + >; + } + /** + * Create a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}` + * @param {google.firestore.admin.v1.Database} request.database + * Required. The Database to create. + * @param {string} request.databaseId + * Required. The ID to use for the database, which will become the final + * component of the database's resource name. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * + * "(default)" database ID is also valid. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async + */ + createDatabase( + request?: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + createDatabase( + request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + createDatabase( + request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + createDatabase( + request?: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('createDatabase response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('createDatabase request %j', request); + return this.innerApiCalls + .createDatabase(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createDatabase response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `createDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async + */ + async checkCreateDatabaseProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.CreateDatabaseMetadata + > + > { + this._log.info('createDatabase long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createDatabase, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.CreateDatabaseMetadata + >; + } + /** + * Updates a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.Database} request.database + * Required. The database to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The list of fields to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + */ + updateDatabase( + request?: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + updateDatabase( + request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + updateDatabase( + request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + updateDatabase( + request?: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'database.name': request.database!.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('updateDatabase response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('updateDatabase request %j', request); + return this.innerApiCalls + .updateDatabase(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('updateDatabase response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `updateDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + */ + async checkUpdateDatabaseProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.UpdateDatabaseMetadata + > + > { + this._log.info('updateDatabase long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.updateDatabase, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.UpdateDatabaseMetadata + >; + } + /** + * Deletes a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {string} request.etag + * The current etag of the Database. + * If an etag is provided and does not match the current etag of the database, + * deletion will be blocked and a FAILED_PRECONDITION error will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async + */ + deleteDatabase( + request?: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + deleteDatabase( + request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + deleteDatabase( + request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + deleteDatabase( + request?: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('deleteDatabase response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('deleteDatabase request %j', request); + return this.innerApiCalls + .deleteDatabase(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('deleteDatabase response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `deleteDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async + */ + async checkDeleteDatabaseProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.DeleteDatabaseMetadata + > + > { + this._log.info('deleteDatabase long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.deleteDatabase, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.DeleteDatabaseMetadata + >; + } + /** + * Creates a new database by restoring from an existing backup. + * + * The new database must be in the same cloud region or multi-region location + * as the existing backup. This behaves similar to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.CreateDatabase|FirestoreAdmin.CreateDatabase} + * except instead of creating a new empty database, a new database is created + * with the database type, index configuration, and documents from an existing + * backup. + * + * The {@link protos.google.longrunning.Operation|long-running operation} can be used to + * track the progress of the restore, with the Operation's + * {@link protos.google.longrunning.Operation.metadata|metadata} field type being the + * {@link protos.google.firestore.admin.v1.RestoreDatabaseMetadata|RestoreDatabaseMetadata}. + * The {@link protos.google.longrunning.Operation.response|response} type is the + * {@link protos.google.firestore.admin.v1.Database|Database} if the restore was + * successful. The new database is not readable or writeable until the LRO has + * completed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project to restore the database in. Format is + * `projects/{project_id}`. + * @param {string} request.databaseId + * Required. The ID to use for the database, which will become the final + * component of the database's resource name. This database ID must not be + * associated with an existing database. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * + * "(default)" database ID is also valid. + * @param {string} request.backup + * Required. Backup to restore from. Must be from the same project as the + * parent. + * + * The restored database will be created in the same location as the source + * backup. + * + * Format is: `projects/{project_id}/locations/{location}/backups/{backup}` + * @param {google.firestore.admin.v1.Database.EncryptionConfig} [request.encryptionConfig] + * Optional. Encryption configuration for the restored database. + * + * If this field is not specified, the restored database will use + * the same encryption configuration as the backup, namely + * {@link protos.google.firestore.admin.v1.Database.EncryptionConfig.use_source_encryption|use_source_encryption}. + * @param {number[]} request.tags + * Optional. Immutable. Tags to be bound to the restored database. + * + * The tags should be provided in the format of + * `tagKeys/{tag_key_id} -> tagValues/{tag_value_id}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async + */ + restoreDatabase( + request?: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + restoreDatabase( + request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + restoreDatabase( + request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + restoreDatabase( + request?: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('restoreDatabase response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('restoreDatabase request %j', request); + return this.innerApiCalls + .restoreDatabase(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('restoreDatabase response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `restoreDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async + */ + async checkRestoreDatabaseProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.RestoreDatabaseMetadata + > + > { + this._log.info('restoreDatabase long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.restoreDatabase, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.RestoreDatabaseMetadata + >; + } + /** + * Creates a new database by cloning an existing one. + * + * The new database must be in the same cloud region or multi-region location + * as the existing database. This behaves similar to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.CreateDatabase|FirestoreAdmin.CreateDatabase} + * except instead of creating a new empty database, a new database is created + * with the database type, index configuration, and documents from an existing + * database. + * + * The {@link protos.google.longrunning.Operation|long-running operation} can be used to + * track the progress of the clone, with the Operation's + * {@link protos.google.longrunning.Operation.metadata|metadata} field type being the + * {@link protos.google.firestore.admin.v1.CloneDatabaseMetadata|CloneDatabaseMetadata}. + * The {@link protos.google.longrunning.Operation.response|response} type is the + * {@link protos.google.firestore.admin.v1.Database|Database} if the clone was + * successful. The new database is not readable or writeable until the LRO has + * completed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project to clone the database in. Format is + * `projects/{project_id}`. + * @param {string} request.databaseId + * Required. The ID to use for the database, which will become the final + * component of the database's resource name. This database ID must not be + * associated with an existing database. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * + * "(default)" database ID is also valid. + * @param {google.firestore.admin.v1.PitrSnapshot} request.pitrSnapshot + * Required. Specification of the PITR data to clone from. The source database + * must exist. + * + * The cloned database will be created in the same location as the source + * database. + * @param {google.firestore.admin.v1.Database.EncryptionConfig} [request.encryptionConfig] + * Optional. Encryption configuration for the cloned database. + * + * If this field is not specified, the cloned database will use + * the same encryption configuration as the source database, namely + * {@link protos.google.firestore.admin.v1.Database.EncryptionConfig.use_source_encryption|use_source_encryption}. + * @param {number[]} request.tags + * Optional. Immutable. Tags to be bound to the cloned database. + * + * The tags should be provided in the format of + * `tagKeys/{tag_key_id} -> tagValues/{tag_value_id}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CloneDatabase_async + */ + cloneDatabase( + request?: protos.google.firestore.admin.v1.ICloneDatabaseRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICloneDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + cloneDatabase( + request: protos.google.firestore.admin.v1.ICloneDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICloneDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + cloneDatabase( + request: protos.google.firestore.admin.v1.ICloneDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICloneDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + cloneDatabase( + request?: protos.google.firestore.admin.v1.ICloneDatabaseRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICloneDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICloneDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICloneDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + const routingParameter = {}; + { + const fieldValue = request.pitrSnapshot?.database; + if (fieldValue !== undefined && fieldValue !== null) { + const match = fieldValue + .toString() + .match(RegExp('projects/(?[^/]+)(?:/.*)?')); + if (match) { + const parameterValue = match.groups?.['project_id'] ?? fieldValue; + Object.assign(routingParameter, {project_id: parameterValue}); + } + } + } + { + const fieldValue = request.pitrSnapshot?.database; + if (fieldValue !== undefined && fieldValue !== null) { + const match = fieldValue + .toString() + .match( + RegExp('projects/[^/]+/databases/(?[^/]+)(?:/.*)?'), + ); + if (match) { + const parameterValue = match.groups?.['database_id'] ?? fieldValue; + Object.assign(routingParameter, {database_id: parameterValue}); + } + } + } + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams(routingParameter); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICloneDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('cloneDatabase response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('cloneDatabase request %j', request); + return this.innerApiCalls + .cloneDatabase(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICloneDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('cloneDatabase response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `cloneDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CloneDatabase_async + */ + async checkCloneDatabaseProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.CloneDatabaseMetadata + > + > { + this._log.info('cloneDatabase long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.cloneDatabase, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.CloneDatabaseMetadata + >; + } + /** + * Lists composite indexes. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Index|Index}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listIndexesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listIndexes( + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IIndex[], + protos.google.firestore.admin.v1.IListIndexesRequest | null, + protos.google.firestore.admin.v1.IListIndexesResponse, + ] + >; + listIndexes( + request: protos.google.firestore.admin.v1.IListIndexesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + protos.google.firestore.admin.v1.IListIndexesResponse | null | undefined, + protos.google.firestore.admin.v1.IIndex + >, + ): void; + listIndexes( + request: protos.google.firestore.admin.v1.IListIndexesRequest, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + protos.google.firestore.admin.v1.IListIndexesResponse | null | undefined, + protos.google.firestore.admin.v1.IIndex + >, + ): void; + listIndexes( + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + | protos.google.firestore.admin.v1.IListIndexesResponse + | null + | undefined, + protos.google.firestore.admin.v1.IIndex + >, + callback?: PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + protos.google.firestore.admin.v1.IListIndexesResponse | null | undefined, + protos.google.firestore.admin.v1.IIndex + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IIndex[], + protos.google.firestore.admin.v1.IListIndexesRequest | null, + protos.google.firestore.admin.v1.IListIndexesResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + | protos.google.firestore.admin.v1.IListIndexesResponse + | null + | undefined, + protos.google.firestore.admin.v1.IIndex + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listIndexes values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listIndexes request %j', request); + return this.innerApiCalls + .listIndexes(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.firestore.admin.v1.IIndex[], + protos.google.firestore.admin.v1.IListIndexesRequest | null, + protos.google.firestore.admin.v1.IListIndexesResponse, + ]) => { + this._log.info('listIndexes values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listIndexes`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Index|Index} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listIndexesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listIndexesStream( + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listIndexes']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listIndexes stream %j', request); + return this.descriptors.page.listIndexes.createStream( + this.innerApiCalls.listIndexes as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listIndexes`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.admin.v1.Index|Index}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListIndexes_async + */ + listIndexesAsync( + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listIndexes']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listIndexes iterate %j', request); + return this.descriptors.page.listIndexes.asyncIterate( + this.innerApiCalls['listIndexes'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * Lists the field configuration and metadata for this database. + * + * Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with the filter set to `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Field|Field}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listFieldsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listFields( + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IField[], + protos.google.firestore.admin.v1.IListFieldsRequest | null, + protos.google.firestore.admin.v1.IListFieldsResponse, + ] + >; + listFields( + request: protos.google.firestore.admin.v1.IListFieldsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + protos.google.firestore.admin.v1.IListFieldsResponse | null | undefined, + protos.google.firestore.admin.v1.IField + >, + ): void; + listFields( + request: protos.google.firestore.admin.v1.IListFieldsRequest, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + protos.google.firestore.admin.v1.IListFieldsResponse | null | undefined, + protos.google.firestore.admin.v1.IField + >, + ): void; + listFields( + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + | protos.google.firestore.admin.v1.IListFieldsResponse + | null + | undefined, + protos.google.firestore.admin.v1.IField + >, + callback?: PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + protos.google.firestore.admin.v1.IListFieldsResponse | null | undefined, + protos.google.firestore.admin.v1.IField + >, + ): Promise< + [ + protos.google.firestore.admin.v1.IField[], + protos.google.firestore.admin.v1.IListFieldsRequest | null, + protos.google.firestore.admin.v1.IListFieldsResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + | protos.google.firestore.admin.v1.IListFieldsResponse + | null + | undefined, + protos.google.firestore.admin.v1.IField + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listFields values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listFields request %j', request); + return this.innerApiCalls + .listFields(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.firestore.admin.v1.IField[], + protos.google.firestore.admin.v1.IListFieldsRequest | null, + protos.google.firestore.admin.v1.IListFieldsResponse, + ]) => { + this._log.info('listFields values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listFields`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Field|Field} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listFieldsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listFieldsStream( + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listFields']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listFields stream %j', request); + return this.descriptors.page.listFields.createStream( + this.innerApiCalls.listFields as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listFields`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.admin.v1.Field|Field}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListFields_async + */ + listFieldsAsync( + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listFields']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listFields iterate %j', request); + return this.descriptors.page.listFields.asyncIterate( + this.innerApiCalls['listFields'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * Gets information about a location. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Resource name for the location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html | CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.cloud.location.Location | Location}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * ``` + * const [response] = await client.getLocation(request); + * ``` + */ + getLocation( + request: LocationProtos.google.cloud.location.IGetLocationRequest, + options?: + | gax.CallOptions + | Callback< + LocationProtos.google.cloud.location.ILocation, + | LocationProtos.google.cloud.location.IGetLocationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + LocationProtos.google.cloud.location.ILocation, + | LocationProtos.google.cloud.location.IGetLocationRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise { + return this.locationsClient.getLocation(request, options, callback); + } + + /** + * Lists information about the supported locations for this service. Returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link google.cloud.location.Location | Location}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * ``` + * const iterable = client.listLocationsAsync(request); + * for await (const response of iterable) { + * // process response + * } + * ``` + */ + listLocationsAsync( + request: LocationProtos.google.cloud.location.IListLocationsRequest, + options?: CallOptions, + ): AsyncIterable { + return this.locationsClient.listLocationsAsync(request, options); + } + + /** + * Gets the latest state of a long-running operation. Clients can use this + * method to poll the operation result at intervals as recommended by the API + * service. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} + * for the details. + * @param {function(?Error, ?Object)=} callback + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing + * {@link google.longrunning.Operation | google.longrunning.Operation}. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * {@link google.longrunning.Operation | google.longrunning.Operation}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * const name = ''; + * const [response] = await client.getOperation({name}); + * // doThingsWith(response) + * ``` + */ + getOperation( + request: protos.google.longrunning.GetOperationRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protos.google.longrunning.Operation, + protos.google.longrunning.GetOperationRequest, + {} | null | undefined + >, + callback?: Callback< + protos.google.longrunning.Operation, + protos.google.longrunning.GetOperationRequest, + {} | null | undefined + >, + ): Promise<[protos.google.longrunning.Operation]> { + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + return this.operationsClient.getOperation(request, options, callback); + } + /** + * Lists operations that match the specified filter in the request. If the + * server doesn't support this method, it returns `UNIMPLEMENTED`. Returns an iterable object. + * + * For-await-of syntax is used with the iterable to recursively get response element on-demand. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation collection. + * @param {string} request.filter - The standard list filter. + * @param {number=} request.pageSize - + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} for the + * details. + * @returns {Object} + * An iterable Object that conforms to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | iteration protocols}. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * for await (const response of client.listOperationsAsync(request)); + * // doThingsWith(response) + * ``` + */ + listOperationsAsync( + request: protos.google.longrunning.ListOperationsRequest, + options?: gax.CallOptions, + ): AsyncIterable { + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + return this.operationsClient.listOperationsAsync(request, options); + } + /** + * Starts asynchronous cancellation on a long-running operation. The server + * makes a best effort to cancel the operation, but success is not + * guaranteed. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. Clients can use + * {@link Operations.GetOperation} or + * other methods to check whether the cancellation succeeded or whether the + * operation completed despite cancellation. On successful cancellation, + * the operation is not deleted; instead, it becomes an operation with + * an {@link Operation.error} value with a {@link google.rpc.Status.code} of + * 1, corresponding to `Code.CANCELLED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be cancelled. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} for the + * details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @returns {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.cancelOperation({name: ''}); + * ``` + */ + cancelOperation( + request: protos.google.longrunning.CancelOperationRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protos.google.longrunning.CancelOperationRequest, + protos.google.protobuf.Empty, + {} | undefined | null + >, + callback?: Callback< + protos.google.longrunning.CancelOperationRequest, + protos.google.protobuf.Empty, + {} | undefined | null + >, + ): Promise { + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + return this.operationsClient.cancelOperation(request, options, callback); + } + + /** + * Deletes a long-running operation. This method indicates that the client is + * no longer interested in the operation result. It does not cancel the + * operation. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be deleted. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} + * for the details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @returns {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.deleteOperation({name: ''}); + * ``` + */ + deleteOperation( + request: protos.google.longrunning.DeleteOperationRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protos.google.protobuf.Empty, + protos.google.longrunning.DeleteOperationRequest, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.Empty, + protos.google.longrunning.DeleteOperationRequest, + {} | null | undefined + >, + ): Promise { + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + return this.operationsClient.deleteOperation(request, options, callback); + } + + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified backup resource name string. + * + * @param {string} project + * @param {string} location + * @param {string} backup + * @returns {string} Resource name string. + */ + backupPath(project: string, location: string, backup: string) { + return this.pathTemplates.backupPathTemplate.render({ + project: project, + location: location, + backup: backup, + }); + } + + /** + * Parse the project from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the project. + */ + matchProjectFromBackupName(backupName: string) { + return this.pathTemplates.backupPathTemplate.match(backupName).project; + } + + /** + * Parse the location from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the location. + */ + matchLocationFromBackupName(backupName: string) { + return this.pathTemplates.backupPathTemplate.match(backupName).location; + } + + /** + * Parse the backup from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the backup. + */ + matchBackupFromBackupName(backupName: string) { + return this.pathTemplates.backupPathTemplate.match(backupName).backup; + } + + /** + * Return a fully-qualified backupSchedule resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} backup_schedule + * @returns {string} Resource name string. + */ + backupSchedulePath( + project: string, + database: string, + backupSchedule: string, + ) { + return this.pathTemplates.backupSchedulePathTemplate.render({ + project: project, + database: database, + backup_schedule: backupSchedule, + }); + } + + /** + * Parse the project from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the project. + */ + matchProjectFromBackupScheduleName(backupScheduleName: string) { + return this.pathTemplates.backupSchedulePathTemplate.match( + backupScheduleName, + ).project; + } + + /** + * Parse the database from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromBackupScheduleName(backupScheduleName: string) { + return this.pathTemplates.backupSchedulePathTemplate.match( + backupScheduleName, + ).database; + } + + /** + * Parse the backup_schedule from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the backup_schedule. + */ + matchBackupScheduleFromBackupScheduleName(backupScheduleName: string) { + return this.pathTemplates.backupSchedulePathTemplate.match( + backupScheduleName, + ).backup_schedule; + } + + /** + * Return a fully-qualified collectionGroup resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} collection + * @returns {string} Resource name string. + */ + collectionGroupPath(project: string, database: string, collection: string) { + return this.pathTemplates.collectionGroupPathTemplate.render({ + project: project, + database: database, + collection: collection, + }); + } + + /** + * Parse the project from CollectionGroup resource. + * + * @param {string} collectionGroupName + * A fully-qualified path representing CollectionGroup resource. + * @returns {string} A string representing the project. + */ + matchProjectFromCollectionGroupName(collectionGroupName: string) { + return this.pathTemplates.collectionGroupPathTemplate.match( + collectionGroupName, + ).project; + } + + /** + * Parse the database from CollectionGroup resource. + * + * @param {string} collectionGroupName + * A fully-qualified path representing CollectionGroup resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromCollectionGroupName(collectionGroupName: string) { + return this.pathTemplates.collectionGroupPathTemplate.match( + collectionGroupName, + ).database; + } + + /** + * Parse the collection from CollectionGroup resource. + * + * @param {string} collectionGroupName + * A fully-qualified path representing CollectionGroup resource. + * @returns {string} A string representing the collection. + */ + matchCollectionFromCollectionGroupName(collectionGroupName: string) { + return this.pathTemplates.collectionGroupPathTemplate.match( + collectionGroupName, + ).collection; + } + + /** + * Return a fully-qualified database resource name string. + * + * @param {string} project + * @param {string} database + * @returns {string} Resource name string. + */ + databasePath(project: string, database: string) { + return this.pathTemplates.databasePathTemplate.render({ + project: project, + database: database, + }); + } + + /** + * Parse the project from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the project. + */ + matchProjectFromDatabaseName(databaseName: string) { + return this.pathTemplates.databasePathTemplate.match(databaseName).project; + } + + /** + * Parse the database from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromDatabaseName(databaseName: string) { + return this.pathTemplates.databasePathTemplate.match(databaseName).database; + } + + /** + * Return a fully-qualified field resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} collection + * @param {string} field + * @returns {string} Resource name string. + */ + fieldPath( + project: string, + database: string, + collection: string, + field: string, + ) { + return this.pathTemplates.fieldPathTemplate.render({ + project: project, + database: database, + collection: collection, + field: field, + }); + } + + /** + * Parse the project from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the project. + */ + matchProjectFromFieldName(fieldName: string) { + return this.pathTemplates.fieldPathTemplate.match(fieldName).project; + } + + /** + * Parse the database from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromFieldName(fieldName: string) { + return this.pathTemplates.fieldPathTemplate.match(fieldName).database; + } + + /** + * Parse the collection from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the collection. + */ + matchCollectionFromFieldName(fieldName: string) { + return this.pathTemplates.fieldPathTemplate.match(fieldName).collection; + } + + /** + * Parse the field from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the field. + */ + matchFieldFromFieldName(fieldName: string) { + return this.pathTemplates.fieldPathTemplate.match(fieldName).field; + } + + /** + * Return a fully-qualified index resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} collection + * @param {string} index + * @returns {string} Resource name string. + */ + indexPath( + project: string, + database: string, + collection: string, + index: string, + ) { + return this.pathTemplates.indexPathTemplate.render({ + project: project, + database: database, + collection: collection, + index: index, + }); + } + + /** + * Parse the project from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the project. + */ + matchProjectFromIndexName(indexName: string) { + return this.pathTemplates.indexPathTemplate.match(indexName).project; + } + + /** + * Parse the database from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromIndexName(indexName: string) { + return this.pathTemplates.indexPathTemplate.match(indexName).database; + } + + /** + * Parse the collection from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the collection. + */ + matchCollectionFromIndexName(indexName: string) { + return this.pathTemplates.indexPathTemplate.match(indexName).collection; + } + + /** + * Parse the index from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the index. + */ + matchIndexFromIndexName(indexName: string) { + return this.pathTemplates.indexPathTemplate.match(indexName).index; + } + + /** + * Return a fully-qualified location resource name string. + * + * @param {string} project + * @param {string} location + * @returns {string} Resource name string. + */ + locationPath(project: string, location: string) { + return this.pathTemplates.locationPathTemplate.render({ + project: project, + location: location, + }); + } + + /** + * Parse the project from Location resource. + * + * @param {string} locationName + * A fully-qualified path representing Location resource. + * @returns {string} A string representing the project. + */ + matchProjectFromLocationName(locationName: string) { + return this.pathTemplates.locationPathTemplate.match(locationName).project; + } + + /** + * Parse the location from Location resource. + * + * @param {string} locationName + * A fully-qualified path representing Location resource. + * @returns {string} A string representing the location. + */ + matchLocationFromLocationName(locationName: string) { + return this.pathTemplates.locationPathTemplate.match(locationName).location; + } + + /** + * Return a fully-qualified project resource name string. + * + * @param {string} project + * @returns {string} Resource name string. + */ + projectPath(project: string) { + return this.pathTemplates.projectPathTemplate.render({ + project: project, + }); + } + + /** + * Parse the project from Project resource. + * + * @param {string} projectName + * A fully-qualified path representing Project resource. + * @returns {string} A string representing the project. + */ + matchProjectFromProjectName(projectName: string) { + return this.pathTemplates.projectPathTemplate.match(projectName).project; + } + + /** + * Return a fully-qualified userCreds resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} user_creds + * @returns {string} Resource name string. + */ + userCredsPath(project: string, database: string, userCreds: string) { + return this.pathTemplates.userCredsPathTemplate.render({ + project: project, + database: database, + user_creds: userCreds, + }); + } + + /** + * Parse the project from UserCreds resource. + * + * @param {string} userCredsName + * A fully-qualified path representing UserCreds resource. + * @returns {string} A string representing the project. + */ + matchProjectFromUserCredsName(userCredsName: string) { + return this.pathTemplates.userCredsPathTemplate.match(userCredsName) + .project; + } + + /** + * Parse the database from UserCreds resource. + * + * @param {string} userCredsName + * A fully-qualified path representing UserCreds resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromUserCredsName(userCredsName: string) { + return this.pathTemplates.userCredsPathTemplate.match(userCredsName) + .database; + } + + /** + * Parse the user_creds from UserCreds resource. + * + * @param {string} userCredsName + * A fully-qualified path representing UserCreds resource. + * @returns {string} A string representing the user_creds. + */ + matchUserCredsFromUserCredsName(userCredsName: string) { + return this.pathTemplates.userCredsPathTemplate.match(userCredsName) + .user_creds; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.firestoreAdminStub && !this._terminated) { + return this.firestoreAdminStub.then(stub => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + this.locationsClient.close().catch(err => { + throw err; + }); + void this.operationsClient.close(); + }); + } + return Promise.resolve(); + } +} diff --git a/handwritten/firestore/dev/src/v1/firestore_admin_client_config.json b/handwritten/firestore/dev/src/v1/firestore_admin_client_config.json new file mode 100644 index 00000000000..101263bf124 --- /dev/null +++ b/handwritten/firestore/dev/src/v1/firestore_admin_client_config.json @@ -0,0 +1,172 @@ +{ + "interfaces": { + "google.firestore.admin.v1.FirestoreAdmin": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ], + "deadline_exceeded_internal_unavailable": [ + "DEADLINE_EXCEEDED", + "INTERNAL", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "CreateIndex": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListIndexes": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_internal_unavailable", + "retry_params_name": "default" + }, + "GetIndex": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_internal_unavailable", + "retry_params_name": "default" + }, + "DeleteIndex": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_internal_unavailable", + "retry_params_name": "default" + }, + "GetField": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_internal_unavailable", + "retry_params_name": "default" + }, + "UpdateField": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListFields": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_internal_unavailable", + "retry_params_name": "default" + }, + "ExportDocuments": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ImportDocuments": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "BulkDeleteDocuments": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "CreateDatabase": { + "timeout_millis": 120000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetDatabase": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListDatabases": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "UpdateDatabase": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DeleteDatabase": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "CreateUserCreds": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetUserCreds": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListUserCreds": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "EnableUserCreds": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DisableUserCreds": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ResetUserPassword": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DeleteUserCreds": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetBackup": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListBackups": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DeleteBackup": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "RestoreDatabase": { + "timeout_millis": 120000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "CreateBackupSchedule": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetBackupSchedule": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListBackupSchedules": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "UpdateBackupSchedule": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DeleteBackupSchedule": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "CloneDatabase": { + "timeout_millis": 120000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/handwritten/firestore/dev/src/v1/firestore_admin_proto_list.json b/handwritten/firestore/dev/src/v1/firestore_admin_proto_list.json new file mode 100644 index 00000000000..72095b1e714 --- /dev/null +++ b/handwritten/firestore/dev/src/v1/firestore_admin_proto_list.json @@ -0,0 +1,12 @@ +[ + "../../protos/google/firestore/admin/v1/backup.proto", + "../../protos/google/firestore/admin/v1/database.proto", + "../../protos/google/firestore/admin/v1/field.proto", + "../../protos/google/firestore/admin/v1/firestore_admin.proto", + "../../protos/google/firestore/admin/v1/index.proto", + "../../protos/google/firestore/admin/v1/location.proto", + "../../protos/google/firestore/admin/v1/operation.proto", + "../../protos/google/firestore/admin/v1/schedule.proto", + "../../protos/google/firestore/admin/v1/snapshot.proto", + "../../protos/google/firestore/admin/v1/user_creds.proto" +] diff --git a/handwritten/firestore/dev/src/v1/firestore_client.ts b/handwritten/firestore/dev/src/v1/firestore_client.ts new file mode 100644 index 00000000000..9429a2d62f5 --- /dev/null +++ b/handwritten/firestore/dev/src/v1/firestore_client.ts @@ -0,0 +1,2907 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, + LocationsClient, + LocationProtos, +} from 'google-gax'; +import {Transform, PassThrough} from 'stream'; +import * as protos from '../../protos/firestore_v1_proto_api'; +import jsonProtos = require('../../protos/v1.json'); +import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1/firestore_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './firestore_client_config.json'; +const version = require('../../../package.json').version; + +/** + * 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. + * @class + * @memberof v1 + */ +export class FirestoreClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('firestore'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: {[name: string]: Function}; + locationsClient: LocationsClient; + firestoreStub?: Promise<{[name: string]: Function}>; + + /** + * Construct an instance of FirestoreClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://cloud.google.com/docs/authentication/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreClient({fallback: true}, gax); + * ``` + */ + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof FirestoreClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); + } + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; + this._servicePath = 'firestore.' + this._universeDomain; + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); + const port = opts?.port || staticMembers.port; + const clientConfig = opts?.clientConfig ?? {}; + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + + // Request numeric enum values if REST transport is used. + opts.numericEnums = true; + + // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. + if (servicePath !== this._servicePath && !('scopes' in opts)) { + opts['scopes'] = staticMembers.scopes; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; + + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + this.locationsClient = new this._gaxModule.LocationsClient( + this._gaxGrpc, + opts, + ); + + // Determine the client header string. + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + listDocuments: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'documents', + ), + partitionQuery: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'partitions', + ), + listCollectionIds: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'collectionIds', + ), + }; + + // Some of the methods on this service provide streaming responses. + // Provide descriptors for these. + this.descriptors.stream = { + batchGetDocuments: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + runQuery: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + executePipeline: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + runAggregationQuery: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + write: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + listen: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.firestore.v1.Firestore', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + {'x-goog-api-client': clientHeader.join(' ')}, + ); + + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.firestoreStub) { + return this.firestoreStub; + } + + // Put together the "service stub" for + // google.firestore.v1.Firestore. + this.firestoreStub = this._gaxGrpc.createStub( + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.firestore.v1.Firestore', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.firestore.v1.Firestore, + this._opts, + this._providedCustomServicePath, + ) as Promise<{[method: string]: Function}>; + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const firestoreStubMethods = [ + 'getDocument', + 'listDocuments', + 'updateDocument', + 'deleteDocument', + 'batchGetDocuments', + 'beginTransaction', + 'commit', + 'rollback', + 'runQuery', + 'executePipeline', + 'runAggregationQuery', + 'partitionQuery', + 'write', + 'listen', + 'listCollectionIds', + 'batchWrite', + 'createDocument', + ]; + for (const methodName of firestoreStubMethods) { + const callPromise = this.firestoreStub.then( + stub => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({objectMode: true}); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { + throw err; + }, + ); + + const descriptor = + this.descriptors.page[methodName] || + this.descriptors.stream[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback, + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.firestoreStub; + } + + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'firestore.googleapis.com'; + } + + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'firestore.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/datastore', + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId( + callback?: Callback, + ): Promise | void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- + /** + * Gets a single document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to get. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1.DocumentMask} request.mask + * 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. + * @param {Buffer} request.transaction + * Reads the document in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_GetDocument_async + */ + getDocument( + request?: protos.google.firestore.v1.IGetDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | undefined, + {} | undefined, + ] + >; + getDocument( + request: protos.google.firestore.v1.IGetDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + getDocument( + request: protos.google.firestore.v1.IGetDocumentRequest, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + getDocument( + request?: protos.google.firestore.v1.IGetDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getDocument request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getDocument response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Updates or inserts a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.v1.Document} request.document + * Required. The updated document. + * Creates the document if it does not already exist. + * @param {google.firestore.v1.DocumentMask} request.updateMask + * 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. + * @param {google.firestore.v1.DocumentMask} request.mask + * 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. + * @param {google.firestore.v1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_UpdateDocument_async + */ + updateDocument( + request?: protos.google.firestore.v1.IUpdateDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | undefined, + {} | undefined, + ] + >; + updateDocument( + request: protos.google.firestore.v1.IUpdateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + updateDocument( + request: protos.google.firestore.v1.IUpdateDocumentRequest, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + updateDocument( + request?: protos.google.firestore.v1.IUpdateDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'document.name': request.document!.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('updateDocument request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateDocument response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .updateDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Deletes a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to delete. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_DeleteDocument_async + */ + deleteDocument( + request?: protos.google.firestore.v1.IDeleteDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | undefined, + {} | undefined, + ] + >; + deleteDocument( + request: protos.google.firestore.v1.IDeleteDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + deleteDocument( + request: protos.google.firestore.v1.IDeleteDocumentRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + deleteDocument( + request?: protos.google.firestore.v1.IDeleteDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteDocument request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteDocument response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Starts a new transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {google.firestore.v1.TransactionOptions} request.options + * The options for the transaction. + * Defaults to a read-write transaction. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.BeginTransactionResponse|BeginTransactionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_BeginTransaction_async + */ + beginTransaction( + request?: protos.google.firestore.v1.IBeginTransactionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | undefined, + {} | undefined, + ] + >; + beginTransaction( + request: protos.google.firestore.v1.IBeginTransactionRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | null | undefined, + {} | null | undefined + >, + ): void; + beginTransaction( + request: protos.google.firestore.v1.IBeginTransactionRequest, + callback: Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | null | undefined, + {} | null | undefined + >, + ): void; + beginTransaction( + request?: protos.google.firestore.v1.IBeginTransactionRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + | protos.google.firestore.v1.IBeginTransactionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('beginTransaction request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + | protos.google.firestore.v1.IBeginTransactionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('beginTransaction response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .beginTransaction(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('beginTransaction response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Commits a transaction, while optionally updating documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * The writes to apply. + * + * Always executed atomically and in order. + * @param {Buffer} request.transaction + * If set, applies all writes in this transaction, and commits it. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.CommitResponse|CommitResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_Commit_async + */ + commit( + request?: protos.google.firestore.v1.ICommitRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | undefined, + {} | undefined, + ] + >; + commit( + request: protos.google.firestore.v1.ICommitRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | null | undefined, + {} | null | undefined + >, + ): void; + commit( + request: protos.google.firestore.v1.ICommitRequest, + callback: Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | null | undefined, + {} | null | undefined + >, + ): void; + commit( + request?: protos.google.firestore.v1.ICommitRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('commit request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('commit response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .commit(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | undefined, + {} | undefined, + ]) => { + this._log.info('commit response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Rolls back a transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {Buffer} request.transaction + * Required. The transaction to roll back. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_Rollback_async + */ + rollback( + request?: protos.google.firestore.v1.IRollbackRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | undefined, + {} | undefined, + ] + >; + rollback( + request: protos.google.firestore.v1.IRollbackRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + ): void; + rollback( + request: protos.google.firestore.v1.IRollbackRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + ): void; + rollback( + request?: protos.google.firestore.v1.IRollbackRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('rollback request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('rollback response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .rollback(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | undefined, + {} | undefined, + ]) => { + this._log.info('rollback response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * 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 + * {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse} for the + * success status of each write. + * + * If you require an atomically applied set of writes, use + * {@link protos.google.firestore.v1.Firestore.Commit|Commit} instead. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * 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. + * @param {number[]} request.labels + * Labels associated with this batch write. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_BatchWrite_async + */ + batchWrite( + request?: protos.google.firestore.v1.IBatchWriteRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | undefined, + {} | undefined, + ] + >; + batchWrite( + request: protos.google.firestore.v1.IBatchWriteRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | null | undefined, + {} | null | undefined + >, + ): void; + batchWrite( + request: protos.google.firestore.v1.IBatchWriteRequest, + callback: Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | null | undefined, + {} | null | undefined + >, + ): void; + batchWrite( + request?: protos.google.firestore.v1.IBatchWriteRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('batchWrite request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('batchWrite response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .batchWrite(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | undefined, + {} | undefined, + ]) => { + this._log.info('batchWrite response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Creates a new document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource. For example: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: + * `chatrooms`. + * @param {string} request.documentId + * The client-assigned document ID to use for this document. + * + * Optional. If not specified, an ID will be assigned by the service. + * @param {google.firestore.v1.Document} request.document + * Required. The document to create. `name` must not be set. + * @param {google.firestore.v1.DocumentMask} request.mask + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_CreateDocument_async + */ + createDocument( + request?: protos.google.firestore.v1.ICreateDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | undefined, + {} | undefined, + ] + >; + createDocument( + request: protos.google.firestore.v1.ICreateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + createDocument( + request: protos.google.firestore.v1.ICreateDocumentRequest, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + createDocument( + request?: protos.google.firestore.v1.ICreateDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + collection_id: request.collectionId?.toString() ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('createDocument request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createDocument response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + + /** + * Gets multiple documents. + * + * Documents returned by this method are not guaranteed to be returned in the + * same order that they were requested. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.documents + * 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. + * @param {google.firestore.v1.DocumentMask} request.mask + * 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. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * 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. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_BatchGetDocuments_async + */ + batchGetDocuments( + request?: protos.google.firestore.v1.IBatchGetDocumentsRequest, + options?: CallOptions, + ): gax.CancellableStream { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('batchGetDocuments stream %j', options); + return this.innerApiCalls.batchGetDocuments(request, options); + } + + /** + * Runs a query. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * @param {Buffer} request.transaction + * Run the query within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * 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. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] + * Optional. Explain options for the query. If set, additional query + * statistics will be returned. If not, only query results will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.RunQueryResponse|RunQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_RunQuery_async + */ + runQuery( + request?: protos.google.firestore.v1.IRunQueryRequest, + options?: CallOptions, + ): gax.CancellableStream { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('runQuery stream %j', options); + return this.innerApiCalls.runQuery(request, options); + } + + /** + * Executes a pipeline query. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. Database identifier, in the form + * `projects/{project}/databases/{database}`. + * @param {google.firestore.v1.StructuredPipeline} request.structuredPipeline + * A pipelined operation. + * @param {Buffer} request.transaction + * Run the query within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * 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. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.ExecutePipelineResponse|ExecutePipelineResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_ExecutePipeline_async + */ + executePipeline( + request?: protos.google.firestore.v1.IExecutePipelineRequest, + options?: CallOptions, + ): gax.CancellableStream { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + const routingParameter = {}; + { + const fieldValue = request.database; + if (fieldValue !== undefined && fieldValue !== null) { + const match = fieldValue + .toString() + .match(RegExp('projects/(?[^/]+)(?:/.*)?')); + if (match) { + const parameterValue = match.groups?.['project_id'] ?? fieldValue; + Object.assign(routingParameter, {project_id: parameterValue}); + } + } + } + { + const fieldValue = request.database; + if (fieldValue !== undefined && fieldValue !== null) { + const match = fieldValue + .toString() + .match( + RegExp('projects/[^/]+/databases/(?[^/]+)(?:/.*)?'), + ); + if (match) { + const parameterValue = match.groups?.['database_id'] ?? fieldValue; + Object.assign(routingParameter, {database_id: parameterValue}); + } + } + } + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams(routingParameter); + this.initialize().catch(err => { + throw err; + }); + this._log.info('executePipeline stream %j', options); + return this.innerApiCalls.executePipeline(request, options); + } + + /** + * Runs an aggregation query. + * + * Rather than producing {@link protos.google.firestore.v1.Document|Document} results like + * {@link protos.google.firestore.v1.Firestore.RunQuery|Firestore.RunQuery}, this API + * allows running an aggregation to produce a series of + * {@link protos.google.firestore.v1.AggregationResult|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 ); + * ``` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {google.firestore.v1.StructuredAggregationQuery} request.structuredAggregationQuery + * An aggregation query. + * @param {Buffer} request.transaction + * Run the aggregation within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * 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. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] + * Optional. Explain options for the query. If set, additional query + * statistics will be returned. If not, only query results will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.RunAggregationQueryResponse|RunAggregationQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_RunAggregationQuery_async + */ + runAggregationQuery( + request?: protos.google.firestore.v1.IRunAggregationQueryRequest, + options?: CallOptions, + ): gax.CancellableStream { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('runAggregationQuery stream %j', options); + return this.innerApiCalls.runAggregationQuery(request, options); + } + + /** + * Streams batches of document updates and deletes, in order. This method is + * only available via gRPC or WebChannel (not REST). + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1.WriteRequest|WriteRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1.WriteResponse|WriteResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_Write_async + */ + write(options?: CallOptions): gax.CancellableStream { + this.initialize().catch(err => { + throw err; + }); + this._log.info('write stream %j', options); + return this.innerApiCalls.write(null, options); + } + + /** + * Listens to changes. This method is only available via gRPC or WebChannel + * (not REST). + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1.ListenRequest|ListenRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1.ListenResponse|ListenResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_Listen_async + */ + listen(options?: CallOptions): gax.CancellableStream { + this.initialize().catch(err => { + throw err; + }); + this._log.info('listen stream %j', options); + return this.innerApiCalls.listen(null, options); + } + + /** + * Lists documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {string} [request.collectionId] + * 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`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * 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. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * 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. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {boolean} request.showMissing + * 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, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1.Document|Document}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocuments( + request?: protos.google.firestore.v1.IListDocumentsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1.IDocument[], + protos.google.firestore.v1.IListDocumentsRequest | null, + protos.google.firestore.v1.IListDocumentsResponse, + ] + >; + listDocuments( + request: protos.google.firestore.v1.IListDocumentsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1.IDocument + >, + ): void; + listDocuments( + request: protos.google.firestore.v1.IListDocumentsRequest, + callback: PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1.IDocument + >, + ): void; + listDocuments( + request?: protos.google.firestore.v1.IListDocumentsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1.IDocument + >, + callback?: PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1.IDocument + >, + ): Promise< + [ + protos.google.firestore.v1.IDocument[], + protos.google.firestore.v1.IListDocumentsRequest | null, + protos.google.firestore.v1.IListDocumentsResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + collection_id: request.collectionId?.toString() ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1.IDocument + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listDocuments values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listDocuments request %j', request); + return this.innerApiCalls + .listDocuments(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.firestore.v1.IDocument[], + protos.google.firestore.v1.IListDocumentsRequest | null, + protos.google.firestore.v1.IListDocumentsResponse, + ]) => { + this._log.info('listDocuments values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listDocuments`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {string} [request.collectionId] + * 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`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * 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. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * 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. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {boolean} request.showMissing + * 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, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1.Document|Document} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocumentsStream( + request?: protos.google.firestore.v1.IListDocumentsRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + collection_id: request.collectionId?.toString() ?? '', + }); + const defaultCallSettings = this._defaults['listDocuments']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listDocuments stream %j', request); + return this.descriptors.page.listDocuments.createStream( + this.innerApiCalls.listDocuments as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listDocuments`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {string} [request.collectionId] + * 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`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * 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. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * 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. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {boolean} request.showMissing + * 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, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1.Document|Document}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_ListDocuments_async + */ + listDocumentsAsync( + request?: protos.google.firestore.v1.IListDocumentsRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + collection_id: request.collectionId?.toString() ?? '', + }); + const defaultCallSettings = this._defaults['listDocuments']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listDocuments iterate %j', request); + return this.descriptors.page.listDocuments.asyncIterate( + this.innerApiCalls['listDocuments'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * 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. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * 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. + * @param {number} request.partitionCount + * 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. + * @param {string} request.pageToken + * 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 + * @param {number} request.pageSize + * 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`. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1.Cursor|Cursor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQuery( + request?: protos.google.firestore.v1.IPartitionQueryRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1.ICursor[], + protos.google.firestore.v1.IPartitionQueryRequest | null, + protos.google.firestore.v1.IPartitionQueryResponse, + ] + >; + partitionQuery( + request: protos.google.firestore.v1.IPartitionQueryRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, + protos.google.firestore.v1.ICursor + >, + ): void; + partitionQuery( + request: protos.google.firestore.v1.IPartitionQueryRequest, + callback: PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, + protos.google.firestore.v1.ICursor + >, + ): void; + partitionQuery( + request?: protos.google.firestore.v1.IPartitionQueryRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, + protos.google.firestore.v1.ICursor + >, + callback?: PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, + protos.google.firestore.v1.ICursor + >, + ): Promise< + [ + protos.google.firestore.v1.ICursor[], + protos.google.firestore.v1.IPartitionQueryRequest | null, + protos.google.firestore.v1.IPartitionQueryResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, + protos.google.firestore.v1.ICursor + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('partitionQuery values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('partitionQuery request %j', request); + return this.innerApiCalls + .partitionQuery(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.firestore.v1.ICursor[], + protos.google.firestore.v1.IPartitionQueryRequest | null, + protos.google.firestore.v1.IPartitionQueryResponse, + ]) => { + this._log.info('partitionQuery values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `partitionQuery`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * 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. + * @param {number} request.partitionCount + * 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. + * @param {string} request.pageToken + * 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 + * @param {number} request.pageSize + * 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`. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1.Cursor|Cursor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQueryStream( + request?: protos.google.firestore.v1.IPartitionQueryRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['partitionQuery']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('partitionQuery stream %j', request); + return this.descriptors.page.partitionQuery.createStream( + this.innerApiCalls.partitionQuery as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `partitionQuery`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * 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. + * @param {number} request.partitionCount + * 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. + * @param {string} request.pageToken + * 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 + * @param {number} request.pageSize + * 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`. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1.Cursor|Cursor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_PartitionQuery_async + */ + partitionQueryAsync( + request?: protos.google.firestore.v1.IPartitionQueryRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['partitionQuery']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('partitionQuery iterate %j', request); + return this.descriptors.page.partitionQuery.asyncIterate( + this.innerApiCalls['partitionQuery'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * Lists all the collection IDs underneath a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of string. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIds( + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + options?: CallOptions, + ): Promise< + [ + string[], + protos.google.firestore.v1.IListCollectionIdsRequest | null, + protos.google.firestore.v1.IListCollectionIdsResponse, + ] + >; + listCollectionIds( + request: protos.google.firestore.v1.IListCollectionIdsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + protos.google.firestore.v1.IListCollectionIdsResponse | null | undefined, + string + >, + ): void; + listCollectionIds( + request: protos.google.firestore.v1.IListCollectionIdsRequest, + callback: PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + protos.google.firestore.v1.IListCollectionIdsResponse | null | undefined, + string + >, + ): void; + listCollectionIds( + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + | protos.google.firestore.v1.IListCollectionIdsResponse + | null + | undefined, + string + >, + callback?: PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + protos.google.firestore.v1.IListCollectionIdsResponse | null | undefined, + string + >, + ): Promise< + [ + string[], + protos.google.firestore.v1.IListCollectionIdsRequest | null, + protos.google.firestore.v1.IListCollectionIdsResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + | protos.google.firestore.v1.IListCollectionIdsResponse + | null + | undefined, + string + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listCollectionIds values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listCollectionIds request %j', request); + return this.innerApiCalls + .listCollectionIds(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + string[], + protos.google.firestore.v1.IListCollectionIdsRequest | null, + protos.google.firestore.v1.IListCollectionIdsResponse, + ]) => { + this._log.info('listCollectionIds values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listCollectionIds`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing string on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIdsStream( + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listCollectionIds']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listCollectionIds stream %j', request); + return this.descriptors.page.listCollectionIds.createStream( + this.innerApiCalls.listCollectionIds as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listCollectionIds`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * string. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_ListCollectionIds_async + */ + listCollectionIdsAsync( + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listCollectionIds']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listCollectionIds iterate %j', request); + return this.descriptors.page.listCollectionIds.asyncIterate( + this.innerApiCalls['listCollectionIds'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * Gets information about a location. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Resource name for the location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html | CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.cloud.location.Location | Location}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * ``` + * const [response] = await client.getLocation(request); + * ``` + */ + getLocation( + request: LocationProtos.google.cloud.location.IGetLocationRequest, + options?: + | gax.CallOptions + | Callback< + LocationProtos.google.cloud.location.ILocation, + | LocationProtos.google.cloud.location.IGetLocationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + LocationProtos.google.cloud.location.ILocation, + | LocationProtos.google.cloud.location.IGetLocationRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise { + return this.locationsClient.getLocation(request, options, callback); + } + + /** + * Lists information about the supported locations for this service. Returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link google.cloud.location.Location | Location}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * ``` + * const iterable = client.listLocationsAsync(request); + * for await (const response of iterable) { + * // process response + * } + * ``` + */ + listLocationsAsync( + request: LocationProtos.google.cloud.location.IListLocationsRequest, + options?: CallOptions, + ): AsyncIterable { + return this.locationsClient.listLocationsAsync(request, options); + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.firestoreStub && !this._terminated) { + return this.firestoreStub.then(stub => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + this.locationsClient.close().catch(err => { + throw err; + }); + }); + } + return Promise.resolve(); + } +} diff --git a/handwritten/firestore/dev/src/v1/firestore_client_config.json b/handwritten/firestore/dev/src/v1/firestore_client_config.json new file mode 100644 index 00000000000..47cbabb9091 --- /dev/null +++ b/handwritten/firestore/dev/src/v1/firestore_client_config.json @@ -0,0 +1,126 @@ +{ + "interfaces": { + "google.firestore.v1.Firestore": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ], + "deadline_exceeded_resource_exhausted_internal_unavailable": [ + "DEADLINE_EXCEEDED", + "RESOURCE_EXHAUSTED", + "INTERNAL", + "UNAVAILABLE" + ], + "resource_exhausted_unavailable": [ + "RESOURCE_EXHAUSTED", + "UNAVAILABLE" + ], + "resource_exhausted_aborted_unavailable": [ + "RESOURCE_EXHAUSTED", + "ABORTED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "GetDocument": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "ListDocuments": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "UpdateDocument": { + "timeout_millis": 60000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "default" + }, + "DeleteDocument": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "BatchGetDocuments": { + "timeout_millis": 300000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "BeginTransaction": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "Commit": { + "timeout_millis": 60000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "default" + }, + "Rollback": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "RunQuery": { + "timeout_millis": 300000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "ExecutePipeline": { + "timeout_millis": 300000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "RunAggregationQuery": { + "timeout_millis": 300000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "PartitionQuery": { + "timeout_millis": 300000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "Write": { + "timeout_millis": 86400000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Listen": { + "timeout_millis": 86400000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "ListCollectionIds": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "BatchWrite": { + "timeout_millis": 60000, + "retry_codes_name": "resource_exhausted_aborted_unavailable", + "retry_params_name": "default" + }, + "CreateDocument": { + "timeout_millis": 60000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "default" + } + } + } + } +} diff --git a/handwritten/firestore/dev/src/v1/firestore_proto_list.json b/handwritten/firestore/dev/src/v1/firestore_proto_list.json new file mode 100644 index 00000000000..6b67f4f4954 --- /dev/null +++ b/handwritten/firestore/dev/src/v1/firestore_proto_list.json @@ -0,0 +1,12 @@ +[ + "../../protos/google/firestore/v1/aggregation_result.proto", + "../../protos/google/firestore/v1/bloom_filter.proto", + "../../protos/google/firestore/v1/common.proto", + "../../protos/google/firestore/v1/document.proto", + "../../protos/google/firestore/v1/explain_stats.proto", + "../../protos/google/firestore/v1/firestore.proto", + "../../protos/google/firestore/v1/pipeline.proto", + "../../protos/google/firestore/v1/query.proto", + "../../protos/google/firestore/v1/query_profile.proto", + "../../protos/google/firestore/v1/write.proto" +] diff --git a/handwritten/firestore/dev/src/v1/gapic_metadata.json b/handwritten/firestore/dev/src/v1/gapic_metadata.json new file mode 100644 index 00000000000..700dcb2c480 --- /dev/null +++ b/handwritten/firestore/dev/src/v1/gapic_metadata.json @@ -0,0 +1,175 @@ +{ + "schema": "1.0", + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "typescript", + "protoPackage": "google.firestore.v1", + "libraryPackage": "@google-cloud/firestore", + "services": { + "Firestore": { + "clients": { + "grpc": { + "libraryClient": "FirestoreClient", + "rpcs": { + "GetDocument": { + "methods": [ + "getDocument" + ] + }, + "UpdateDocument": { + "methods": [ + "updateDocument" + ] + }, + "DeleteDocument": { + "methods": [ + "deleteDocument" + ] + }, + "BeginTransaction": { + "methods": [ + "beginTransaction" + ] + }, + "Commit": { + "methods": [ + "commit" + ] + }, + "Rollback": { + "methods": [ + "rollback" + ] + }, + "BatchWrite": { + "methods": [ + "batchWrite" + ] + }, + "CreateDocument": { + "methods": [ + "createDocument" + ] + }, + "BatchGetDocuments": { + "methods": [ + "batchGetDocuments" + ] + }, + "RunQuery": { + "methods": [ + "runQuery" + ] + }, + "ExecutePipeline": { + "methods": [ + "executePipeline" + ] + }, + "RunAggregationQuery": { + "methods": [ + "runAggregationQuery" + ] + }, + "Write": { + "methods": [ + "write" + ] + }, + "Listen": { + "methods": [ + "listen" + ] + }, + "ListDocuments": { + "methods": [ + "listDocuments", + "listDocumentsStream", + "listDocumentsAsync" + ] + }, + "PartitionQuery": { + "methods": [ + "partitionQuery", + "partitionQueryStream", + "partitionQueryAsync" + ] + }, + "ListCollectionIds": { + "methods": [ + "listCollectionIds", + "listCollectionIdsStream", + "listCollectionIdsAsync" + ] + } + } + }, + "grpc-fallback": { + "libraryClient": "FirestoreClient", + "rpcs": { + "GetDocument": { + "methods": [ + "getDocument" + ] + }, + "UpdateDocument": { + "methods": [ + "updateDocument" + ] + }, + "DeleteDocument": { + "methods": [ + "deleteDocument" + ] + }, + "BeginTransaction": { + "methods": [ + "beginTransaction" + ] + }, + "Commit": { + "methods": [ + "commit" + ] + }, + "Rollback": { + "methods": [ + "rollback" + ] + }, + "BatchWrite": { + "methods": [ + "batchWrite" + ] + }, + "CreateDocument": { + "methods": [ + "createDocument" + ] + }, + "ListDocuments": { + "methods": [ + "listDocuments", + "listDocumentsStream", + "listDocumentsAsync" + ] + }, + "PartitionQuery": { + "methods": [ + "partitionQuery", + "partitionQueryStream", + "partitionQueryAsync" + ] + }, + "ListCollectionIds": { + "methods": [ + "listCollectionIds", + "listCollectionIdsStream", + "listCollectionIdsAsync" + ] + } + } + } + } + } + } +} diff --git a/handwritten/firestore/dev/src/v1/index.ts b/handwritten/firestore/dev/src/v1/index.ts new file mode 100644 index 00000000000..b6d83aaf9ed --- /dev/null +++ b/handwritten/firestore/dev/src/v1/index.ts @@ -0,0 +1,23 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {FirestoreAdminClient} from './firestore_admin_client'; +import {FirestoreClient} from './firestore_client'; + +export {FirestoreClient, FirestoreAdminClient}; + +// Doing something really horrible for reverse compatibility with original JavaScript exports +const existingExports = module.exports; +module.exports = FirestoreClient; +module.exports = Object.assign(module.exports, existingExports); diff --git a/handwritten/firestore/dev/src/v1beta1/firestore_client.ts b/handwritten/firestore/dev/src/v1beta1/firestore_client.ts new file mode 100644 index 00000000000..7d3b2fde416 --- /dev/null +++ b/handwritten/firestore/dev/src/v1beta1/firestore_client.ts @@ -0,0 +1,2592 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import {Transform, PassThrough} from 'stream'; +import * as protos from '../../protos/firestore_v1beta1_proto_api'; +import jsonProtos = require('../../protos/v1beta1.json'); +import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1beta1/firestore_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './firestore_client_config.json'; +// tslint:disable deprecation + +// tslint:disable deprecation + +// tslint:disable deprecation + +// tslint:disable deprecation + +const version = require('../../../package.json').version; + +/** + * 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 (GCP) accelerate + * building truly serverless apps. + * @class + * @deprecated Use v1/firestore_client instead. + * @deprecated Use v1/firestore_client instead. + * @deprecated Use v1/firestore_client instead. + * @deprecated Use v1/firestore_client instead. + * @memberof v1beta1 + */ +export class FirestoreClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('firestore'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: {[name: string]: Function}; + firestoreStub?: Promise<{[name: string]: Function}>; + + /** + * Construct an instance of FirestoreClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://cloud.google.com/docs/authentication/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreClient({fallback: true}, gax); + * ``` + */ + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof FirestoreClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); + } + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; + this._servicePath = 'firestore.' + this._universeDomain; + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); + const port = opts?.port || staticMembers.port; + const clientConfig = opts?.clientConfig ?? {}; + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + + // Request numeric enum values if REST transport is used. + opts.numericEnums = true; + + // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. + if (servicePath !== this._servicePath && !('scopes' in opts)) { + opts['scopes'] = staticMembers.scopes; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; + + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + + // Determine the client header string. + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + listDocuments: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'documents', + ), + partitionQuery: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'partitions', + ), + listCollectionIds: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'collectionIds', + ), + }; + + // Some of the methods on this service provide streaming responses. + // Provide descriptors for these. + this.descriptors.stream = { + batchGetDocuments: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + runQuery: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + write: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + listen: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.firestore.v1beta1.Firestore', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + {'x-goog-api-client': clientHeader.join(' ')}, + ); + + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.firestoreStub) { + return this.firestoreStub; + } + + // Put together the "service stub" for + // google.firestore.v1beta1.Firestore. + this.firestoreStub = this._gaxGrpc.createStub( + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.firestore.v1beta1.Firestore', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.firestore.v1beta1.Firestore, + this._opts, + this._providedCustomServicePath, + ) as Promise<{[method: string]: Function}>; + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const firestoreStubMethods = [ + 'getDocument', + 'listDocuments', + 'updateDocument', + 'deleteDocument', + 'batchGetDocuments', + 'beginTransaction', + 'commit', + 'rollback', + 'runQuery', + 'partitionQuery', + 'write', + 'listen', + 'listCollectionIds', + 'batchWrite', + 'createDocument', + ]; + for (const methodName of firestoreStubMethods) { + const callPromise = this.firestoreStub.then( + stub => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({objectMode: true}); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { + throw err; + }, + ); + + const descriptor = + this.descriptors.page[methodName] || + this.descriptors.stream[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback, + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.firestoreStub; + } + + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'firestore.googleapis.com'; + } + + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'firestore.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/datastore', + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId( + callback?: Callback, + ): Promise | void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- + /** + * Gets a single document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to get. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * 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. + * @param {Buffer} request.transaction + * Reads the document in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads the version of the document at the given time. + * This may not be older than 270 seconds. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_GetDocument_async + */ + getDocument( + request?: protos.google.firestore.v1beta1.IGetDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IGetDocumentRequest | undefined, + {} | undefined, + ] + >; + getDocument( + request: protos.google.firestore.v1beta1.IGetDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IGetDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + getDocument( + request: protos.google.firestore.v1beta1.IGetDocumentRequest, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IGetDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + getDocument( + request?: protos.google.firestore.v1beta1.IGetDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.v1beta1.IDocument, + | protos.google.firestore.v1beta1.IGetDocumentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IGetDocumentRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IGetDocumentRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getDocument request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.v1beta1.IDocument, + | protos.google.firestore.v1beta1.IGetDocumentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getDocument response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IGetDocumentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Updates or inserts a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.v1beta1.Document} request.document + * Required. The updated document. + * Creates the document if it does not already exist. + * @param {google.firestore.v1beta1.DocumentMask} request.updateMask + * 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. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * 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. + * @param {google.firestore.v1beta1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_UpdateDocument_async + */ + updateDocument( + request?: protos.google.firestore.v1beta1.IUpdateDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IUpdateDocumentRequest | undefined, + {} | undefined, + ] + >; + updateDocument( + request: protos.google.firestore.v1beta1.IUpdateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + updateDocument( + request: protos.google.firestore.v1beta1.IUpdateDocumentRequest, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + updateDocument( + request?: protos.google.firestore.v1beta1.IUpdateDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.v1beta1.IDocument, + | protos.google.firestore.v1beta1.IUpdateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IUpdateDocumentRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'document.name': request.document!.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('updateDocument request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.v1beta1.IDocument, + | protos.google.firestore.v1beta1.IUpdateDocumentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateDocument response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .updateDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IUpdateDocumentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Deletes a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to delete. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1beta1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_DeleteDocument_async + */ + deleteDocument( + request?: protos.google.firestore.v1beta1.IDeleteDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IDeleteDocumentRequest | undefined, + {} | undefined, + ] + >; + deleteDocument( + request: protos.google.firestore.v1beta1.IDeleteDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + deleteDocument( + request: protos.google.firestore.v1beta1.IDeleteDocumentRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + deleteDocument( + request?: protos.google.firestore.v1beta1.IDeleteDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.v1beta1.IDeleteDocumentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IDeleteDocumentRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteDocument request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.v1beta1.IDeleteDocumentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteDocument response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IDeleteDocumentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Starts a new transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {google.firestore.v1beta1.TransactionOptions} request.options + * The options for the transaction. + * Defaults to a read-write transaction. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.BeginTransactionResponse|BeginTransactionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_BeginTransaction_async + */ + beginTransaction( + request?: protos.google.firestore.v1beta1.IBeginTransactionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1beta1.IBeginTransactionResponse, + protos.google.firestore.v1beta1.IBeginTransactionRequest | undefined, + {} | undefined, + ] + >; + beginTransaction( + request: protos.google.firestore.v1beta1.IBeginTransactionRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.IBeginTransactionResponse, + | protos.google.firestore.v1beta1.IBeginTransactionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + beginTransaction( + request: protos.google.firestore.v1beta1.IBeginTransactionRequest, + callback: Callback< + protos.google.firestore.v1beta1.IBeginTransactionResponse, + | protos.google.firestore.v1beta1.IBeginTransactionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + beginTransaction( + request?: protos.google.firestore.v1beta1.IBeginTransactionRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.v1beta1.IBeginTransactionResponse, + | protos.google.firestore.v1beta1.IBeginTransactionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1beta1.IBeginTransactionResponse, + | protos.google.firestore.v1beta1.IBeginTransactionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.v1beta1.IBeginTransactionResponse, + protos.google.firestore.v1beta1.IBeginTransactionRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('beginTransaction request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.v1beta1.IBeginTransactionResponse, + | protos.google.firestore.v1beta1.IBeginTransactionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('beginTransaction response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .beginTransaction(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1beta1.IBeginTransactionResponse, + protos.google.firestore.v1beta1.IBeginTransactionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('beginTransaction response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Commits a transaction, while optionally updating documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * The writes to apply. + * + * Always executed atomically and in order. + * @param {Buffer} request.transaction + * If set, applies all writes in this transaction, and commits it. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.CommitResponse|CommitResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_Commit_async + */ + commit( + request?: protos.google.firestore.v1beta1.ICommitRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1beta1.ICommitResponse, + protos.google.firestore.v1beta1.ICommitRequest | undefined, + {} | undefined, + ] + >; + commit( + request: protos.google.firestore.v1beta1.ICommitRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.ICommitResponse, + protos.google.firestore.v1beta1.ICommitRequest | null | undefined, + {} | null | undefined + >, + ): void; + commit( + request: protos.google.firestore.v1beta1.ICommitRequest, + callback: Callback< + protos.google.firestore.v1beta1.ICommitResponse, + protos.google.firestore.v1beta1.ICommitRequest | null | undefined, + {} | null | undefined + >, + ): void; + commit( + request?: protos.google.firestore.v1beta1.ICommitRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.v1beta1.ICommitResponse, + protos.google.firestore.v1beta1.ICommitRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1beta1.ICommitResponse, + protos.google.firestore.v1beta1.ICommitRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.v1beta1.ICommitResponse, + protos.google.firestore.v1beta1.ICommitRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('commit request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.v1beta1.ICommitResponse, + protos.google.firestore.v1beta1.ICommitRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('commit response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .commit(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1beta1.ICommitResponse, + protos.google.firestore.v1beta1.ICommitRequest | undefined, + {} | undefined, + ]) => { + this._log.info('commit response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Rolls back a transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {Buffer} request.transaction + * Required. The transaction to roll back. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_Rollback_async + */ + rollback( + request?: protos.google.firestore.v1beta1.IRollbackRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IRollbackRequest | undefined, + {} | undefined, + ] + >; + rollback( + request: protos.google.firestore.v1beta1.IRollbackRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + ): void; + rollback( + request: protos.google.firestore.v1beta1.IRollbackRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + ): void; + rollback( + request?: protos.google.firestore.v1beta1.IRollbackRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IRollbackRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('rollback request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IRollbackRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('rollback response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .rollback(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IRollbackRequest | undefined, + {} | undefined, + ]) => { + this._log.info('rollback response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * 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 + * {@link protos.google.firestore.v1beta1.BatchWriteResponse|BatchWriteResponse} for the success status of each write. + * + * If you require an atomically applied set of writes, use + * {@link protos.google.firestore.v1beta1.Firestore.Commit|Commit} instead. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * 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. + * @param {number[]} request.labels + * Labels associated with this batch write. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.BatchWriteResponse|BatchWriteResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_BatchWrite_async + */ + batchWrite( + request?: protos.google.firestore.v1beta1.IBatchWriteRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1beta1.IBatchWriteResponse, + protos.google.firestore.v1beta1.IBatchWriteRequest | undefined, + {} | undefined, + ] + >; + batchWrite( + request: protos.google.firestore.v1beta1.IBatchWriteRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.IBatchWriteResponse, + protos.google.firestore.v1beta1.IBatchWriteRequest | null | undefined, + {} | null | undefined + >, + ): void; + batchWrite( + request: protos.google.firestore.v1beta1.IBatchWriteRequest, + callback: Callback< + protos.google.firestore.v1beta1.IBatchWriteResponse, + protos.google.firestore.v1beta1.IBatchWriteRequest | null | undefined, + {} | null | undefined + >, + ): void; + batchWrite( + request?: protos.google.firestore.v1beta1.IBatchWriteRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.v1beta1.IBatchWriteResponse, + protos.google.firestore.v1beta1.IBatchWriteRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1beta1.IBatchWriteResponse, + protos.google.firestore.v1beta1.IBatchWriteRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.v1beta1.IBatchWriteResponse, + protos.google.firestore.v1beta1.IBatchWriteRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('batchWrite request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.v1beta1.IBatchWriteResponse, + protos.google.firestore.v1beta1.IBatchWriteRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('batchWrite response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .batchWrite(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1beta1.IBatchWriteResponse, + protos.google.firestore.v1beta1.IBatchWriteRequest | undefined, + {} | undefined, + ]) => { + this._log.info('batchWrite response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Creates a new document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource. For example: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`. + * @param {string} request.documentId + * The client-assigned document ID to use for this document. + * + * Optional. If not specified, an ID will be assigned by the service. + * @param {google.firestore.v1beta1.Document} request.document + * Required. The document to create. `name` must not be set. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_CreateDocument_async + */ + createDocument( + request?: protos.google.firestore.v1beta1.ICreateDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.ICreateDocumentRequest | undefined, + {} | undefined, + ] + >; + createDocument( + request: protos.google.firestore.v1beta1.ICreateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + createDocument( + request: protos.google.firestore.v1beta1.ICreateDocumentRequest, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + createDocument( + request?: protos.google.firestore.v1beta1.ICreateDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.firestore.v1beta1.IDocument, + | protos.google.firestore.v1beta1.ICreateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.ICreateDocumentRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + collection_id: request.collectionId?.toString() ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('createDocument request %j', request); + const wrappedCallback: + | Callback< + protos.google.firestore.v1beta1.IDocument, + | protos.google.firestore.v1beta1.ICreateDocumentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createDocument response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.ICreateDocumentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + + /** + * Gets multiple documents. + * + * Documents returned by this method are not guaranteed to be returned in the + * same order that they were requested. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.documents + * 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. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * 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. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1beta1.TransactionOptions} request.newTransaction + * 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. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1beta1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_BatchGetDocuments_async + */ + batchGetDocuments( + request?: protos.google.firestore.v1beta1.IBatchGetDocumentsRequest, + options?: CallOptions, + ): gax.CancellableStream { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('batchGetDocuments stream %j', options); + return this.innerApiCalls.batchGetDocuments(request, options); + } + + /** + * Runs a query. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * A structured query. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1beta1.TransactionOptions} request.newTransaction + * 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. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1beta1.RunQueryResponse|RunQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_RunQuery_async + */ + runQuery( + request?: protos.google.firestore.v1beta1.IRunQueryRequest, + options?: CallOptions, + ): gax.CancellableStream { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('runQuery stream %j', options); + return this.innerApiCalls.runQuery(request, options); + } + + /** + * Streams batches of document updates and deletes, in order. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1beta1.WriteRequest|WriteRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1beta1.WriteResponse|WriteResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_Write_async + */ + write(options?: CallOptions): gax.CancellableStream { + this.initialize().catch(err => { + throw err; + }); + this._log.info('write stream %j', options); + return this.innerApiCalls.write(null, options); + } + + /** + * Listens to changes. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1beta1.ListenRequest|ListenRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1beta1.ListenResponse|ListenResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_Listen_async + */ + listen(options?: CallOptions): gax.CancellableStream { + this.initialize().catch(err => { + throw err; + }); + this._log.info('listen stream %j', options); + return this.innerApiCalls.listen(null, options); + } + + /** + * Lists documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` + * or `messages`. + * @param {number} request.pageSize + * The maximum number of documents to return. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous List request, if any. + * @param {string} request.orderBy + * The order to sort results by. For example: `priority desc, name`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * 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. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {boolean} request.showMissing + * If the list should show missing documents. A missing document is a + * document that does not exist but has sub-documents. These documents will + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * + * Requests with `show_missing` may not specify `where` or + * `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1beta1.Document|Document}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocuments( + request?: protos.google.firestore.v1beta1.IListDocumentsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1beta1.IDocument[], + protos.google.firestore.v1beta1.IListDocumentsRequest | null, + protos.google.firestore.v1beta1.IListDocumentsResponse, + ] + >; + listDocuments( + request: protos.google.firestore.v1beta1.IListDocumentsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IListDocumentsRequest, + protos.google.firestore.v1beta1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1beta1.IDocument + >, + ): void; + listDocuments( + request: protos.google.firestore.v1beta1.IListDocumentsRequest, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IListDocumentsRequest, + protos.google.firestore.v1beta1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1beta1.IDocument + >, + ): void; + listDocuments( + request?: protos.google.firestore.v1beta1.IListDocumentsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.firestore.v1beta1.IListDocumentsRequest, + | protos.google.firestore.v1beta1.IListDocumentsResponse + | null + | undefined, + protos.google.firestore.v1beta1.IDocument + >, + callback?: PaginationCallback< + protos.google.firestore.v1beta1.IListDocumentsRequest, + protos.google.firestore.v1beta1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1beta1.IDocument + >, + ): Promise< + [ + protos.google.firestore.v1beta1.IDocument[], + protos.google.firestore.v1beta1.IListDocumentsRequest | null, + protos.google.firestore.v1beta1.IListDocumentsResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + collection_id: request.collectionId?.toString() ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.firestore.v1beta1.IListDocumentsRequest, + | protos.google.firestore.v1beta1.IListDocumentsResponse + | null + | undefined, + protos.google.firestore.v1beta1.IDocument + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listDocuments values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listDocuments request %j', request); + return this.innerApiCalls + .listDocuments(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.firestore.v1beta1.IDocument[], + protos.google.firestore.v1beta1.IListDocumentsRequest | null, + protos.google.firestore.v1beta1.IListDocumentsResponse, + ]) => { + this._log.info('listDocuments values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listDocuments`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` + * or `messages`. + * @param {number} request.pageSize + * The maximum number of documents to return. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous List request, if any. + * @param {string} request.orderBy + * The order to sort results by. For example: `priority desc, name`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * 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. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {boolean} request.showMissing + * If the list should show missing documents. A missing document is a + * document that does not exist but has sub-documents. These documents will + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * + * Requests with `show_missing` may not specify `where` or + * `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1beta1.Document|Document} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocumentsStream( + request?: protos.google.firestore.v1beta1.IListDocumentsRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + collection_id: request.collectionId?.toString() ?? '', + }); + const defaultCallSettings = this._defaults['listDocuments']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listDocuments stream %j', request); + return this.descriptors.page.listDocuments.createStream( + this.innerApiCalls.listDocuments as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listDocuments`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` + * or `messages`. + * @param {number} request.pageSize + * The maximum number of documents to return. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous List request, if any. + * @param {string} request.orderBy + * The order to sort results by. For example: `priority desc, name`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * 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. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {boolean} request.showMissing + * If the list should show missing documents. A missing document is a + * document that does not exist but has sub-documents. These documents will + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * + * Requests with `show_missing` may not specify `where` or + * `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1beta1.Document|Document}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_ListDocuments_async + */ + listDocumentsAsync( + request?: protos.google.firestore.v1beta1.IListDocumentsRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + collection_id: request.collectionId?.toString() ?? '', + }); + const defaultCallSettings = this._defaults['listDocuments']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listDocuments iterate %j', request); + return this.descriptors.page.listDocuments.asyncIterate( + this.innerApiCalls['listDocuments'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * 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. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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. + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * 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. + * @param {number} request.partitionCount + * 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. + * @param {string} request.pageToken + * 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 + * @param {number} request.pageSize + * 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`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1beta1.Cursor|Cursor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQuery( + request?: protos.google.firestore.v1beta1.IPartitionQueryRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1beta1.ICursor[], + protos.google.firestore.v1beta1.IPartitionQueryRequest | null, + protos.google.firestore.v1beta1.IPartitionQueryResponse, + ] + >; + partitionQuery( + request: protos.google.firestore.v1beta1.IPartitionQueryRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IPartitionQueryRequest, + | protos.google.firestore.v1beta1.IPartitionQueryResponse + | null + | undefined, + protos.google.firestore.v1beta1.ICursor + >, + ): void; + partitionQuery( + request: protos.google.firestore.v1beta1.IPartitionQueryRequest, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IPartitionQueryRequest, + | protos.google.firestore.v1beta1.IPartitionQueryResponse + | null + | undefined, + protos.google.firestore.v1beta1.ICursor + >, + ): void; + partitionQuery( + request?: protos.google.firestore.v1beta1.IPartitionQueryRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.firestore.v1beta1.IPartitionQueryRequest, + | protos.google.firestore.v1beta1.IPartitionQueryResponse + | null + | undefined, + protos.google.firestore.v1beta1.ICursor + >, + callback?: PaginationCallback< + protos.google.firestore.v1beta1.IPartitionQueryRequest, + | protos.google.firestore.v1beta1.IPartitionQueryResponse + | null + | undefined, + protos.google.firestore.v1beta1.ICursor + >, + ): Promise< + [ + protos.google.firestore.v1beta1.ICursor[], + protos.google.firestore.v1beta1.IPartitionQueryRequest | null, + protos.google.firestore.v1beta1.IPartitionQueryResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.firestore.v1beta1.IPartitionQueryRequest, + | protos.google.firestore.v1beta1.IPartitionQueryResponse + | null + | undefined, + protos.google.firestore.v1beta1.ICursor + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('partitionQuery values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('partitionQuery request %j', request); + return this.innerApiCalls + .partitionQuery(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.firestore.v1beta1.ICursor[], + protos.google.firestore.v1beta1.IPartitionQueryRequest | null, + protos.google.firestore.v1beta1.IPartitionQueryResponse, + ]) => { + this._log.info('partitionQuery values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `partitionQuery`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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. + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * 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. + * @param {number} request.partitionCount + * 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. + * @param {string} request.pageToken + * 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 + * @param {number} request.pageSize + * 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`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1beta1.Cursor|Cursor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQueryStream( + request?: protos.google.firestore.v1beta1.IPartitionQueryRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['partitionQuery']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('partitionQuery stream %j', request); + return this.descriptors.page.partitionQuery.createStream( + this.innerApiCalls.partitionQuery as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `partitionQuery`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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. + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * 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. + * @param {number} request.partitionCount + * 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. + * @param {string} request.pageToken + * 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 + * @param {number} request.pageSize + * 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`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1beta1.Cursor|Cursor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_PartitionQuery_async + */ + partitionQueryAsync( + request?: protos.google.firestore.v1beta1.IPartitionQueryRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['partitionQuery']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('partitionQuery iterate %j', request); + return this.descriptors.page.partitionQuery.asyncIterate( + this.innerApiCalls['partitionQuery'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * Lists all the collection IDs underneath a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of string. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIds( + request?: protos.google.firestore.v1beta1.IListCollectionIdsRequest, + options?: CallOptions, + ): Promise< + [ + string[], + protos.google.firestore.v1beta1.IListCollectionIdsRequest | null, + protos.google.firestore.v1beta1.IListCollectionIdsResponse, + ] + >; + listCollectionIds( + request: protos.google.firestore.v1beta1.IListCollectionIdsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IListCollectionIdsRequest, + | protos.google.firestore.v1beta1.IListCollectionIdsResponse + | null + | undefined, + string + >, + ): void; + listCollectionIds( + request: protos.google.firestore.v1beta1.IListCollectionIdsRequest, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IListCollectionIdsRequest, + | protos.google.firestore.v1beta1.IListCollectionIdsResponse + | null + | undefined, + string + >, + ): void; + listCollectionIds( + request?: protos.google.firestore.v1beta1.IListCollectionIdsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.firestore.v1beta1.IListCollectionIdsRequest, + | protos.google.firestore.v1beta1.IListCollectionIdsResponse + | null + | undefined, + string + >, + callback?: PaginationCallback< + protos.google.firestore.v1beta1.IListCollectionIdsRequest, + | protos.google.firestore.v1beta1.IListCollectionIdsResponse + | null + | undefined, + string + >, + ): Promise< + [ + string[], + protos.google.firestore.v1beta1.IListCollectionIdsRequest | null, + protos.google.firestore.v1beta1.IListCollectionIdsResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.firestore.v1beta1.IListCollectionIdsRequest, + | protos.google.firestore.v1beta1.IListCollectionIdsResponse + | null + | undefined, + string + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listCollectionIds values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listCollectionIds request %j', request); + return this.innerApiCalls + .listCollectionIds(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + string[], + protos.google.firestore.v1beta1.IListCollectionIdsRequest | null, + protos.google.firestore.v1beta1.IListCollectionIdsResponse, + ]) => { + this._log.info('listCollectionIds values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listCollectionIds`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing string on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIdsStream( + request?: protos.google.firestore.v1beta1.IListCollectionIdsRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listCollectionIds']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listCollectionIds stream %j', request); + return this.descriptors.page.listCollectionIds.createStream( + this.innerApiCalls.listCollectionIds as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listCollectionIds`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * string. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_ListCollectionIds_async + */ + listCollectionIdsAsync( + request?: protos.google.firestore.v1beta1.IListCollectionIdsRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listCollectionIds']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listCollectionIds iterate %j', request); + return this.descriptors.page.listCollectionIds.asyncIterate( + this.innerApiCalls['listCollectionIds'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.firestoreStub && !this._terminated) { + return this.firestoreStub.then(stub => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} diff --git a/handwritten/firestore/dev/src/v1beta1/firestore_client_config.json b/handwritten/firestore/dev/src/v1beta1/firestore_client_config.json new file mode 100644 index 00000000000..b0366d66260 --- /dev/null +++ b/handwritten/firestore/dev/src/v1beta1/firestore_client_config.json @@ -0,0 +1,99 @@ +{ + "interfaces": { + "google.firestore.v1beta1.Firestore": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "GetDocument": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "ListDocuments": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "UpdateDocument": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DeleteDocument": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "BatchGetDocuments": { + "timeout_millis": 300000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "BeginTransaction": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "Commit": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Rollback": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "RunQuery": { + "timeout_millis": 300000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "PartitionQuery": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Write": { + "timeout_millis": 86400000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Listen": { + "timeout_millis": 86400000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "ListCollectionIds": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "BatchWrite": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "CreateDocument": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/handwritten/firestore/dev/src/v1beta1/firestore_proto_list.json b/handwritten/firestore/dev/src/v1beta1/firestore_proto_list.json new file mode 100644 index 00000000000..735b7955917 --- /dev/null +++ b/handwritten/firestore/dev/src/v1beta1/firestore_proto_list.json @@ -0,0 +1,8 @@ +[ + "../../protos/google/firestore/v1beta1/common.proto", + "../../protos/google/firestore/v1beta1/document.proto", + "../../protos/google/firestore/v1beta1/firestore.proto", + "../../protos/google/firestore/v1beta1/query.proto", + "../../protos/google/firestore/v1beta1/undeliverable_first_gen_event.proto", + "../../protos/google/firestore/v1beta1/write.proto" +] diff --git a/handwritten/firestore/dev/src/v1beta1/gapic_metadata.json b/handwritten/firestore/dev/src/v1beta1/gapic_metadata.json new file mode 100644 index 00000000000..90ed69dcf90 --- /dev/null +++ b/handwritten/firestore/dev/src/v1beta1/gapic_metadata.json @@ -0,0 +1,165 @@ +{ + "schema": "1.0", + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "typescript", + "protoPackage": "google.firestore.v1beta1", + "libraryPackage": "@google-cloud/firestore", + "services": { + "Firestore": { + "clients": { + "grpc": { + "libraryClient": "FirestoreClient", + "rpcs": { + "GetDocument": { + "methods": [ + "getDocument" + ] + }, + "UpdateDocument": { + "methods": [ + "updateDocument" + ] + }, + "DeleteDocument": { + "methods": [ + "deleteDocument" + ] + }, + "BeginTransaction": { + "methods": [ + "beginTransaction" + ] + }, + "Commit": { + "methods": [ + "commit" + ] + }, + "Rollback": { + "methods": [ + "rollback" + ] + }, + "BatchWrite": { + "methods": [ + "batchWrite" + ] + }, + "CreateDocument": { + "methods": [ + "createDocument" + ] + }, + "BatchGetDocuments": { + "methods": [ + "batchGetDocuments" + ] + }, + "RunQuery": { + "methods": [ + "runQuery" + ] + }, + "Write": { + "methods": [ + "write" + ] + }, + "Listen": { + "methods": [ + "listen" + ] + }, + "ListDocuments": { + "methods": [ + "listDocuments", + "listDocumentsStream", + "listDocumentsAsync" + ] + }, + "PartitionQuery": { + "methods": [ + "partitionQuery", + "partitionQueryStream", + "partitionQueryAsync" + ] + }, + "ListCollectionIds": { + "methods": [ + "listCollectionIds", + "listCollectionIdsStream", + "listCollectionIdsAsync" + ] + } + } + }, + "grpc-fallback": { + "libraryClient": "FirestoreClient", + "rpcs": { + "GetDocument": { + "methods": [ + "getDocument" + ] + }, + "UpdateDocument": { + "methods": [ + "updateDocument" + ] + }, + "DeleteDocument": { + "methods": [ + "deleteDocument" + ] + }, + "BeginTransaction": { + "methods": [ + "beginTransaction" + ] + }, + "Commit": { + "methods": [ + "commit" + ] + }, + "Rollback": { + "methods": [ + "rollback" + ] + }, + "BatchWrite": { + "methods": [ + "batchWrite" + ] + }, + "CreateDocument": { + "methods": [ + "createDocument" + ] + }, + "ListDocuments": { + "methods": [ + "listDocuments", + "listDocumentsStream", + "listDocumentsAsync" + ] + }, + "PartitionQuery": { + "methods": [ + "partitionQuery", + "partitionQueryStream", + "partitionQueryAsync" + ] + }, + "ListCollectionIds": { + "methods": [ + "listCollectionIds", + "listCollectionIdsStream", + "listCollectionIdsAsync" + ] + } + } + } + } + } + } +} diff --git a/handwritten/firestore/dev/src/v1beta1/index.ts b/handwritten/firestore/dev/src/v1beta1/index.ts new file mode 100644 index 00000000000..b19eff7ed37 --- /dev/null +++ b/handwritten/firestore/dev/src/v1beta1/index.ts @@ -0,0 +1,27 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +// tslint:disable deprecation + +import {FirestoreClient} from './firestore_client'; +export {FirestoreClient}; + +// Doing something really horrible for reverse compatibility with original JavaScript exports +const existingExports = module.exports; +module.exports = FirestoreClient; +module.exports = Object.assign(module.exports, existingExports); diff --git a/handwritten/firestore/dev/src/validate.ts b/handwritten/firestore/dev/src/validate.ts new file mode 100644 index 00000000000..7a33461ec26 --- /dev/null +++ b/handwritten/firestore/dev/src/validate.ts @@ -0,0 +1,450 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {URL} from 'url'; +import {FieldPath} from './path'; +import {isFunction, isObject} from './util'; +import {Timestamp} from './timestamp'; + +/** + * Options to allow argument omission. + * + * @private + * @internal + */ +export interface RequiredArgumentOptions { + optional?: boolean; +} + +/** + * Options to limit the range of numbers. + * + * @private + * @internal + */ +export interface NumericRangeOptions { + minValue?: number; + maxValue?: number; +} + +/** + * Generates an error message to use with custom objects that cannot be + * serialized. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The value that failed serialization. + * @param path The field path that the object is assigned to. + */ +export function customObjectMessage( + arg: string | number, + value: unknown, + path?: FieldPath, +): string { + const fieldPathMessage = path ? ` (found in field "${path}")` : ''; + + if (isObject(value)) { + // We use the base class name as the type name as the sentinel classes + // returned by the public FieldValue API are subclasses of FieldValue. By + // using the base name, we reduce the number of special cases below. + const typeName = value.constructor.name; + switch (typeName) { + case 'DocumentReference': + case 'FieldPath': + case 'FieldValue': + case 'GeoPoint': + case 'Timestamp': + return ( + `${invalidArgumentMessage( + arg, + 'Firestore document', + )} Detected an object of type "${typeName}" that doesn't match the ` + + `expected instance${fieldPathMessage}. Please ensure that the ` + + 'Firestore types you are using are from the same NPM package.)' + ); + case 'Object': + return `${invalidArgumentMessage( + arg, + 'Firestore document', + )} Invalid use of type "${typeof value}" as a Firestore argument${fieldPathMessage}.`; + default: + return ( + `${invalidArgumentMessage( + arg, + 'Firestore document', + )} Couldn't serialize object of type "${typeName}"${fieldPathMessage}. Firestore doesn't support JavaScript ` + + 'objects with custom prototypes (i.e. objects that were created ' + + 'via the "new" operator).' + ); + } + } else { + return `${invalidArgumentMessage( + arg, + 'Firestore document', + )} Input is not a plain JavaScript object${fieldPathMessage}.`; + } +} + +/** + * Validates that 'value' is a function. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the function can be omitted. + */ +export function validateFunction( + arg: string | number, + value: unknown, + options?: RequiredArgumentOptions, +): void { + if (!validateOptional(value, options)) { + if (!isFunction(value)) { + throw new Error(invalidArgumentMessage(arg, 'function')); + } + } +} + +/** + * Validates that 'value' is an object. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the object can be omitted. + */ +export function validateObject( + arg: string | number, + value: unknown, + options?: RequiredArgumentOptions, +): void { + if (!validateOptional(value, options)) { + if (!isObject(value)) { + throw new Error(invalidArgumentMessage(arg, 'object')); + } + } +} + +/** + * Validates that 'value' is a string. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the string can be omitted. + */ +export function validateString( + arg: string | number, + value: unknown, + options?: RequiredArgumentOptions, +): void { + if (!validateOptional(value, options)) { + if (typeof value !== 'string') { + throw new Error(invalidArgumentMessage(arg, 'string')); + } + } +} + +/** + * Validates that 'value' is a host. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the host can be omitted. + */ +export function validateHost( + arg: string | number, + value: unknown, + options?: RequiredArgumentOptions, +): void { + if (!validateOptional(value, options)) { + validateString(arg, value); + const urlString = `http://${value}/`; + let parsed; + try { + parsed = new URL(urlString); + } catch (e) { + throw new Error(invalidArgumentMessage(arg, 'host')); + } + + if ( + parsed.search !== '' || + parsed.pathname !== '/' || + parsed.username !== '' + ) { + throw new Error(invalidArgumentMessage(arg, 'host')); + } + } +} + +/** + * Validates that 'value' is a boolean. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the boolean can be omitted. + */ +export function validateBoolean( + arg: string | number, + value: unknown, + options?: RequiredArgumentOptions, +): void { + if (!validateOptional(value, options)) { + if (typeof value !== 'boolean') { + throw new Error(invalidArgumentMessage(arg, 'boolean')); + } + } +} + +/** + * Validates that 'value' is a number. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the number can be omitted. + */ +export function validateNumber( + arg: string | number, + value: unknown, + options?: RequiredArgumentOptions & NumericRangeOptions, +): void { + const min = + options !== undefined && options.minValue !== undefined + ? options.minValue + : -Infinity; + const max = + options !== undefined && options.maxValue !== undefined + ? options.maxValue + : Infinity; + + if (!validateOptional(value, options)) { + if (typeof value !== 'number' || isNaN(value)) { + throw new Error(invalidArgumentMessage(arg, 'number')); + } else if (value < min || value > max) { + throw new Error( + `${formatArgumentName( + arg, + )} must be within [${min}, ${max}] inclusive, but was: ${value}`, + ); + } + } +} + +/** + * Validates that 'value' is a integer. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the integer can be omitted. + */ +export function validateInteger( + arg: string | number, + value: unknown, + options?: RequiredArgumentOptions & NumericRangeOptions, +): void { + const min = + options !== undefined && options.minValue !== undefined + ? options.minValue + : -Infinity; + const max = + options !== undefined && options.maxValue !== undefined + ? options.maxValue + : Infinity; + + if (!validateOptional(value, options)) { + if (typeof value !== 'number' || isNaN(value) || value % 1 !== 0) { + throw new Error(invalidArgumentMessage(arg, 'integer')); + } else if (value < min || value > max) { + throw new Error( + `${formatArgumentName( + arg, + )} must be within [${min}, ${max}] inclusive, but was: ${value}`, + ); + } + } +} + +/** + * Validates that 'value' is a Timestamp. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the Timestamp can be omitted. + */ +export function validateTimestamp( + arg: string | number, + value: unknown, + options?: RequiredArgumentOptions, +): void { + if (!validateOptional(value, options)) { + if (!(value instanceof Timestamp)) { + throw new Error(invalidArgumentMessage(arg, 'Timestamp')); + } + } +} + +/** + * Generates an error message to use with invalid arguments. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param expectedType The expected input type. + */ +export function invalidArgumentMessage( + arg: string | number, + expectedType: string, +): string { + return `${formatArgumentName(arg)} is not a valid ${expectedType}.`; +} + +/** + * Enforces the 'options.optional' constraint for 'value'. + * + * @private + * @internal + * @param value The input to validate. + * @param options Whether the function can be omitted. + * @returns Whether the object is omitted and is allowed to be omitted. + */ +export function validateOptional( + value: unknown, + options?: RequiredArgumentOptions, +): boolean { + return ( + value === undefined && options !== undefined && options.optional === true + ); +} + +/** + * Formats the given word as plural conditionally given the preceding number. + * + * @private + * @internal + * @param num The number to use for formatting. + * @param str The string to format. + */ +function formatPlural(num: number, str: string): string { + return `${num} ${str}` + (num === 1 ? '' : 's'); +} + +/** + * Creates a descriptive name for the provided argument name or index. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @returns Either the argument name or its index description. + */ +function formatArgumentName(arg: string | number): string { + return typeof arg === 'string' + ? `Value for argument "${arg}"` + : `Element at index ${arg}`; +} + +/** + * Verifies that 'args' has at least 'minSize' elements. + * + * @private + * @internal + * @param funcName The function name to use in the error message. + * @param args The array (or array-like structure) to verify. + * @param minSize The minimum number of elements to enforce. + * @throws if the expectation is not met. + */ +export function validateMinNumberOfArguments( + funcName: string, + args: IArguments | unknown[], + minSize: number, +): void { + if (args.length < minSize) { + throw new Error( + `Function "${funcName}()" requires at least ` + + `${formatPlural(minSize, 'argument')}.`, + ); + } +} + +/** + * Verifies that 'args' has at most 'maxSize' elements. + * + * @private + * @internal + * @param funcName The function name to use in the error message. + * @param args The array (or array-like structure) to verify. + * @param maxSize The maximum number of elements to enforce. + * @throws if the expectation is not met. + */ +export function validateMaxNumberOfArguments( + funcName: string, + args: IArguments, + maxSize: number, +): void { + if (args.length > maxSize) { + throw new Error( + `Function "${funcName}()" accepts at most ` + + `${formatPlural(maxSize, 'argument')}.`, + ); + } +} + +/** + * Validates that the provided named option equals one of the expected values. + * + * @param arg The argument name or argument index (for varargs methods).). + * @param value The input to validate. + * @param allowedValues A list of expected values. + * @param options Whether the input can be omitted. + * @private + * @internal + */ +export function validateEnumValue( + arg: string | number, + value: unknown, + allowedValues: string[], + options?: RequiredArgumentOptions, +): void { + if (!validateOptional(value, options)) { + const expectedDescription: string[] = []; + + for (const allowed of allowedValues) { + if (allowed === value) { + return; + } + expectedDescription.push(allowed); + } + + throw new Error( + `${formatArgumentName( + arg, + )} is invalid. Acceptable values are: ${expectedDescription.join(', ')}`, + ); + } +} diff --git a/handwritten/firestore/dev/src/watch.ts b/handwritten/firestore/dev/src/watch.ts new file mode 100644 index 00000000000..72e3a4d2043 --- /dev/null +++ b/handwritten/firestore/dev/src/watch.ts @@ -0,0 +1,947 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; + +import * as assert from 'assert'; +import * as rbtree from 'functional-red-black-tree'; +import {GoogleError, Status} from 'google-gax'; +import {Duplex} from 'stream'; + +import {google} from '../protos/firestore_v1_proto_api'; +import {delayExecution, ExponentialBackoff} from './backoff'; +import {DocumentSnapshotBuilder, QueryDocumentSnapshot} from './document'; +import {DocumentChange, DocumentChangeType} from './document-change'; +import {DocumentReference, Firestore, Query} from './index'; +import {logger} from './logger'; +import {QualifiedResourcePath} from './path'; +import {Timestamp} from './timestamp'; +import {defaultConverter, RBTree} from './types'; +import {requestTag} from './util'; + +import api = google.firestore.v1; +import {DocumentData} from '@google-cloud/firestore'; + +/*! + * Target ID used by watch. Watch uses a fixed target id since we only support + * one target per stream. + * @type {number} + */ +const WATCH_TARGET_ID = 0x1; + +/*! + * Idle timeout used to detect Watch streams that stall (see + * https://github.com/googleapis/nodejs-firestore/issues/1057, b/156308554). + * Under normal load, the Watch backend will send a TARGET_CHANGE message + * roughly every 30 seconds. As discussed with the backend team, we reset the + * Watch stream if we do not receive any message within 120 seconds. + */ +export const WATCH_IDLE_TIMEOUT_MS = 120 * 1000; + +/*! + * Sentinel value for a document remove. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const REMOVED = {} as DocumentSnapshotBuilder; + +/*! + * The change type for document change events. + */ +// tslint:disable-next-line:variable-name +const ChangeType: {[k: string]: DocumentChangeType} = { + added: 'added', + modified: 'modified', + removed: 'removed', +}; + +/*! + * The comparator used for document watches (which should always get called with + * the same document). + */ +const DOCUMENT_WATCH_COMPARATOR: < + AppModelType, + DbModelType extends DocumentData, +>( + doc1: QueryDocumentSnapshot, + doc2: QueryDocumentSnapshot, +) => number = (doc1, doc2) => { + assert(doc1 === doc2, 'Document watches only support one document.'); + return 0; +}; + +const EMPTY_FUNCTION: () => void = () => {}; + +/** + * @private + * @internal + * @callback docsCallback + * @returns {Array.} An ordered list of documents. + */ + +/** + * @private + * @internal + * @callback changeCallback + * @returns {Array.} An ordered list of document + * changes. + */ + +/** + * onSnapshot() callback that receives the updated query state. + * + * @private + * @internal + * @callback watchSnapshotCallback + * + * @param {Timestamp} readTime The time at which this snapshot was obtained. + * @param {number} size The number of documents in the result set. + * @param {docsCallback} docs A callback that returns the ordered list of + * documents stored in this snapshot. + * @param {changeCallback} changes A callback that returns the list of + * changed documents since the last snapshot delivered for this watch. + */ + +type DocumentComparator< + AppModelType, + DbModelType extends firestore.DocumentData, +> = ( + l: QueryDocumentSnapshot, + r: QueryDocumentSnapshot, +) => number; + +interface DocumentChangeSet< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> { + deletes: string[]; + adds: Array>; + updates: Array>; +} + +/** + * Watch provides listen functionality and exposes the 'onSnapshot' observer. It + * can be used with a valid Firestore Listen target. + * + * @class + * @private + * @internal + */ +abstract class Watch< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> { + protected readonly firestore: Firestore; + private readonly backoff: ExponentialBackoff; + private readonly requestTag: string; + + /** + * Indicates whether we are interested in data from the stream. Set to false in the + * 'unsubscribe()' callback. + * @private + * @internal + */ + private isActive = true; + + /** + * The current stream to the backend. + * @private + * @internal + */ + private currentStream: Duplex | null = null; + + /** + * The server assigns and updates the resume token. + * @private + * @internal + */ + private resumeToken: Uint8Array | undefined = undefined; + + /** + * A map of document names to QueryDocumentSnapshots for the last sent snapshot. + * @private + * @internal + */ + private docMap = new Map< + string, + QueryDocumentSnapshot + >(); + + /** + * The accumulated map of document changes (keyed by document name) for the + * current snapshot. + * @private + * @internal + */ + private changeMap = new Map< + string, + DocumentSnapshotBuilder + >(); + + /** + * The current state of the query results. * + * @private + * @internal + */ + private current = false; + + /** + * The sorted tree of QueryDocumentSnapshots as sent in the last snapshot. + * We only look at the keys. + * @private + * @internal + */ + private docTree: RBTree | undefined; + + /** + * We need this to track whether we've pushed an initial set of changes, + * since we should push those even when there are no changes, if there + * aren't docs. + * @private + * @internal + */ + private hasPushed = false; + + /** + * The handler used to restart the Watch stream if it has been idle for more + * than WATCH_IDLE_TIMEOUT_MS. + */ + private idleTimeoutHandle?: NodeJS.Timeout; + + private onNext: ( + readTime: Timestamp, + size: number, + docs: () => Array>, + changes: () => Array>, + ) => void; + + private onError: (error: Error) => void; + + /** + * @private + * @internal + * + * @param firestore The Firestore Database client. + */ + constructor( + firestore: Firestore, + readonly _converter = defaultConverter(), + ) { + this.firestore = firestore; + this.backoff = new ExponentialBackoff(); + this.requestTag = requestTag(); + this.onNext = EMPTY_FUNCTION; + this.onError = EMPTY_FUNCTION; + } + + /** Returns a 'Target' proto denoting the target to listen on. */ + protected abstract getTarget(resumeToken?: Uint8Array): api.ITarget; + + /** + * Returns a comparator for QueryDocumentSnapshots that is used to order the + * document snapshots returned by this watch. + */ + protected abstract getComparator(): DocumentComparator< + AppModelType, + DbModelType + >; + + /** + * Starts a watch and attaches a listener for document change events. + * + * @private + * @internal + * @param onNext A callback to be called every time a new snapshot is + * available. + * @param onError A callback to be called if the listen fails or is cancelled. + * No further callbacks will occur. + * + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ + onSnapshot( + onNext: ( + readTime: Timestamp, + size: number, + docs: () => Array>, + changes: () => Array>, + ) => void, + onError: (error: Error) => void, + ): () => void { + assert( + this.onNext === EMPTY_FUNCTION, + 'onNext should not already be defined.', + ); + assert( + this.onError === EMPTY_FUNCTION, + 'onError should not already be defined.', + ); + assert( + this.docTree === undefined, + 'docTree should not already be defined.', + ); + this.onNext = onNext; + this.onError = onError; + this.docTree = rbtree(this.getComparator()); + + this.initStream(); + + const unsubscribe: () => void = () => { + logger('Watch.onSnapshot', this.requestTag, 'Unsubscribe called'); + // Prevent further callbacks. + this.onNext = () => {}; + this.onError = () => {}; + this.shutdown(); + }; + this.firestore.registerListener(); + return unsubscribe; + } + + /** + * Returns the current count of all documents, including the changes from + * the current changeMap. + * @private + * @internal + */ + private currentSize(): number { + const changes = this.extractCurrentChanges(Timestamp.now()); + return this.docMap.size + changes.adds.length - changes.deletes.length; + } + + /** + * Splits up document changes into removals, additions, and updates. + * @private + * @internal + */ + private extractCurrentChanges( + readTime: Timestamp, + ): DocumentChangeSet { + const deletes: string[] = []; + const adds: Array> = []; + const updates: Array> = []; + + this.changeMap.forEach((value, name) => { + if (value === REMOVED) { + if (this.docMap.has(name)) { + deletes.push(name); + } + } else if (this.docMap.has(name)) { + value.readTime = readTime; + updates.push( + value.build() as QueryDocumentSnapshot, + ); + } else { + value.readTime = readTime; + adds.push( + value.build() as QueryDocumentSnapshot, + ); + } + }); + + return {deletes, adds, updates}; + } + + /** + * Helper to clear the docs on RESET or filter mismatch. + * @private + * @internal + */ + private resetDocs(): void { + logger('Watch.resetDocs', this.requestTag, 'Resetting documents'); + this.changeMap.clear(); + this.resumeToken = undefined; + + this.docTree.forEach((snapshot: QueryDocumentSnapshot) => { + // Mark each document as deleted. If documents are not deleted, they + // will be send again by the server. + this.changeMap.set( + snapshot.ref.path, + REMOVED as DocumentSnapshotBuilder, + ); + }); + + this.current = false; + } + + /** + * Closes the stream and calls onError() if the stream is still active. + * @private + * @internal + */ + private closeStream(err: GoogleError): void { + if (this.isActive) { + logger('Watch.closeStream', this.requestTag, 'Invoking onError: ', err); + this.onError(err); + } + this.shutdown(); + } + + /** + * Re-opens the stream unless the specified error is considered permanent. + * Clears the change map. + * @private + * @internal + */ + private maybeReopenStream(err: GoogleError): void { + if (this.isActive && !this.isPermanentWatchError(err)) { + logger( + 'Watch.maybeReopenStream', + this.requestTag, + 'Stream ended, re-opening after retryable error:', + err, + ); + this.changeMap.clear(); + + if (this.isResourceExhaustedError(err)) { + this.backoff.resetToMax(); + } + + this.initStream(); + } else { + this.closeStream(err); + } + } + + /** + * Cancels the current idle timeout and reschedules a new timer. + * + * @private + * @internal + */ + private resetIdleTimeout(): void { + if (this.idleTimeoutHandle) { + clearTimeout(this.idleTimeoutHandle); + } + + this.idleTimeoutHandle = delayExecution(() => { + logger( + 'Watch.resetIdleTimeout', + this.requestTag, + 'Resetting stream after idle timeout', + ); + this.currentStream?.end(); + this.currentStream = null; + + const error = new GoogleError('Watch stream idle timeout'); + error.code = Status.UNKNOWN; + this.maybeReopenStream(error); + }, WATCH_IDLE_TIMEOUT_MS); + } + + /** + * Helper to restart the outgoing stream to the backend. + * @private + * @internal + */ + private resetStream(): void { + logger('Watch.resetStream', this.requestTag, 'Restarting stream'); + if (this.currentStream) { + this.currentStream.end(); + this.currentStream = null; + } + this.initStream(); + } + + /** + * Initializes a new stream to the backend with backoff. + * @private + * @internal + */ + private initStream(): void { + this.backoff + .backoffAndWait() + .then(async () => { + if (!this.isActive) { + logger( + 'Watch.initStream', + this.requestTag, + 'Not initializing inactive stream', + ); + return; + } + + await this.firestore.initializeIfNeeded(this.requestTag); + + const request: api.IListenRequest = {}; + request.database = this.firestore.formattedName; + request.addTarget = this.getTarget(this.resumeToken); + + // Note that we need to call the internal _listen API to pass additional + // header values in readWriteStream. + return this.firestore + .requestStream( + 'listen', + /* bidirectional= */ true, + request, + this.requestTag, + ) + .then(backendStream => { + if (!this.isActive) { + logger( + 'Watch.initStream', + this.requestTag, + 'Closing inactive stream', + ); + backendStream.emit('end'); + backendStream.on('error', () => { + // Note that emitting 'end' above does not prevent the Duplex + // from receiving potential errors from the backend. Since the + // stream is no longer active (`isActive` is false), we + // swallow / ignore any errors it may receive. + }); + return; + } + logger('Watch.initStream', this.requestTag, 'Opened new stream'); + this.currentStream = backendStream; + this.resetIdleTimeout(); + + this.currentStream!.on('data', (proto: api.IListenResponse) => { + this.resetIdleTimeout(); + this.onData(proto); + }) + .on('error', err => { + if (this.currentStream === backendStream) { + this.currentStream = null; + this.maybeReopenStream(err); + } + }) + .on('end', () => { + if (this.currentStream === backendStream) { + this.currentStream = null; + + const err = new GoogleError('Stream ended unexpectedly'); + err.code = Status.UNKNOWN; + this.maybeReopenStream(err); + } + }); + this.currentStream!.resume(); + }); + }) + .catch(err => { + this.closeStream(err); + }); + } + + /** + * Handles 'data' events and closes the stream if the response type is + * invalid. + * @private + * @internal + */ + private onData(proto: api.IListenResponse): void { + if (proto.targetChange) { + logger('Watch.onData', this.requestTag, 'Processing target change'); + const change = proto.targetChange; + const noTargetIds = !change.targetIds || change.targetIds.length === 0; + if (change.targetChangeType === 'NO_CHANGE') { + if (noTargetIds && change.readTime && this.current) { + // This means everything is up-to-date, so emit the current + // set of docs as a snapshot, if there were changes. + this.pushSnapshot( + Timestamp.fromProto(change.readTime), + change.resumeToken!, + ); + } + } else if (change.targetChangeType === 'ADD') { + if (WATCH_TARGET_ID !== change.targetIds![0]) { + this.closeStream(Error('Unexpected target ID sent by server')); + } + } else if (change.targetChangeType === 'REMOVE') { + let code = Status.INTERNAL; + let message = 'internal error'; + if (change.cause) { + code = change.cause.code!; + message = change.cause.message!; + } + // @todo: Surface a .code property on the exception. + this.closeStream(new Error('Error ' + code + ': ' + message)); + } else if (change.targetChangeType === 'RESET') { + // Whatever changes have happened so far no longer matter. + this.resetDocs(); + } else if (change.targetChangeType === 'CURRENT') { + this.current = true; + } else { + this.closeStream( + new Error('Unknown target change type: ' + JSON.stringify(change)), + ); + } + + if ( + change.resumeToken && + this.affectsTarget(change.targetIds!, WATCH_TARGET_ID) + ) { + this.backoff.reset(); + } + } else if (proto.documentChange) { + logger('Watch.onData', this.requestTag, 'Processing change event'); + + // No other targetIds can show up here, but we still need to see + // if the targetId was in the added list or removed list. + const targetIds = proto.documentChange.targetIds || []; + const removedTargetIds = proto.documentChange.removedTargetIds || []; + let changed = false; + let removed = false; + for (let i = 0; i < targetIds.length; i++) { + if (targetIds[i] === WATCH_TARGET_ID) { + changed = true; + } + } + for (let i = 0; i < removedTargetIds.length; i++) { + if (removedTargetIds[i] === WATCH_TARGET_ID) { + removed = true; + } + } + + const document = proto.documentChange.document!; + const name = document.name!; + const relativeName = + QualifiedResourcePath.fromSlashSeparatedString(name).relativeName; + + if (changed) { + logger('Watch.onData', this.requestTag, 'Received document change'); + const ref = this.firestore.doc(relativeName); + const snapshot = new DocumentSnapshotBuilder( + ref.withConverter(this._converter), + ); + snapshot.fieldsProto = document.fields || {}; + snapshot.createTime = Timestamp.fromProto(document.createTime!); + snapshot.updateTime = Timestamp.fromProto(document.updateTime!); + this.changeMap.set(relativeName, snapshot); + } else if (removed) { + logger('Watch.onData', this.requestTag, 'Received document remove'); + this.changeMap.set( + relativeName, + REMOVED as DocumentSnapshotBuilder, + ); + } + } else if (proto.documentDelete || proto.documentRemove) { + logger('Watch.onData', this.requestTag, 'Processing remove event'); + const name = (proto.documentDelete || proto.documentRemove)!.document!; + const relativeName = + QualifiedResourcePath.fromSlashSeparatedString(name).relativeName; + this.changeMap.set( + relativeName, + REMOVED as DocumentSnapshotBuilder, + ); + } else if (proto.filter) { + logger('Watch.onData', this.requestTag, 'Processing filter update'); + if (proto.filter.count !== this.currentSize()) { + // We need to remove all the current results. + this.resetDocs(); + // The filter didn't match, so re-issue the query. + this.resetStream(); + } + } else { + this.closeStream( + new Error('Unknown listen response type: ' + JSON.stringify(proto)), + ); + } + } + + /** + * Checks if the current target id is included in the list of target ids. + * If no targetIds are provided, returns true. + * @private + * @internal + */ + private affectsTarget( + targetIds: number[] | undefined, + currentId: number, + ): boolean { + if (targetIds === undefined || targetIds.length === 0) { + return true; + } + + for (const targetId of targetIds) { + if (targetId === currentId) { + return true; + } + } + + return false; + } + + /** + * Assembles a new snapshot from the current set of changes and invokes the + * user's callback. Clears the current changes on completion. + * @private + * @internal + */ + private pushSnapshot( + readTime: Timestamp, + nextResumeToken?: Uint8Array, + ): void { + const appliedChanges = this.computeSnapshot(readTime); + + if (!this.hasPushed || appliedChanges.length > 0) { + logger( + 'Watch.pushSnapshot', + this.requestTag, + 'Sending snapshot with %d changes and %d documents', + String(appliedChanges.length), + this.docTree.length, + ); + // We pass the current set of changes, even if `docTree` is modified later. + const currentTree = this.docTree; + this.onNext( + readTime, + currentTree.length, + () => currentTree.keys, + () => appliedChanges, + ); + this.hasPushed = true; + } + + this.changeMap.clear(); + this.resumeToken = nextResumeToken; + } + + /** + * Applies a document delete to the document tree and the document map. + * Returns the corresponding DocumentChange event. + * @private + * @internal + */ + private deleteDoc(name: string): DocumentChange { + assert(this.docMap.has(name), 'Document to delete does not exist'); + const oldDocument = this.docMap.get(name)!; + const existing = this.docTree.find(oldDocument); + const oldIndex = existing.index; + this.docTree = existing.remove(); + this.docMap.delete(name); + return new DocumentChange(ChangeType.removed, oldDocument, oldIndex, -1); + } + + /** + * Applies a document add to the document tree and the document map. Returns + * the corresponding DocumentChange event. + * @private + * @internal + */ + private addDoc( + newDocument: QueryDocumentSnapshot, + ): DocumentChange { + const name = newDocument.ref.path; + assert(!this.docMap.has(name), 'Document to add already exists'); + this.docTree = this.docTree.insert(newDocument, null); + const newIndex = this.docTree.find(newDocument).index; + this.docMap.set(name, newDocument); + return new DocumentChange(ChangeType.added, newDocument, -1, newIndex); + } + + /** + * Applies a document modification to the document tree and the document map. + * Returns the DocumentChange event for successful modifications. + * @private + * @internal + */ + private modifyDoc( + newDocument: QueryDocumentSnapshot, + ): DocumentChange | null { + const name = newDocument.ref.path; + assert(this.docMap.has(name), 'Document to modify does not exist'); + const oldDocument = this.docMap.get(name)!; + if (!oldDocument.updateTime.isEqual(newDocument.updateTime)) { + const removeChange = this.deleteDoc(name); + const addChange = this.addDoc(newDocument); + return new DocumentChange( + ChangeType.modified, + newDocument, + removeChange.oldIndex, + addChange.newIndex, + ); + } + return null; + } + + /** + * Applies the mutations in changeMap to both the document tree and the + * document lookup map. Modified docMap in-place and returns the updated + * state. + * @private + * @internal + */ + private computeSnapshot( + readTime: Timestamp, + ): Array> { + const changeSet = this.extractCurrentChanges(readTime); + const appliedChanges: Array> = []; + + // Process the sorted changes in the order that is expected by our clients + // (removals, additions, and then modifications). We also need to sort the + // individual changes to assure that oldIndex/newIndex keep incrementing. + changeSet.deletes.sort((name1, name2) => { + // Deletes are sorted based on the order of the existing document. + return this.getComparator()( + this.docMap.get(name1)!, + this.docMap.get(name2)!, + ); + }); + changeSet.deletes.forEach(name => { + const change = this.deleteDoc(name); + appliedChanges.push(change); + }); + + changeSet.adds.sort(this.getComparator()); + changeSet.adds.forEach(snapshot => { + const change = this.addDoc(snapshot); + appliedChanges.push(change); + }); + + changeSet.updates.sort(this.getComparator()); + changeSet.updates.forEach(snapshot => { + const change = this.modifyDoc(snapshot); + if (change) { + appliedChanges.push(change); + } + }); + + assert( + this.docTree.length === this.docMap.size, + 'The update document ' + + 'tree and document map should have the same number of entries.', + ); + + return appliedChanges; + } + + /** + * Determines whether a watch error is considered permanent and should not be + * retried. Errors that don't provide a GRPC error code are always considered + * transient in this context. + * + * @private + * @internal + * @param error An error object. + * @returns Whether the error is permanent. + */ + private isPermanentWatchError(error: GoogleError): boolean { + if (error.code === undefined) { + logger( + 'Watch.isPermanentError', + this.requestTag, + 'Unable to determine error code: ', + error, + ); + return false; + } + + switch (error.code) { + case Status.ABORTED: + case Status.CANCELLED: + case Status.UNKNOWN: + case Status.DEADLINE_EXCEEDED: + case Status.RESOURCE_EXHAUSTED: + case Status.INTERNAL: + case Status.UNAVAILABLE: + case Status.UNAUTHENTICATED: + return false; + default: + return true; + } + } + + /** + * Determines whether we need to initiate a longer backoff due to system + * overload. + * + * @private + * @internal + * @param error A GRPC Error object that exposes an error code. + * @returns Whether we need to back off our retries. + */ + private isResourceExhaustedError(error: GoogleError): boolean { + return error.code === Status.RESOURCE_EXHAUSTED; + } + + /** Closes the stream and clears all timeouts. */ + private shutdown(): void { + if (this.isActive) { + this.isActive = false; + if (this.idleTimeoutHandle) { + clearTimeout(this.idleTimeoutHandle); + this.idleTimeoutHandle = undefined; + } + this.firestore.unregisterListener(); + } + + this.currentStream?.end(); + this.currentStream = null; + } +} + +/** + * Creates a new Watch instance to listen on DocumentReferences. + * + * @private + * @internal + */ +export class DocumentWatch< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> extends Watch { + constructor( + firestore: Firestore, + private readonly ref: DocumentReference, + ) { + super(firestore, ref._converter); + } + + getComparator(): DocumentComparator { + return DOCUMENT_WATCH_COMPARATOR; + } + + getTarget(resumeToken?: Uint8Array): google.firestore.v1.ITarget { + const formattedName = this.ref.formattedName; + return { + documents: { + documents: [formattedName], + }, + targetId: WATCH_TARGET_ID, + resumeToken, + }; + } +} + +/** + * Creates a new Watch instance to listen on Queries. + * + * @private + * @internal + */ +export class QueryWatch< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> extends Watch { + private comparator: DocumentComparator; + + constructor( + firestore: Firestore, + private readonly query: Query, + converter?: firestore.FirestoreDataConverter, + ) { + super(firestore, converter); + this.comparator = query.comparator(); + } + + getComparator(): DocumentComparator { + return this.query.comparator(); + } + + getTarget(resumeToken?: Uint8Array): google.firestore.v1.ITarget { + const query = this.query.toProto(); + return {query, targetId: WATCH_TARGET_ID, resumeToken}; + } +} diff --git a/handwritten/firestore/dev/src/write-batch.ts b/handwritten/firestore/dev/src/write-batch.ts new file mode 100644 index 00000000000..0b9492011d3 --- /dev/null +++ b/handwritten/firestore/dev/src/write-batch.ts @@ -0,0 +1,938 @@ +/*! + * Copyright 2019 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as firestore from '@google-cloud/firestore'; + +import {google} from '../protos/firestore_v1_proto_api'; +import { + DocumentMask, + DocumentSnapshot, + DocumentTransform, + Precondition, +} from './document'; +import {Firestore} from './index'; +import {logger} from './logger'; +import {FieldPath, validateFieldPath} from './path'; +import {validateDocumentReference} from './reference/helpers'; +import {Serializer, validateUserInput} from './serializer'; +import {Timestamp} from './timestamp'; +import {FirestoreUnaryMethod, UpdateMap} from './types'; +import { + getRetryCodes, + isObject, + isPlainObject, + requestTag, + wrapError, +} from './util'; +import { + customObjectMessage, + invalidArgumentMessage, + RequiredArgumentOptions, + validateMaxNumberOfArguments, + validateMinNumberOfArguments, + validateOptional, +} from './validate'; +import {StatusCode} from './status-code'; + +import api = google.firestore.v1; +import { + ATTRIBUTE_KEY_DOC_COUNT, + ATTRIBUTE_KEY_IS_TRANSACTIONAL, + SPAN_NAME_BATCH_COMMIT, +} from './telemetry/trace-util'; + +/** + * A WriteResult wraps the write time set by the Firestore servers on sets(), + * updates(), and creates(). + * + * @class WriteResult + */ +export class WriteResult implements firestore.WriteResult { + /** + * @private + * + * @param _writeTime The time of the corresponding document write. + */ + constructor(private readonly _writeTime: Timestamp) {} + + /** + * The write time as set by the Firestore servers. + * + * @type {Timestamp} + * @name WriteResult#writeTime + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({foo: 'bar'}).then(writeResult => { + * console.log(`Document written at: ${writeResult.writeTime.toDate()}`); + * }); + * ``` + */ + get writeTime(): Timestamp { + return this._writeTime; + } + + /** + * Returns true if this `WriteResult` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @returns true if this `WriteResult` is equal to the provided value. + */ + isEqual(other: firestore.WriteResult): boolean { + return ( + this === other || + (other instanceof WriteResult && + this._writeTime.isEqual(other._writeTime)) + ); + } +} + +/** + * A lazily-evaluated write that allows us to detect the Project ID before + * serializing the request. + * @private + * @internal + */ +export type PendingWriteOp = () => api.IWrite; + +/** + * A Firestore WriteBatch that can be used to atomically commit multiple write + * operations at once. + * + * @class WriteBatch + */ +export class WriteBatch implements firestore.WriteBatch { + protected readonly _firestore: Firestore; + private readonly _serializer: Serializer; + private readonly _allowUndefined: boolean; + + /** + * An array of document paths and the corresponding write operations that are + * executed as part of the commit. The resulting `api.IWrite` will be sent to + * the backend. + * + * @private + * @internal + */ + private readonly _ops: Array<{docPath: string; op: PendingWriteOp}> = []; + + private _committed = false; + + /** + * The number of writes in this batch. + * @private + * @internal + */ + get _opCount(): number { + return this._ops.length; + } + + /** @private */ + constructor(firestore: Firestore) { + this._firestore = firestore; + this._serializer = new Serializer(firestore); + this._allowUndefined = !!firestore._settings.ignoreUndefinedProperties; + } + + /** + * Checks if this write batch has any pending operations. + * + * @private + * @internal + */ + get isEmpty(): boolean { + return this._ops.length === 0; + } + + /** + * Throws an error if this batch has already been committed. + * + * @private + * @internal + */ + private verifyNotCommitted(): void { + if (this._committed) { + throw new Error('Cannot modify a WriteBatch that has been committed.'); + } + } + + /** + * Create a document with the provided object values. This will fail the batch + * if a document exists at its location. + * + * @param {DocumentReference} documentRef A reference to the document to be + * created. + * @param {T} data The object to serialize as the document. + * @throws {Error} If the provided input is not a valid Firestore document. + * @returns {WriteBatch} This WriteBatch instance. Used for chaining + * method calls. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * let documentRef = firestore.collection('col').doc(); + * + * writeBatch.create(documentRef, {foo: 'bar'}); + * + * writeBatch.commit().then(() => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + create( + documentRef: firestore.DocumentReference, + data: firestore.WithFieldValue, + ): WriteBatch { + const ref = validateDocumentReference('documentRef', documentRef); + const firestoreData = ref._converter.toFirestore( + data as firestore.WithFieldValue, + ); + validateDocumentData( + 'data', + firestoreData, + /* allowDeletes= */ false, + this._allowUndefined, + ); + + this.verifyNotCommitted(); + + const transform = DocumentTransform.fromObject(ref, firestoreData); + transform.validate(); + + const precondition = new Precondition({exists: false}); + + const op: PendingWriteOp = () => { + const document = DocumentSnapshot.fromObject(ref, firestoreData); + const write = document.toWriteProto(); + if (!transform.isEmpty) { + write.updateTransforms = transform.toProto(this._serializer); + } + write.currentDocument = precondition.toProto(); + return write; + }; + + this._ops.push({docPath: documentRef.path, op}); + + return this; + } + + /** + * Deletes a document from the database. + * + * @param {DocumentReference} documentRef A reference to the document to be + * deleted. + * @param {Precondition=} precondition A precondition to enforce for this + * delete. + * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the + * document was last updated at lastUpdateTime. Fails the batch if the + * document doesn't exist or was last updated at a different time. + * @param {boolean= } precondition.exists If set to true, enforces that the target + * document must or must not exist. + * @returns {WriteBatch} This WriteBatch instance. Used for chaining + * method calls. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * let documentRef = firestore.doc('col/doc'); + * + * writeBatch.delete(documentRef); + * + * writeBatch.commit().then(() => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + delete( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + documentRef: firestore.DocumentReference, + precondition?: firestore.Precondition, + ): WriteBatch { + const ref = validateDocumentReference('documentRef', documentRef); + validateDeletePrecondition('precondition', precondition, {optional: true}); + + this.verifyNotCommitted(); + + const conditions = new Precondition(precondition); + + const op: PendingWriteOp = () => { + const write: api.IWrite = {delete: ref.formattedName}; + if (!conditions.isEmpty) { + write.currentDocument = conditions.toProto(); + } + return write; + }; + + this._ops.push({docPath: documentRef.path, op}); + + return this; + } + + set( + documentRef: firestore.DocumentReference, + data: firestore.PartialWithFieldValue, + options: firestore.SetOptions, + ): WriteBatch; + set( + documentRef: firestore.DocumentReference, + data: firestore.WithFieldValue, + ): WriteBatch; + /** + * Write to the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document does not + * exist yet, it will be created. If you pass [SetOptions]{@link SetOptions}, + * the provided data can be merged into the existing document. + * + * @param {DocumentReference} documentRef A reference to the document to be + * set. + * @param {T|Partial} data The object to serialize as the document. + * @param {SetOptions=} options An object to configure the set behavior. + * @param {boolean=} options.merge - If true, set() merges the values + * specified in its data argument. Fields omitted from this set() call + * remain untouched. If your input sets any field to an empty map, all nested + * fields are overwritten. + * @param {Array.=} options.mergeFields - If provided, + * set() only replaces the specified field paths. Any field path that is no + * specified is ignored and remains untouched. If your input sets any field to + * an empty map, all nested fields are overwritten. + * @throws {Error} If the provided input is not a valid Firestore document. + * @returns {WriteBatch} This WriteBatch instance. Used for chaining + * method calls. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * let documentRef = firestore.doc('col/doc'); + * + * writeBatch.set(documentRef, {foo: 'bar'}); + * + * writeBatch.commit().then(() => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + set( + documentRef: firestore.DocumentReference, + data: firestore.PartialWithFieldValue, + options?: firestore.SetOptions, + ): WriteBatch { + validateSetOptions('options', options, {optional: true}); + const mergeLeaves = options && 'merge' in options && options.merge; + const mergePaths = options && 'mergeFields' in options; + const ref = validateDocumentReference('documentRef', documentRef); + let firestoreData: firestore.DocumentData; + if (mergeLeaves || mergePaths) { + firestoreData = ref._converter.toFirestore(data, options); + } else { + firestoreData = ref._converter.toFirestore(data as AppModelType); + } + validateDocumentData( + 'data', + firestoreData, + /* allowDeletes= */ !!(mergePaths || mergeLeaves), + this._allowUndefined, + ); + + this.verifyNotCommitted(); + + let documentMask: DocumentMask; + + if (mergePaths) { + documentMask = DocumentMask.fromFieldMask( + (options as {mergeFields: Array}).mergeFields, + ); + firestoreData = documentMask.applyTo(firestoreData); + } + + const transform = DocumentTransform.fromObject(ref, firestoreData); + transform.validate(); + + const op: PendingWriteOp = () => { + const document = DocumentSnapshot.fromObject(ref, firestoreData); + + if (mergePaths) { + documentMask!.removeFields(transform.fields); + } else if (mergeLeaves) { + documentMask = DocumentMask.fromObject(firestoreData); + } + + const write = document.toWriteProto(); + if (!transform.isEmpty) { + write.updateTransforms = transform.toProto(this._serializer); + } + if (mergePaths || mergeLeaves) { + write.updateMask = documentMask!.toProto(); + } + return write; + }; + + this._ops.push({docPath: documentRef.path, op}); + + return this; + } + + /** + * Update fields of the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document + * doesn't yet exist, the update fails and the entire batch will be rejected. + * + * The update() method accepts either an object with field paths encoded as + * keys and field values encoded as values, or a variable number of arguments + * that alternate between field paths and field values. Nested fields can be + * updated by providing dot-separated field path strings or by providing + * FieldPath objects. + * + * A Precondition restricting this update can be specified as the last + * argument. + * + * @param {DocumentReference} documentRef A reference to the document to be + * updated. + * @param {UpdateData|string|FieldPath} dataOrField An object + * containing the fields and values with which to update the document + * or the path of the first field to update. + * @param { + * ...(Precondition|*|string|FieldPath)} preconditionOrValues - + * An alternating list of field paths and values to update or a Precondition + * to restrict this update. + * @throws {Error} If the provided input is not valid Firestore data. + * @returns {WriteBatch} This WriteBatch instance. Used for chaining + * method calls. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * let documentRef = firestore.doc('col/doc'); + * + * writeBatch.update(documentRef, {foo: 'bar'}); + * + * writeBatch.commit().then(() => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + update< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, + >( + documentRef: firestore.DocumentReference, + dataOrField: + | firestore.UpdateData + | string + | firestore.FieldPath, + ...preconditionOrValues: Array< + | {lastUpdateTime?: firestore.Timestamp} + | unknown + | string + | firestore.FieldPath + > + ): WriteBatch { + // eslint-disable-next-line prefer-rest-params + validateMinNumberOfArguments('WriteBatch.update', arguments, 2); + validateDocumentReference('documentRef', documentRef); + + this.verifyNotCommitted(); + + const updateMap = new Map(); + let precondition = new Precondition({exists: true}); + + const argumentError = + 'Update() requires either a single JavaScript ' + + 'object or an alternating list of field/value pairs that can be ' + + 'followed by an optional precondition.'; + + const usesVarargs = + typeof dataOrField === 'string' || dataOrField instanceof FieldPath; + + if (usesVarargs) { + const argumentOffset = 1; // Respect 'documentRef' in the error message + const fieldOrValues = [dataOrField, ...preconditionOrValues]; + try { + for (let i = 0; i < fieldOrValues.length; i += 2) { + if (i === fieldOrValues.length - 1) { + const maybePrecondition = fieldOrValues[i]; + validateUpdatePrecondition(i + argumentOffset, maybePrecondition); + precondition = new Precondition(maybePrecondition); + } else { + const maybeFieldPath = fieldOrValues[i]; + validateFieldPath(i + argumentOffset, maybeFieldPath); + // Unlike the `validateMinNumberOfArguments` invocation above, this + // validation can be triggered both from `WriteBatch.update()` and + // `DocumentReference.update()`. Hence, we don't use the fully + // qualified API name in the error message. + validateMinNumberOfArguments('update', fieldOrValues, i + 1); + + const fieldPath = FieldPath.fromArgument(maybeFieldPath); + validateFieldValue( + i + argumentOffset, + fieldOrValues[i + 1], + this._allowUndefined, + fieldPath, + ); + updateMap.set(fieldPath, fieldOrValues[i + 1]); + } + } + } catch (err) { + logger('WriteBatch.update', null, 'Varargs validation failed:', err); + // We catch the validation error here and re-throw to provide a better + // error message. + throw new Error(`${argumentError} ${err.message}`); + } + } else { + try { + validateUpdateMap('dataOrField', dataOrField, this._allowUndefined); + // eslint-disable-next-line prefer-rest-params + validateMaxNumberOfArguments('update', arguments, 3); + Object.entries( + dataOrField as firestore.UpdateData, + ).forEach(([key, value]) => { + // Skip `undefined` values (can be hit if `ignoreUndefinedProperties` + // is set) + if (value !== undefined) { + validateFieldPath(key, key); + updateMap.set(FieldPath.fromArgument(key), value); + } + }); + + if (preconditionOrValues.length > 0) { + validateUpdatePrecondition( + 'preconditionOrValues', + preconditionOrValues[0], + ); + precondition = new Precondition( + preconditionOrValues[0] as { + lastUpdateTime?: Timestamp; + }, + ); + } + } catch (err) { + logger( + 'WriteBatch.update', + null, + 'Non-varargs validation failed:', + err, + ); + // We catch the validation error here and prefix the error with a custom + // message to describe the usage of update() better. + throw new Error(`${argumentError} ${err.message}`); + } + } + + validateNoConflictingFields('dataOrField', updateMap); + + const transform = DocumentTransform.fromUpdateMap(documentRef, updateMap); + transform.validate(); + + const documentMask = DocumentMask.fromUpdateMap(updateMap); + + const op: PendingWriteOp = () => { + const document = DocumentSnapshot.fromUpdateMap(documentRef, updateMap); + const write = document.toWriteProto(); + write.updateMask = documentMask.toProto(); + if (!transform.isEmpty) { + write.updateTransforms = transform.toProto(this._serializer); + } + write.currentDocument = precondition.toProto(); + return write; + }; + + this._ops.push({docPath: documentRef.path, op}); + + return this; + } + + /** + * Atomically commits all pending operations to the database and verifies all + * preconditions. Fails the entire write if any precondition is not met. + * + * @returns {Promise.>} A Promise that resolves + * when this batch completes. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * let documentRef = firestore.doc('col/doc'); + * + * writeBatch.set(documentRef, {foo: 'bar'}); + * + * writeBatch.commit().then(() => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + commit(): Promise { + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_BATCH_COMMIT, + async () => { + // Capture the error stack to preserve stack tracing across async calls. + const stack = Error().stack!; + + // Commits should also be retried when they fail with status code ABORTED. + const retryCodes = [StatusCode.ABORTED, ...getRetryCodes('commit')]; + + return this._commit({retryCodes}) + .then(response => { + return (response.writeResults || []).map( + writeResult => + new WriteResult( + Timestamp.fromProto( + writeResult.updateTime || response.commitTime!, + ), + ), + ); + }) + .catch(err => { + throw wrapError(err, stack); + }); + }, + { + [ATTRIBUTE_KEY_IS_TRANSACTIONAL]: false, + [ATTRIBUTE_KEY_DOC_COUNT]: this._opCount, + }, + ); + } + + /** + * Commit method that takes an optional transaction ID. + * + * @private + * @internal + * @param commitOptions Options to use for this commit. + * @param commitOptions.transactionId The transaction ID of this commit. + * @param commitOptions.requestTag A unique client-assigned identifier for + * this request. + * @returns A Promise that resolves when this batch completes. + */ + async _commit(commitOptions?: { + transactionId?: Uint8Array; + requestTag?: string; + retryCodes?: number[]; + methodName?: FirestoreUnaryMethod; + }): Promise { + // Note: We don't call `verifyNotCommitted()` to allow for retries. + this._committed = true; + + const tag = commitOptions?.requestTag ?? requestTag(); + await this._firestore.initializeIfNeeded(tag); + + // Note that the request may not always be of type ICommitRequest. This is + // just here to ensure type safety. + const request: api.ICommitRequest = { + database: this._firestore.formattedName, + writes: this._ops.map(op => op.op()), + }; + + if (commitOptions?.transactionId) { + request.transaction = commitOptions.transactionId; + } + + logger( + 'WriteBatch.commit', + tag, + 'Sending %d writes', + request.writes!.length, + ); + + return this._firestore.request( + commitOptions?.methodName || 'commit', + request as Req, + tag, + commitOptions?.retryCodes, + ); + } + + /** + * Resets the WriteBatch and dequeues all pending operations. + * @private + * @internal + */ + _reset(): void { + this._ops.splice(0); + this._committed = false; + } +} + +/** + * Validates the use of 'value' as a Precondition and enforces that 'exists' + * and 'lastUpdateTime' use valid types. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The object to validate + * @param options Options describing other things for this function to validate. + */ +function validatePrecondition( + arg: string | number, + value: unknown, + options?: {allowedExistsValues?: boolean[]}, +): void { + if (typeof value !== 'object' || value === null) { + throw new Error('Input is not an object.'); + } + + const precondition = value as {[k: string]: unknown}; + + let conditions = 0; + + if (precondition.exists !== undefined) { + ++conditions; + if (typeof precondition.exists !== 'boolean') { + throw new Error( + `${invalidArgumentMessage( + arg, + 'precondition', + )} "exists" is not a boolean.'`, + ); + } + if ( + options?.allowedExistsValues && + options.allowedExistsValues.indexOf(precondition.exists) < 0 + ) { + throw new Error( + `${invalidArgumentMessage(arg, 'precondition')} ` + + `"exists" is not allowed to have the value ${precondition.exists} ` + + `(allowed values: ${options.allowedExistsValues.join(', ')})`, + ); + } + } + + if (precondition.lastUpdateTime !== undefined) { + ++conditions; + if (!(precondition.lastUpdateTime instanceof Timestamp)) { + throw new Error( + `${invalidArgumentMessage( + arg, + 'precondition', + )} "lastUpdateTime" is not a Firestore Timestamp.`, + ); + } + } + + if (conditions > 1) { + throw new Error( + `${invalidArgumentMessage( + arg, + 'precondition', + )} Input specifies more than one precondition.`, + ); + } +} + +/** + * Validates the use of 'value' as an update Precondition. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The object to validate. + * @param options Optional validation options specifying whether the value can + * be omitted. + */ +function validateUpdatePrecondition( + arg: string | number, + value: unknown, + options?: RequiredArgumentOptions, +): asserts value is {lastUpdateTime?: Timestamp} { + if (!validateOptional(value, options)) { + validatePrecondition(arg, value, {allowedExistsValues: [true]}); + } +} + +/** + * Validates the use of 'value' as a delete Precondition. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The object to validate. + * @param options Optional validation options specifying whether the value can + * be omitted. + */ +function validateDeletePrecondition( + arg: string | number, + value: unknown, + options?: RequiredArgumentOptions, +): void { + if (!validateOptional(value, options)) { + validatePrecondition(arg, value); + } +} + +/** + * Validates the use of 'value' as SetOptions and enforces that 'merge' is a + * boolean. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The object to validate. + * @param options Optional validation options specifying whether the value can + * be omitted. + * @throws if the input is not a valid SetOptions object. + */ +export function validateSetOptions( + arg: string | number, + value: unknown, + options?: RequiredArgumentOptions, +): void { + if (!validateOptional(value, options)) { + if (!isObject(value)) { + throw new Error( + `${invalidArgumentMessage( + arg, + 'set() options argument', + )} Input is not an object.`, + ); + } + + const setOptions = value as {mergeFields: Array}; + + if ('mergeFields' in setOptions) { + for (let i = 0; i < setOptions.mergeFields.length; ++i) { + try { + validateFieldPath(i, setOptions.mergeFields[i]); + } catch (err) { + throw new Error( + `${invalidArgumentMessage( + arg, + 'set() options argument', + )} "mergeFields" is not valid: ${err.message}`, + ); + } + } + } + + if ('merge' in setOptions && 'mergeFields' in setOptions) { + throw new Error( + `${invalidArgumentMessage( + arg, + 'set() options argument', + )} You cannot specify both "merge" and "mergeFields".`, + ); + } + } +} + +/** + * Validates a JavaScript object for usage as a Firestore document. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param obj JavaScript object to validate. + * @param allowDeletes Whether to allow FieldValue.delete() sentinels. + * @param allowUndefined Whether to allow nested properties that are `undefined`. + * @throws when the object is invalid. + */ +export function validateDocumentData( + arg: string | number, + obj: unknown, + allowDeletes: boolean, + allowUndefined: boolean, +): void { + if (!isPlainObject(obj)) { + throw new Error(customObjectMessage(arg, obj)); + } + + validateUserInput(arg, obj, 'Firestore document', { + allowDeletes: allowDeletes ? 'all' : 'none', + allowTransforms: true, + allowUndefined, + }); +} + +/** + * Validates that a value can be used as field value during an update. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param val The value to verify. + * @param allowUndefined Whether to allow nested properties that are `undefined`. + * @param path The path to show in the error message. + */ +export function validateFieldValue( + arg: string | number, + val: unknown, + allowUndefined: boolean, + path?: FieldPath, +): void { + validateUserInput( + arg, + val, + 'Firestore value', + {allowDeletes: 'root', allowTransforms: true, allowUndefined}, + path, + ); +} + +/** + * Validates that the update data does not contain any ambiguous field + * definitions (such as 'a.b' and 'a'). + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param data An update map with field/value pairs. + */ +function validateNoConflictingFields( + arg: string | number, + data: UpdateMap, +): void { + const fields: FieldPath[] = []; + data.forEach((value, key) => { + fields.push(key); + }); + + fields.sort((left, right) => left.compareTo(right)); + + for (let i = 1; i < fields.length; ++i) { + if (fields[i - 1].isPrefixOf(fields[i])) { + throw new Error( + `${invalidArgumentMessage(arg, 'update map')} Field "${ + fields[i - 1] + }" was specified multiple times.`, + ); + } + } +} + +/** + * Validates that a JavaScript object is a map of field paths to field values. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param obj JavaScript object to validate. + * @param allowUndefined Whether to allow nested properties that are `undefined`. + * @throws when the object is invalid. + */ +function validateUpdateMap( + arg: string | number, + obj: unknown, + allowUndefined: boolean, +): void { + if (!isPlainObject(obj)) { + throw new Error(customObjectMessage(arg, obj)); + } + if (Object.keys(obj).length === 0) { + throw new Error('At least one field must be updated.'); + } + validateFieldValue(arg, obj, allowUndefined); +} diff --git a/handwritten/firestore/dev/system-test/firestore.ts b/handwritten/firestore/dev/system-test/firestore.ts new file mode 100644 index 00000000000..2ceca962693 --- /dev/null +++ b/handwritten/firestore/dev/system-test/firestore.ts @@ -0,0 +1,8560 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { + DocumentData, + ExplainMetrics, + PartialWithFieldValue, + QuerySnapshot, + SetOptions, + Settings, + VectorValue, + WithFieldValue, +} from '@google-cloud/firestore'; + +import {afterEach, before, beforeEach, describe, it} from 'mocha'; +import '../test/util/mocha_extensions'; +import {expect, use} from 'chai'; +import * as chaiAsPromised from 'chai-as-promised'; +import * as extend from 'extend'; +import {firestore} from '../protos/firestore_v1_proto_api'; + +import { + AggregateField, + CollectionReference, + DocumentReference, + DocumentSnapshot, + FieldPath, + FieldValue, + Firestore, + GeoPoint, + Query, + QueryDocumentSnapshot, + setLogFunction, + Timestamp, + WriteResult, +} from '../src'; +import {autoId, Deferred} from '../src/util'; +import {TEST_BUNDLE_ID, verifyMetadata} from '../test/bundle'; +import { + bundleToElementArray, + isEnterprise, + Post, + postConverter, + postConverterMerge, + verifyInstance, +} from '../test/util/helpers'; +import {BulkWriter} from '../src/bulk-writer'; +import {Status} from 'google-gax'; +import {QueryPartition} from '../src/query-partition'; +import {CollectionGroup} from '../src/collection-group'; +import IBundleElement = firestore.IBundleElement; +import {Filter} from '../src/filter'; +import {IndexTestHelper} from './index_test_helper'; + +use(chaiAsPromised); + +const version = require('../../package.json').version; + +export class DeferredPromise { + resolve: Function; + reject: Function; + promise: Promise | null; + + constructor() { + this.resolve = () => { + throw new Error('DeferredPromise.resolve has not been initialized'); + }; + this.reject = () => { + throw new Error('DeferredPromise.reject has not been initialized'); + }; + this.promise = null; + } +} + +const firestoreEnv: { + [key: string]: string | undefined; +} = {}; +for (const key in process.env) { + if (key.startsWith('FIRESTORE')) { + firestoreEnv[key] = process.env[key]; + } +} +console.log( + `Running system tests with environment variables:\n ${JSON.stringify( + firestoreEnv, + null, + 2, + )}`, +); + +if (process.env.NODE_ENV === 'DEBUG') { + setLogFunction(console.log); +} + +export function getTestDb(settings: Settings = {}): Firestore { + const internalSettings: Settings = {}; + if (process.env.FIRESTORE_NAMED_DATABASE) { + internalSettings.databaseId = process.env.FIRESTORE_NAMED_DATABASE; + } + + if (process.env.FIRESTORE_TARGET_BACKEND) { + switch (process.env.FIRESTORE_TARGET_BACKEND.toUpperCase()) { + case 'PROD': { + break; + } + case 'QA': { + internalSettings.host = 'staging-firestore.sandbox.googleapis.com'; + break; + } + case 'NIGHTLY': { + internalSettings.host = 'test-firestore.sandbox.googleapis.com'; + break; + } + default: { + break; + } + } + } + + return new Firestore({ + ...internalSettings, + ...settings, // caller settings take precedent over internal settings + }); +} + +export function getTestRoot(settings: Settings = {}): CollectionReference { + return getTestDb(settings).collection(`node_${version}_${autoId()}`); +} + +describe('Firestore class', () => { + let firestore: Firestore; + let randomCol: CollectionReference; + + beforeEach(() => { + randomCol = getTestRoot(); + firestore = randomCol.firestore; + }); + + afterEach(() => verifyInstance(firestore)); + + it('has collection() method', () => { + const ref = firestore.collection('col'); + expect(ref.id).to.equal('col'); + }); + + it('has doc() method', () => { + const ref = firestore.doc('col/doc'); + expect(ref.id).to.equal('doc'); + }); + + it('has getAll() method', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + return Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'a'})]) + .then(() => { + return firestore.getAll(ref1, ref2); + }) + .then(docs => { + expect(docs.length).to.equal(2); + }); + }); + + it.skipEnterprise('can plan a query using default options', async () => { + await randomCol.doc('doc1').set({foo: 1}); + await randomCol.doc('doc2').set({foo: 2}); + await randomCol.doc('doc3').set({foo: 1}); + const explainResults = await randomCol.where('foo', '>', 1).explain(); + + // Should have metrics. + const metrics = explainResults.metrics; + expect(metrics).to.not.be.null; + + // Should have query plan. + const plan = metrics.planSummary; + expect(plan).to.not.be.null; + expect(Object.keys(plan.indexesUsed).length).to.be.greaterThan(0); + + // No execution stats and no snapshot. + expect(metrics.executionStats).to.be.null; + expect(explainResults.snapshot).to.be.null; + }); + + it.skipEnterprise('can plan a query', async () => { + await randomCol.doc('doc1').set({foo: 1}); + await randomCol.doc('doc2').set({foo: 2}); + await randomCol.doc('doc3').set({foo: 1}); + const explainResults = await randomCol + .where('foo', '>', 1) + .explain({analyze: false}); + + // Should have metrics. + const metrics = explainResults.metrics; + expect(metrics).to.not.be.null; + + // Should have query plan. + const plan = metrics.planSummary; + expect(plan).to.not.be.null; + expect(Object.keys(plan.indexesUsed).length).to.be.greaterThan(0); + + // No execution stats and no snapshot. + expect(metrics.executionStats).to.be.null; + expect(explainResults.snapshot).to.be.null; + }); + + it.skipEnterprise('can profile a query', async () => { + await randomCol.doc('doc1').set({foo: 1, bar: 0}); + await randomCol.doc('doc2').set({foo: 2, bar: 1}); + await randomCol.doc('doc3').set({foo: 1, bar: 2}); + const explainResults = await randomCol + .where('foo', '==', 1) + .explain({analyze: true}); + + const metrics = explainResults.metrics; + + expect(metrics.planSummary).to.not.be.null; + expect(metrics.executionStats).to.not.be.null; + expect(explainResults.snapshot).to.not.be.null; + + expect( + Object.keys(metrics.planSummary.indexesUsed).length, + ).to.be.greaterThan(0); + + const stats = metrics.executionStats!; + expect(stats.readOperations).to.be.greaterThan(0); + expect(stats.resultsReturned).to.be.equal(2); + expect( + stats.executionDuration.nanoseconds > 0 || + stats.executionDuration.seconds > 0, + ).to.be.true; + expect(Object.keys(stats.debugStats).length).to.be.greaterThan(0); + + expect(explainResults.snapshot!.size).to.equal(2); + }); + + it.skipEnterprise( + 'can profile a query that does not match any docs', + async () => { + await randomCol.doc('doc1').set({foo: 1, bar: 0}); + await randomCol.doc('doc2').set({foo: 2, bar: 1}); + await randomCol.doc('doc3').set({foo: 1, bar: 2}); + const results = await randomCol.where('foo', '==', 12345).get(); + expect(results.empty).to.be.true; + expect(results.docs.length).to.equal(0); + expect(results.readTime.toMillis()).to.be.greaterThan(0); + + const explainResults = await randomCol + .where('foo', '==', 12345) + .explain({analyze: true}); + + const metrics = explainResults.metrics; + + expect(metrics.planSummary).to.not.be.null; + expect(metrics.executionStats).to.not.be.null; + expect(explainResults.snapshot).to.not.be.null; + + expect( + Object.keys(metrics.planSummary.indexesUsed).length, + ).to.be.greaterThan(0); + + const stats = metrics.executionStats!; + expect(stats.readOperations).to.be.greaterThan(0); + expect(stats.resultsReturned).to.be.equal(0); + expect( + stats.executionDuration.nanoseconds > 0 || + stats.executionDuration.seconds > 0, + ).to.be.true; + expect(Object.keys(stats.debugStats).length).to.be.greaterThan(0); + + expect(explainResults.snapshot!.size).to.equal(0); + }, + ); + + it.skipEnterprise( + 'can stream explain results with default options', + async () => { + await randomCol.doc('doc1').set({foo: 1, bar: 0}); + await randomCol.doc('doc2').set({foo: 2, bar: 1}); + await randomCol.doc('doc3').set({foo: 1, bar: 2}); + let totalResponses = 0; + let totalDocuments = 0; + let metrics: ExplainMetrics | null = null; + const stream = randomCol.explainStream(); + const promise = new Promise((resolve, reject) => { + stream.on('data', data => { + ++totalResponses; + if (data.document) { + ++totalDocuments; + } + if (data.metrics) { + metrics = data.metrics; + } + }); + stream.on('end', () => { + expect(totalResponses).to.equal(1); + expect(totalDocuments).to.equal(0); + expect(metrics).to.not.be.null; + expect(metrics!.planSummary.indexesUsed.length).to.be.greaterThan(0); + expect(metrics!.executionStats).to.be.null; + resolve(true); + }); + stream.on('error', (error: Error) => { + reject(error); + }); + }); + + const success: boolean = await promise; + expect(success).to.be.true; + }, + ); + + it.skipEnterprise('can stream explain results without analyze', async () => { + await randomCol.doc('doc1').set({foo: 1, bar: 0}); + await randomCol.doc('doc2').set({foo: 2, bar: 1}); + await randomCol.doc('doc3').set({foo: 1, bar: 2}); + let totalResponses = 0; + let totalDocuments = 0; + let metrics: ExplainMetrics | null = null; + const stream = randomCol.explainStream({analyze: false}); + const promise = new Promise((resolve, reject) => { + stream.on('data', data => { + ++totalResponses; + if (data.document) { + ++totalDocuments; + } + if (data.metrics) { + metrics = data.metrics; + } + }); + stream.on('end', () => { + expect(totalResponses).to.equal(1); + expect(totalDocuments).to.equal(0); + expect(metrics).to.not.be.null; + expect(metrics!.planSummary.indexesUsed.length).to.be.greaterThan(0); + expect(metrics!.executionStats).to.be.null; + resolve(true); + }); + stream.on('error', (error: Error) => { + reject(error); + }); + }); + + const success: boolean = await promise; + expect(success).to.be.true; + }); + + it.skipEnterprise('can stream explain results with analyze', async () => { + await randomCol.doc('doc1').set({foo: 1, bar: 0}); + await randomCol.doc('doc2').set({foo: 2, bar: 1}); + await randomCol.doc('doc3').set({foo: 1, bar: 2}); + let totalResponses = 0; + let totalDocuments = 0; + let metrics: ExplainMetrics | null = null; + const stream = randomCol + .where('foo', '==', 1) + .explainStream({analyze: true}); + const promise = new Promise((resolve, reject) => { + stream.on('data', data => { + ++totalResponses; + if (data.document) { + ++totalDocuments; + } + if (data.metrics) { + metrics = data.metrics; + } + }); + stream.on('end', () => { + expect(totalResponses).to.equal(2); + expect(totalDocuments).to.equal(2); + expect(metrics).to.not.be.null; + expect(metrics!.planSummary.indexesUsed.length).to.be.greaterThan(0); + expect(metrics!.executionStats).to.not.be.null; + expect(metrics!.executionStats!.resultsReturned).to.equal(2); + resolve(true); + }); + stream.on('error', (error: Error) => { + reject(error); + }); + }); + + const success: boolean = await promise; + expect(success).to.be.true; + }); + + it.skipEnterprise( + 'can plan an aggregate query using default options', + async () => { + await randomCol.doc('doc1').set({foo: 1}); + await randomCol.doc('doc2').set({foo: 2}); + await randomCol.doc('doc3').set({foo: 1}); + const explainResults = await randomCol + .where('foo', '>', 0) + .count() + .explain(); + + const metrics = explainResults.metrics; + + const plan = metrics.planSummary; + expect(plan).to.not.be.null; + expect(Object.keys(plan.indexesUsed).length).to.be.greaterThan(0); + + expect(metrics.executionStats).to.be.null; + expect(explainResults.snapshot).to.be.null; + }, + ); + + it.skipEnterprise('can plan an aggregate query', async () => { + await randomCol.doc('doc1').set({foo: 1}); + await randomCol.doc('doc2').set({foo: 2}); + await randomCol.doc('doc3').set({foo: 1}); + const explainResults = await randomCol + .where('foo', '>', 0) + .count() + .explain({analyze: false}); + + const metrics = explainResults.metrics; + + const plan = metrics.planSummary; + expect(plan).to.not.be.null; + expect(Object.keys(plan.indexesUsed).length).to.be.greaterThan(0); + + expect(metrics.executionStats).to.be.null; + expect(explainResults.snapshot).to.be.null; + }); + + it.skipEnterprise('can profile an aggregate query', async () => { + await randomCol.doc('doc1').set({foo: 1}); + await randomCol.doc('doc2').set({foo: 2}); + await randomCol.doc('doc3').set({foo: 1}); + const explainResults = await randomCol + .where('foo', '<', 3) + .count() + .explain({analyze: true}); + + const metrics = explainResults.metrics; + expect(metrics.planSummary).to.not.be.null; + expect( + Object.keys(metrics.planSummary.indexesUsed).length, + ).to.be.greaterThan(0); + + expect(metrics.executionStats).to.not.be.null; + const stats = metrics.executionStats!; + expect(stats.readOperations).to.be.greaterThan(0); + expect(stats.resultsReturned).to.be.equal(1); + expect( + stats.executionDuration.nanoseconds > 0 || + stats.executionDuration.seconds > 0, + ).to.be.true; + expect(Object.keys(stats.debugStats).length).to.be.greaterThan(0); + + expect(explainResults.snapshot).to.not.be.null; + expect(explainResults.snapshot!.data().count).to.equal(3); + }); + + it.skipEnterprise('can plan a vector query', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); + + const explainResults = await indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: FieldValue.vector([1, 3]), + limit: 10, + distanceMeasure: 'COSINE', + }) + .explain({analyze: false}); + + const metrics = explainResults.metrics; + + const plan = metrics.planSummary; + expect(plan).to.not.be.null; + expect(Object.keys(plan.indexesUsed).length).to.be.greaterThan(0); + + expect(metrics.executionStats).to.be.null; + expect(explainResults.snapshot).to.be.null; + }); + + it.skipEnterprise('can profile a vector query', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); + + const explainResults = await indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: FieldValue.vector([1, 3]), + limit: 10, + distanceMeasure: 'COSINE', + }) + .explain({analyze: true}); + + const metrics = explainResults.metrics; + expect(metrics.planSummary).to.not.be.null; + expect( + Object.keys(metrics.planSummary.indexesUsed).length, + ).to.be.greaterThan(0); + + expect(metrics.executionStats).to.not.be.null; + const stats = metrics.executionStats!; + + expect(stats.readOperations).to.be.greaterThan(0); + expect(stats.resultsReturned).to.be.equal(5); + expect( + stats.executionDuration.nanoseconds > 0 || + stats.executionDuration.seconds > 0, + ).to.be.true; + expect(Object.keys(stats.debugStats).length).to.be.greaterThan(0); + + expect(explainResults.snapshot).to.not.be.null; + expect(explainResults.snapshot!.docs.length).to.equal(5); + }); + + it('getAll() supports array destructuring', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + return Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'a'})]) + .then(() => { + return firestore.getAll(...[ref1, ref2]); + }) + .then(docs => { + expect(docs.length).to.equal(2); + }); + }); + + it('getAll() supports field mask', () => { + const ref1 = randomCol.doc('doc1'); + return ref1 + .set({foo: 'a', bar: 'b'}) + .then(() => { + return firestore.getAll(ref1, {fieldMask: ['foo']}); + }) + .then(docs => { + expect(docs[0].data()).to.deep.equal({foo: 'a'}); + }); + }); + + it('getAll() supports array destructuring with field mask', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + return Promise.all([ref1.set({f: 'a', b: 'b'}), ref2.set({f: 'a', b: 'b'})]) + .then(() => { + return firestore.getAll(...[ref1, ref2], {fieldMask: ['f']}); + }) + .then(docs => { + expect(docs[0].data()).to.deep.equal({f: 'a'}); + expect(docs[1].data()).to.deep.equal({f: 'a'}); + }); + }); + + it('getAll() supports generics', async () => { + const ref1 = randomCol.doc('doc1').withConverter(postConverter); + const ref2 = randomCol.doc('doc2').withConverter(postConverter); + await ref1.set(new Post('post1', 'author1')); + await ref2.set(new Post('post2', 'author2')); + + const docs = await firestore.getAll(ref1, ref2); + expect(docs[0].data()!.toString()).to.deep.equal('post1, by author1'); + expect(docs[1].data()!.toString()).to.deep.equal('post2, by author2'); + }); + + it('cannot make calls after the client has been terminated', async () => { + const ref1 = randomCol.doc('doc1'); + await firestore.terminate(); + return expect(ref1.set({foo: 100})).to.eventually.be.rejectedWith( + 'The client has already been terminated', + ); + }); + + it('throws an error if terminate() is called with active listeners', async () => { + const ref = randomCol.doc('doc-1'); + const unsubscribe = ref.onSnapshot(() => { + // No-op + }); + + await expect(firestore.terminate()).to.eventually.be.rejectedWith( + 'All onSnapshot() listeners must be unsubscribed, and all BulkWriter ' + + 'instances must be closed before terminating the client. There are 1 ' + + 'active listeners and 0 open BulkWriter instances.', + ); + unsubscribe(); + }); + + it('throws an error if terminate() is called with pending BulkWriter operations', async () => { + const writer = firestore.bulkWriter(); + const ref = randomCol.doc('doc-1'); + void writer.set(ref, {foo: 'bar'}); + await expect(firestore.terminate()).to.eventually.be.rejectedWith( + 'All onSnapshot() listeners must be unsubscribed, and all BulkWriter ' + + 'instances must be closed before terminating the client. There are 0 ' + + 'active listeners and 1 open BulkWriter instances.', + ); + }); +}); + +// Skip partition query tests when running against the emulator because +// partition queries are not supported by the emulator. +describe.skipEmulator.skipEnterprise('CollectionGroup class', () => { + const desiredPartitionCount = 3; + const documentCount = 2 * 128 + 127; // Minimum partition size is 128. + + let firestore: Firestore; + let randomColl: CollectionReference; + let collectionGroup: CollectionGroup; + + before(async () => { + randomColl = getTestRoot(); + firestore = randomColl.firestore; + collectionGroup = firestore.collectionGroup(randomColl.id); + + const batch = firestore.batch(); + for (let i = 0; i < documentCount; ++i) { + batch.create(randomColl.doc(), {title: 'post', author: 'author'}); + } + await batch.commit(); + }); + + async function getPartitions( + collectionGroup: CollectionGroup, + desiredPartitionsCount: number, + ): Promise[]> { + const partitions: QueryPartition[] = []; + for await (const partition of collectionGroup.getPartitions( + desiredPartitionsCount, + )) { + partitions.push(partition); + } + return partitions; + } + + async function verifyPartitions( + partitions: QueryPartition[], + ): Promise[]> { + expect(partitions.length).to.not.be.greaterThan(desiredPartitionCount); + + expect(partitions[0].startAt).to.be.undefined; + for (let i = 0; i < partitions.length - 1; ++i) { + // The cursor value is a single DocumentReference + expect( + (partitions[i].endBefore![0] as DocumentReference).isEqual( + partitions[i + 1].startAt![0] as DocumentReference, + ), + ).to.be.true; + } + expect(partitions[partitions.length - 1].endBefore).to.be.undefined; + + // Validate that we can use the partitions to read the original documents. + const documents: QueryDocumentSnapshot[] = []; + for (const partition of partitions) { + documents.push(...(await partition.toQuery().get()).docs); + } + expect(documents.length).to.equal(documentCount); + + return documents; + } + + it('partition query', async () => { + const partitions = await getPartitions( + collectionGroup, + desiredPartitionCount, + ); + await verifyPartitions(partitions); + }); + + it('partition query with manual cursors', async () => { + const partitions = await getPartitions( + collectionGroup, + desiredPartitionCount, + ); + + const documents: QueryDocumentSnapshot[] = []; + for (const partition of partitions) { + let partitionedQuery: Query = collectionGroup.orderBy( + FieldPath.documentId(), + ); + if (partition.startAt) { + partitionedQuery = partitionedQuery.startAt(...partition.startAt); + } + if (partition.endBefore) { + partitionedQuery = partitionedQuery.endBefore(...partition.endBefore); + } + documents.push(...(await partitionedQuery.get()).docs); + } + + expect(documents.length).to.equal(documentCount); + }); + + it('partition query with converter', async () => { + const collectionGroupWithConverter = + collectionGroup.withConverter(postConverter); + const partitions = await getPartitions( + collectionGroupWithConverter, + desiredPartitionCount, + ); + const documents = await verifyPartitions(partitions); + + for (const document of documents) { + expect(document.data()).to.be.an.instanceOf(Post); + } + }); + + it('empty partition query', async () => { + const desiredPartitionCount = 3; + + const collectionGroupId = randomColl.doc().id; + const collectionGroup = firestore.collectionGroup(collectionGroupId); + const partitions = await getPartitions( + collectionGroup, + desiredPartitionCount, + ); + + expect(partitions.length).to.equal(1); + expect(partitions[0].startAt).to.be.undefined; + expect(partitions[0].endBefore).to.be.undefined; + }); +}); + +describe('CollectionReference class', () => { + let firestore: Firestore; + let randomCol: CollectionReference; + + beforeEach(() => { + randomCol = getTestRoot(); + firestore = randomCol.firestore; + }); + + afterEach(() => verifyInstance(firestore)); + + it('has firestore property', () => { + const ref = firestore.collection('col'); + expect(ref.firestore).to.be.an.instanceOf(Firestore); + }); + + it('has id property', () => { + const ref = firestore.collection('col'); + expect(ref.id).to.equal('col'); + }); + + it('has parent property', () => { + const ref = firestore.collection('col/doc/col'); + expect(ref.parent!.id).to.equal('doc'); + }); + + it('has path property', () => { + const ref = firestore.collection('col/doc/col'); + expect(ref.path).to.equal('col/doc/col'); + }); + + it('has doc() method', () => { + let ref = firestore.collection('col').doc('doc'); + expect(ref.id).to.equal('doc'); + ref = firestore.collection('col').doc(); + expect(ref.id).to.have.length(20); + }); + + it('has add() method', () => { + return randomCol + .add({foo: 'a'}) + .then(ref => { + return ref.get(); + }) + .then(doc => { + expect(doc.get('foo')).to.equal('a'); + }); + }); + + // showMissing is not supported in Enterprise + it.skipEnterprise('lists missing documents', async () => { + const batch = firestore.batch(); + + batch.set(randomCol.doc('a'), {}); + batch.set(randomCol.doc('b/b/b'), {}); + batch.set(randomCol.doc('c'), {}); + await batch.commit(); + + const documentRefs = await randomCol.listDocuments(); + const documents = await firestore.getAll(...documentRefs); + + const existingDocs = documents.filter(doc => doc.exists); + const missingDocs = documents.filter(doc => !doc.exists); + + expect(existingDocs.map(doc => doc.id)).to.have.members(['a', 'c']); + expect(missingDocs.map(doc => doc.id)).to.have.members(['b']); + }); + + // showMissing is not supported in Enterprise + it.skipEnterprise( + 'lists documents (more than the max page size)', + async () => { + const batch = firestore.batch(); + const expectedResults = []; + for (let i = 0; i < 400; i++) { + const docRef = randomCol.doc(`${i}`.padStart(3, '0')); + batch.set(docRef, {id: i}); + expectedResults.push(docRef.id); + } + await batch.commit(); + + const documentRefs = await randomCol.listDocuments(); + + const actualDocIds = documentRefs + .map(dr => dr.id) + .sort((a, b) => a.localeCompare(b)); + + expect(actualDocIds).to.deep.equal(expectedResults); + }, + ); + + it('supports withConverter()', async () => { + const ref = await firestore + .collection('col') + .withConverter(postConverter) + .add(new Post('post', 'author')); + const postData = await ref.get(); + const post = postData.data(); + expect(post).to.not.be.undefined; + expect(post!.toString()).to.equal('post, by author'); + }); +}); + +describe('DocumentReference class', () => { + let firestore: Firestore; + let randomCol: CollectionReference; + + beforeEach(() => { + randomCol = getTestRoot(); + firestore = randomCol.firestore; + }); + + afterEach(() => verifyInstance(firestore)); + + it('has firestore property', () => { + const ref = firestore.doc('col/doc'); + expect(ref.firestore).to.be.an.instanceOf(Firestore); + }); + + it('has id property', () => { + const ref = firestore.doc('col/doc'); + expect(ref.id).to.equal('doc'); + }); + + it('has parent property', () => { + const ref = firestore.doc('col/doc'); + expect(ref.parent.id).to.equal('col'); + }); + + it('has path property', () => { + const ref = firestore.doc('col/doc'); + expect(ref.path).to.equal('col/doc'); + }); + + it('has collection() method', () => { + const ref = firestore.doc('col/doc').collection('subcol'); + expect(ref.id).to.equal('subcol'); + }); + + it('has create()/get() method', () => { + const ref = randomCol.doc(); + return ref + .create({foo: 'a'}) + .then(() => { + return ref.get(); + }) + .then(doc => { + expect(doc.get('foo')).to.equal('a'); + }); + }); + + it('has set() method', () => { + const allSupportedTypesObject: {[field: string]: unknown} = { + stringValue: 'a', + trueValue: true, + falseValue: false, + integerValue: 10, + largeIntegerValue: 1234567890000, + doubleValue: 0.1, + infinityValue: Infinity, + negativeInfinityValue: -Infinity, + objectValue: {foo: 'bar', '😀': '😜'}, + emptyObject: {}, + dateValue: new Timestamp(479978400, 123000000), + zeroDateValue: new Timestamp(0, 0), + pathValue: firestore.doc('col1/ref1'), + arrayValue: ['foo', 42, 'bar'], + emptyArray: [], + nilValue: null, + geoPointValue: new GeoPoint(50.1430847, -122.947778), + zeroGeoPointValue: new GeoPoint(0, 0), + bytesValue: Buffer.from([0x01, 0x02]), + }; + const ref = randomCol.doc('doc'); + return ref + .set(allSupportedTypesObject) + .then(() => { + return ref.get(); + }) + .then(doc => { + const data = doc.data()!; + expect(data.pathValue.path).to.equal( + (allSupportedTypesObject.pathValue as DocumentReference).path, + ); + delete data.pathValue; + delete allSupportedTypesObject.pathValue; + expect(data).to.deep.equal(allSupportedTypesObject); + }); + }); + + it('supports NaNs', () => { + const nanObject = { + nanValue: NaN, + }; + const ref = randomCol.doc('doc'); + return ref + .set(nanObject) + .then(() => { + return ref.get(); + }) + .then(doc => { + const actualValue = doc.data()!.nanValue; + expect(actualValue).to.be.a('number'); + expect(actualValue).to.be.NaN; + }); + }); + + it('round-trips BigInts', () => { + const bigIntValue = BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1); + + const randomCol = getTestRoot({useBigInt: true}); + const ref = randomCol.doc('doc'); + return ref + .set({bigIntValue}) + .then(() => ref.get()) + .then(doc => ref.set(doc.data()!)) + .then(() => ref.get()) + .then(doc => { + const actualValue = doc.data()!.bigIntValue; + expect(actualValue).to.be.a('bigint'); + expect(actualValue).to.equal(bigIntValue); + }); + }); + + it('supports server timestamps', () => { + const baseObject = { + a: 'bar', + b: {remove: 'bar'}, + d: {keep: 'bar'}, + f: FieldValue.serverTimestamp(), + }; + const updateObject = { + a: FieldValue.serverTimestamp(), + b: {c: FieldValue.serverTimestamp()}, + 'd.e': FieldValue.serverTimestamp(), + }; + + const ref = randomCol.doc('doc'); + let setTimestamp: Timestamp; + + return ref + .set(baseObject) + .then(() => { + return ref.get(); + }) + .then(doc => { + setTimestamp = doc.get('f'); + expect(setTimestamp).to.be.an.instanceOf(Timestamp); + expect(doc.data()).to.deep.equal({ + a: 'bar', + b: {remove: 'bar'}, + d: {keep: 'bar'}, + f: setTimestamp, + }); + return ref.update(updateObject); + }) + .then(() => { + return ref.get(); + }) + .then(doc => { + const updateTimestamp = doc.get('a'); + expect(setTimestamp).to.be.an.instanceOf(Timestamp); + expect(doc.data()).to.deep.equal({ + a: updateTimestamp, + b: {c: updateTimestamp}, + d: {e: updateTimestamp, keep: 'bar'}, + f: setTimestamp, + }); + }); + }); + + it('supports increment()', () => { + const baseData = {sum: 1}; + const updateData = {sum: FieldValue.increment(1)}; + const expectedData = {sum: 2}; + + const ref = randomCol.doc('doc'); + return ref + .set(baseData) + .then(() => ref.update(updateData)) + .then(() => ref.get()) + .then(doc => { + expect(doc.data()).to.deep.equal(expectedData); + }); + }); + + it('supports increment() with set() with merge', () => { + const baseData = {sum: 1}; + const updateData = {sum: FieldValue.increment(1)}; + const expectedData = {sum: 2}; + + const ref = randomCol.doc('doc'); + return ref + .set(baseData) + .then(() => ref.set(updateData, {merge: true})) + .then(() => ref.get()) + .then(doc => { + expect(doc.data()).to.deep.equal(expectedData); + }); + }); + + it('supports arrayUnion()', () => { + const baseObject = { + a: [], + b: ['foo'], + c: {d: ['foo']}, + }; + const updateObject = { + a: FieldValue.arrayUnion('foo', 'bar'), + b: FieldValue.arrayUnion('foo', 'bar'), + 'c.d': FieldValue.arrayUnion('foo', 'bar'), + }; + const expectedObject = { + a: ['foo', 'bar'], + b: ['foo', 'bar'], + c: {d: ['foo', 'bar']}, + }; + + const ref = randomCol.doc('doc'); + + return ref + .set(baseObject) + .then(() => ref.update(updateObject)) + .then(() => ref.get()) + .then(doc => { + expect(doc.data()).to.deep.equal(expectedObject); + }); + }); + + it('supports arrayRemove()', () => { + const baseObject = { + a: [], + b: ['foo', 'foo', 'baz'], + c: {d: ['foo', 'bar', 'baz']}, + }; + const updateObject = { + a: FieldValue.arrayRemove('foo'), + b: FieldValue.arrayRemove('foo'), + 'c.d': FieldValue.arrayRemove('foo', 'bar'), + }; + const expectedObject = { + a: [], + b: ['baz'], + c: {d: ['baz']}, + }; + + const ref = randomCol.doc('doc'); + + return ref + .set(baseObject) + .then(() => ref.update(updateObject)) + .then(() => ref.get()) + .then(doc => { + expect(doc.data()).to.deep.equal(expectedObject); + }); + }); + + it('supports set() with merge', () => { + const ref = randomCol.doc('doc'); + return ref + .set({'a.1': 'foo', nested: {'b.1': 'bar'}}) + .then(() => + ref.set({'a.2': 'foo', nested: {'b.2': 'bar'}}, {merge: true}), + ) + .then(() => ref.get()) + .then(doc => { + const data = doc.data(); + expect(data).to.deep.equal({ + 'a.1': 'foo', + 'a.2': 'foo', + nested: { + 'b.1': 'bar', + 'b.2': 'bar', + }, + }); + }); + }); + + it('supports server timestamps for merge', () => { + const ref = randomCol.doc('doc'); + return ref + .set({a: 'b'}) + .then(() => ref.set({c: FieldValue.serverTimestamp()}, {merge: true})) + .then(() => ref.get()) + .then(doc => { + const updateTimestamp = doc.get('c'); + expect(updateTimestamp).to.be.an.instanceOf(Timestamp); + expect(doc.data()).to.deep.equal({ + a: 'b', + c: updateTimestamp, + }); + }); + }); + + it('has update() method', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'a'}) + .then(res => { + return ref.update({foo: 'b'}, {lastUpdateTime: res.writeTime}); + }) + .then(() => { + return ref.get(); + }) + .then(doc => { + expect(doc.get('foo')).to.equal('b'); + }); + }); + + // TODO (b/429419330) re-enable test when this bug is fixed + it.skip('enforces that updated document exists', async () => { + const promise = randomCol.doc().update({foo: 'b'}); + + // Validate the error message when testing against the firestore backend. + if (process.env.FIRESTORE_EMULATOR_HOST === undefined) { + await expect(promise).to.eventually.be.rejectedWith( + /No document to update/, + ); + } else { + // The emulator generates a different error message, do not validate the error message. + await expect(promise).to.eventually.be.rejected; + } + }); + + it('has delete() method', () => { + let deleted = false; + + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'a'}) + .then(() => { + return ref.delete(); + }) + .then(() => { + deleted = true; + return ref.get(); + }) + .then(result => { + expect(deleted).to.be.true; + expect(result.exists).to.be.false; + }); + }); + + it('can delete() a non-existing document', () => { + const ref = firestore.collection('col').doc(); + return ref.delete(); + }); + + // TODO (b/429419330) re-enable test when this bug is fixed + it.skip('will fail to delete document with exists: true if doc does not exist', async () => { + const ref = randomCol.doc(); + const promise = ref + .delete({exists: true}) + .then(() => Promise.reject('Delete should have failed')); + + // Validate the error message when testing against the firestore backend. + if (process.env.FIRESTORE_EMULATOR_HOST === undefined) { + await expect(promise).to.eventually.be.rejectedWith( + /No document to update/, + ); + } else { + // The emulator generates a different error message, do not validate the error message. + await expect(promise).to.eventually.be.rejected; + } + }); + + it('supports non-alphanumeric field names', () => { + const ref = randomCol.doc('doc'); + return ref + .set({'!.\\`': {'!.\\`': 'value'}}) + .then(() => { + return ref.get(); + }) + .then(doc => { + expect(doc.data()).to.deep.equal({'!.\\`': {'!.\\`': 'value'}}); + return ref.update(new FieldPath('!.\\`', '!.\\`'), 'new-value'); + }) + .then(() => { + return ref.get(); + }) + .then(doc => { + expect(doc.data()).to.deep.equal({'!.\\`': {'!.\\`': 'new-value'}}); + }); + }); + + // TODO this test times out in the RPC because there is no index in the backend + // to support the query. The latency scales with the total number of collection + // groups in the database, regardless of which collection / parent is being listed. + it.skipEnterprise('has listCollections() method', () => { + const collections: string[] = []; + const promises: Array> = []; + + for (let i = 0; i < 400; i++) { + const collectionId = i.toString().padStart(3, '0'); + promises.push(randomCol.doc(`doc/${collectionId}/doc`).create({})); + collections.push(collectionId); + } + + return Promise.all(promises) + .then(() => { + return randomCol.doc('doc').listCollections(); + }) + .then(response => { + expect(response).to.have.length(collections.length); + for (let i = 0; i < response.length; ++i) { + expect(response[i].id).to.equal(collections[i]); + } + }); + }); + + // tslint:disable-next-line:only-arrow-function + it('can add and delete fields sequentially', async function () { + this.timeout(30 * 1000); + + const ref = randomCol.doc('doc'); + + const actions = [ + () => ref.create({}), + () => ref.delete(), + () => ref.create({a: {b: 'c'}}), + () => ref.set({}, {merge: true}), + () => ref.set({}), + () => ref.set({a: {b: 'c'}}), + () => ref.set({a: {d: 'e'}}, {merge: true}), + () => ref.set({a: {d: FieldValue.delete()}}, {merge: true}), + () => ref.set({a: {b: FieldValue.delete()}}, {merge: true}), + () => ref.set({a: {e: 'foo'}}, {merge: true}), + () => ref.set({f: 'foo'}, {merge: true}), + () => ref.set({f: {g: 'foo'}}, {merge: true}), + () => ref.update({'f.h': 'foo'}), + () => ref.update({'f.g': FieldValue.delete()}), + () => ref.update({'f.h': FieldValue.delete()}), + () => ref.update({f: FieldValue.delete()}), + () => ref.update({'i.j': {}}), + () => ref.update({'i.j': {k: 'foo'}}), + () => ref.update({'i.j': {l: {}}}), + () => ref.update({i: FieldValue.delete()}), + () => ref.update({a: FieldValue.delete()}), + ]; + + const expectedState = [ + {}, + null, + {a: {b: 'c'}}, + {a: {b: 'c'}}, + {}, + {a: {b: 'c'}}, + {a: {b: 'c', d: 'e'}}, + {a: {b: 'c'}}, + {a: {}}, + {a: {e: 'foo'}}, + {a: {e: 'foo'}, f: 'foo'}, + {a: {e: 'foo'}, f: {g: 'foo'}}, + {a: {e: 'foo'}, f: {g: 'foo', h: 'foo'}}, + {a: {e: 'foo'}, f: {h: 'foo'}}, + {a: {e: 'foo'}, f: {}}, + {a: {e: 'foo'}}, + {a: {e: 'foo'}, i: {j: {}}}, + {a: {e: 'foo'}, i: {j: {k: 'foo'}}}, + {a: {e: 'foo'}, i: {j: {l: {}}}}, + {a: {e: 'foo'}}, + {}, + ]; + + let promise = Promise.resolve(); + + for (let i = 0; i < actions.length; ++i) { + promise = promise + .then(() => actions[i]()) + .then(() => { + return ref.get(); + }) + .then(snap => { + if (!snap.exists) { + expect(expectedState[i]).to.be.null; + } else { + expect(snap.data()).to.deep.equal(expectedState[i]); + } + }); + } + + await promise; + }); + + // tslint:disable-next-line:only-arrow-function + it('can add and delete fields with server timestamps', function () { + this.timeout(10 * 1000); + + const ref = randomCol.doc('doc'); + + const actions = [ + () => + ref.create({ + time: FieldValue.serverTimestamp(), + a: {b: FieldValue.serverTimestamp()}, + }), + () => + ref.set({ + time: FieldValue.serverTimestamp(), + a: {c: FieldValue.serverTimestamp()}, + }), + () => + ref.set( + { + time: FieldValue.serverTimestamp(), + a: {d: FieldValue.serverTimestamp()}, + }, + {merge: true}, + ), + () => + ref.set( + { + time: FieldValue.serverTimestamp(), + e: FieldValue.serverTimestamp(), + }, + {merge: true}, + ), + () => + ref.set( + { + time: FieldValue.serverTimestamp(), + e: {f: FieldValue.serverTimestamp()}, + }, + {merge: true}, + ), + () => + ref.update({ + time: FieldValue.serverTimestamp(), + 'g.h': FieldValue.serverTimestamp(), + }), + () => + ref.update({ + time: FieldValue.serverTimestamp(), + 'g.j': {k: FieldValue.serverTimestamp()}, + }), + ]; + + const expectedState = [ + (times: number[]) => { + return {time: times[0], a: {b: times[0]}}; + }, + (times: number[]) => { + return {time: times[1], a: {c: times[1]}}; + }, + (times: number[]) => { + return {time: times[2], a: {c: times[1], d: times[2]}}; + }, + (times: number[]) => { + return {time: times[3], a: {c: times[1], d: times[2]}, e: times[3]}; + }, + (times: number[]) => { + return { + time: times[4], + a: {c: times[1], d: times[2]}, + e: {f: times[4]}, + }; + }, + (times: number[]) => { + return { + time: times[5], + a: {c: times[1], d: times[2]}, + e: {f: times[4]}, + g: {h: times[5]}, + }; + }, + (times: number[]) => { + return { + time: times[6], + a: {c: times[1], d: times[2]}, + e: {f: times[4]}, + g: {h: times[5], j: {k: times[6]}}, + }; + }, + ]; + + let promise = Promise.resolve(); + const times: number[] = []; + + for (let i = 0; i < actions.length; ++i) { + promise = promise + .then(() => actions[i]()) + .then(() => { + return ref.get(); + }) + .then(snap => { + times.push(snap.get('time')); + expect(snap.data()).to.deep.equal(expectedState[i](times)); + }); + } + + return promise; + }); + + it('can write and read vector embeddings', async () => { + const ref = randomCol.doc(); + await ref.create({ + vector0: FieldValue.vector([0.0]), + vector1: FieldValue.vector([1, 2, 3.99]), + }); + await ref.set({ + vector0: FieldValue.vector([0.0]), + vector1: FieldValue.vector([1, 2, 3.99]), + vector2: FieldValue.vector([0, 0, 0]), + }); + await ref.update({ + vector3: FieldValue.vector([-1, -200, -999]), + }); + + const snap1 = await ref.get(); + expect(snap1.get('vector0').isEqual(FieldValue.vector([0.0]))).to.be.true; + expect(snap1.get('vector1').isEqual(FieldValue.vector([1, 2, 3.99]))).to.be + .true; + expect(snap1.get('vector2').isEqual(FieldValue.vector([0, 0, 0]))).to.be + .true; + expect(snap1.get('vector3').isEqual(FieldValue.vector([-1, -200, -999]))).to + .be.true; + }); + + describe('watch', () => { + const currentDeferred = new DeferredPromise(); + + function resetPromise() { + currentDeferred.promise = new Promise((resolve, reject) => { + currentDeferred.resolve = resolve; + currentDeferred.reject = reject; + }); + } + + function waitForSnapshot(): Promise { + return currentDeferred.promise!.then(snapshot => { + resetPromise(); + return snapshot as DocumentSnapshot; + }); + } + + beforeEach(() => resetPromise()); + + it('handles changing a doc', () => { + const ref = randomCol.doc('doc'); + let readTime: Timestamp; + let createTime: Timestamp; + let updateTime: Timestamp; + + const unsubscribe = ref.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject(err); + }, + ); + + return waitForSnapshot() + .then(snapshot => { + expect(snapshot.exists).to.be.false; + + // Add the document. + return ref.set({foo: 'a'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(snapshot => { + expect(snapshot.exists).to.be.true; + expect(snapshot.get('foo')).to.equal('a'); + readTime = snapshot.readTime; + createTime = snapshot.createTime!; + updateTime = snapshot.updateTime!; + + // Update documents. + return ref.set({foo: 'b'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(snapshot => { + expect(snapshot.exists).to.be.true; + expect(snapshot.get('foo')).to.equal('b'); + expect(snapshot.createTime!.isEqual(createTime)).to.be.true; + expect(snapshot.readTime.toMillis()).to.be.greaterThan( + readTime.toMillis(), + ); + expect(snapshot.updateTime!.toMillis()).to.be.greaterThan( + updateTime.toMillis(), + ); + unsubscribe(); + }); + }); + + it('handles deleting a doc', () => { + const ref = randomCol.doc('doc'); + + const unsubscribe = ref.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject(err); + }, + ); + + return waitForSnapshot() + .then(snapshot => { + expect(snapshot.exists).to.be.false; + + // Add the document. + return ref.set({foo: 'a'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(snapshot => { + expect(snapshot.exists).to.be.true; + + // Delete the document. + return ref.delete(); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(snapshot => { + expect(snapshot.exists).to.be.false; + unsubscribe(); + }); + }); + + it('handles multiple docs', done => { + const doc1 = randomCol.doc(); + const doc2 = randomCol.doc(); + + // Documents transition from non-existent to existent to non-existent. + const exists1 = [false, true, false]; + const exists2 = [false, true, false]; + + const promises: Array> = []; + + // Code blocks to run after each step. + const run = [ + () => { + promises.push(doc1.set({foo: 'foo'})); + promises.push(doc2.set({foo: 'foo'})); + }, + () => { + promises.push(doc1.delete()); + promises.push(doc2.delete()); + }, + () => { + unsubscribe1(); + unsubscribe2(); + void Promise.all(promises).then(() => done()); + }, + ]; + + const maybeRun = () => { + if (exists1.length === exists2.length) { + run.shift()!(); + } + }; + const unsubscribe1 = doc1.onSnapshot(snapshot => { + expect(snapshot.exists).to.equal(exists1.shift()); + maybeRun(); + }); + + const unsubscribe2 = doc2.onSnapshot(snapshot => { + expect(snapshot.exists).to.equal(exists2.shift()); + maybeRun(); + }); + }); + + it('handles multiple streams on same doc', done => { + const doc = randomCol.doc(); + + // Document transitions from non-existent to existent to non-existent. + const exists1 = [false, true, false]; + const exists2 = [false, true, false]; + + const promises: Array> = []; + + // Code blocks to run after each step. + const run = [ + () => { + promises.push(doc.set({foo: 'foo'})); + }, + () => { + promises.push(doc.delete()); + }, + () => { + unsubscribe1(); + unsubscribe2(); + void Promise.all(promises).then(() => done()); + }, + ]; + + const maybeRun = () => { + if (exists1.length === exists2.length) { + run.shift()!(); + } + }; + + const unsubscribe1 = doc.onSnapshot(snapshot => { + expect(snapshot.exists).to.equal(exists1.shift()); + maybeRun(); + }); + + const unsubscribe2 = doc.onSnapshot(snapshot => { + expect(snapshot.exists).to.equal(exists2.shift()); + maybeRun(); + }); + }); + + it('handles more than 100 concurrent listeners', async () => { + const ref = randomCol.doc('doc'); + + const emptyResults: Array> = []; + const documentResults: Array> = []; + const unsubscribeCallbacks: Array<() => void> = []; + + // A single GAPIC client can only handle 100 concurrent streams. We set + // up 100+ long-lived listeners to verify that Firestore pools requests + // across multiple clients. + for (let i = 0; i < 150; ++i) { + emptyResults[i] = new Deferred(); + documentResults[i] = new Deferred(); + + unsubscribeCallbacks[i] = randomCol + .where('i', '>', i) + .onSnapshot(snapshot => { + if (snapshot.size === 0) { + emptyResults[i].resolve(); + } else if (snapshot.size === 1) { + documentResults[i].resolve(); + } + }); + } + + await Promise.all(emptyResults.map(d => d.promise)); + await ref.set({i: 1337}); + await Promise.all(documentResults.map(d => d.promise)); + unsubscribeCallbacks.forEach(c => c()); + }); + + it('handles query snapshots with converters', async () => { + const setupDeferred = new Deferred(); + const resultsDeferred = new Deferred>(); + const ref = randomCol.doc('doc').withConverter(postConverter); + const unsubscribe = randomCol + .where('title', '==', 'post') + .withConverter(postConverter) + .onSnapshot(snapshot => { + if (snapshot.size === 0) { + setupDeferred.resolve(); + } + if (snapshot.size === 1) { + resultsDeferred.resolve(snapshot); + } + }); + + await setupDeferred.promise; + await ref.set(new Post('post', 'author')); + const snapshot = await resultsDeferred.promise; + expect(snapshot.docs[0].data().toString()).to.equal('post, by author'); + unsubscribe(); + }); + }); + + it('supports withConverter()', async () => { + const ref = firestore + .collection('col') + .doc('doc') + .withConverter(postConverter); + await ref.set(new Post('post', 'author')); + const postData = await ref.get(); + const post = postData.data(); + expect(post).to.not.be.undefined; + expect(post!.toString()).to.equal('post, by author'); + }); + + it('supports primitive types with valid converter', async () => { + type Primitive = number; + const primitiveConverter = { + toFirestore(value: Primitive): DocumentData { + return {value}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): Primitive { + const data = snapshot.data(); + return data.value; + }, + }; + + type ArrayValue = number[]; + const arrayConverter = { + toFirestore(value: ArrayValue): DocumentData { + return {values: value}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): ArrayValue { + const data = snapshot.data(); + return data.values; + }, + }; + + const coll = firestore.collection('tests'); + const ref = coll.doc('number').withConverter(primitiveConverter); + await ref.set(3); + const result = await ref.get(); + expect(result.data()).to.equal(3); + + const ref2 = coll.doc('array').withConverter(arrayConverter); + await ref2.set([1, 2, 3]); + const result2 = await ref2.get(); + expect(result2.data()).to.deep.equal([1, 2, 3]); + }); + + it('can listen to documents with vectors', async () => { + const ref = randomCol.doc(); + const initialDeferred = new Deferred(); + const createDeferred = new Deferred(); + const setDeferred = new Deferred(); + const updateDeferred = new Deferred(); + const deleteDeferred = new Deferred(); + + const expected = [ + initialDeferred, + createDeferred, + setDeferred, + updateDeferred, + deleteDeferred, + ]; + let idx = 0; + let document: DocumentSnapshot | null = null; + + const unlisten = randomCol + .where('purpose', '==', 'vector tests') + .onSnapshot(snap => { + expected[idx].resolve(); + idx += 1; + if (snap.docs.length > 0) { + document = snap.docs[0]; + } else { + document = null; + } + }); + + await initialDeferred.promise; + expect(document).to.be.null; + + await ref.create({ + purpose: 'vector tests', + vector0: FieldValue.vector([0.0]), + vector1: FieldValue.vector([1, 2, 3.99]), + }); + + await createDeferred.promise; + expect(document).to.be.not.null; + expect(document!.get('vector0').isEqual(FieldValue.vector([0.0]))).to.be + .true; + expect(document!.get('vector1').isEqual(FieldValue.vector([1, 2, 3.99]))).to + .be.true; + + await ref.set({ + purpose: 'vector tests', + vector0: FieldValue.vector([0.0]), + vector1: FieldValue.vector([1, 2, 3.99]), + vector2: FieldValue.vector([0, 0, 0]), + }); + await setDeferred.promise; + expect(document).to.be.not.null; + expect(document!.get('vector0').isEqual(FieldValue.vector([0.0]))).to.be + .true; + expect(document!.get('vector1').isEqual(FieldValue.vector([1, 2, 3.99]))).to + .be.true; + expect(document!.get('vector2').isEqual(FieldValue.vector([0, 0, 0]))).to.be + .true; + + await ref.update({ + vector3: FieldValue.vector([-1, -200, -999]), + }); + await updateDeferred.promise; + expect(document).to.be.not.null; + expect(document!.get('vector0').isEqual(FieldValue.vector([0.0]))).to.be + .true; + expect(document!.get('vector1').isEqual(FieldValue.vector([1, 2, 3.99]))).to + .be.true; + expect(document!.get('vector2').isEqual(FieldValue.vector([0, 0, 0]))).to.be + .true; + expect( + document!.get('vector3').isEqual(FieldValue.vector([-1, -200, -999])), + ).to.be.true; + + await ref.delete(); + await deleteDeferred.promise; + expect(document).to.be.null; + + unlisten(); + }); +}); + +describe('runs query on a large collection', () => { + let firestore: Firestore; + let randomCol: CollectionReference; + + beforeEach(async () => { + firestore = new Firestore({}); + randomCol = getTestRoot(firestore); + + const promises: Array>> = []; + for (let i = 0; i < 1000; i++) { + promises.push(randomCol.add({foo: 'a'})); + } + await Promise.all(promises); + }); + + afterEach(() => verifyInstance(firestore)); + + it('can get()', () => { + return randomCol.get().then(res => { + expect(res.size).to.equal(1000); + }); + }); + + it('can stream()', async () => { + let received = 0; + const stream = randomCol.stream(); + + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(1000); + }); +}); + +describe.skipEnterprise('Query class - Standard DB', () => { + interface PaginatedResults { + pages: number; + docs: QueryDocumentSnapshot[]; + } + + let firestore: Firestore; + let randomCol: CollectionReference; + + const paginateResults = ( + query: Query, + startAfter?: unknown, + ): Promise => { + return (startAfter ? query.startAfter(startAfter) : query) + .get() + .then(snapshot => { + if (snapshot.empty) { + return {pages: 0, docs: []}; + } else { + const docs = snapshot.docs; + return paginateResults(query, docs[docs.length - 1]).then( + nextPage => { + return { + pages: nextPage.pages + 1, + docs: docs.concat(nextPage.docs), + }; + }, + ); + } + }); + }; + + async function addDocs( + ...docs: DocumentData[] + ): Promise { + let id = 0; // Guarantees consistent ordering for the first documents + const refs: DocumentReference[] = []; + for (const doc of docs) { + const ref = randomCol.doc('doc' + id++); + await ref.set(doc); + refs.push(ref); + } + return refs; + } + + async function testCollectionWithDocs(docs: { + [id: string]: DocumentData; + }): Promise> { + for (const id in docs) { + const ref = randomCol.doc(id); + await ref.set(docs[id]); + } + return randomCol; + } + + function expectDocs(result: QuerySnapshot, ...docs: string[]): void; + function expectDocs(result: QuerySnapshot, ...data: DocumentData[]): void; + + function expectDocs( + result: QuerySnapshot, + ...data: DocumentData[] | string[] + ): void { + expect(result.size).to.equal(data.length); + + if (data.length > 0) { + if (typeof data[0] === 'string') { + const actualIds = result.docs.map(docSnapshot => docSnapshot.id); + expect(actualIds).to.deep.equal(data); + } else { + result.forEach(doc => { + expect(doc.data()).to.deep.equal(data.shift()); + }); + } + } + } + + beforeEach(() => { + randomCol = getTestRoot(); + firestore = randomCol.firestore; + }); + + afterEach(() => verifyInstance(firestore)); + + it('has firestore property', () => { + const ref = randomCol.limit(0); + expect(ref.firestore).to.be.an.instanceOf(Firestore); + }); + + it('has select() method', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar', bar: 'foo'}) + .then(() => { + return randomCol.select('foo').get(); + }) + .then(res => { + expect(res.docs[0].data()).to.deep.equal({foo: 'bar'}); + }); + }); + + it('select() supports empty fields', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar', bar: 'foo'}) + .then(() => { + return randomCol.select().get(); + }) + .then(res => { + expect(res.docs[0].ref.id).to.deep.equal('doc'); + expect(res.docs[0].data()).to.deep.equal({}); + }); + }); + + it('has where() method', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar'}) + .then(() => { + return randomCol.where('foo', '==', 'bar').get(); + }) + .then(res => { + expect(res.docs[0].data()).to.deep.equal({foo: 'bar'}); + }); + }); + + it('supports NaN and Null', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: NaN, bar: null}) + .then(() => { + return randomCol.where('foo', '==', NaN).where('bar', '==', null).get(); + }) + .then(res => { + expect( + typeof res.docs[0].get('foo') === 'number' && + isNaN(res.docs[0].get('foo')), + ); + expect(res.docs[0].get('bar')).to.equal(null); + }); + }); + + it('supports array-contains', () => { + return Promise.all([ + randomCol.add({foo: ['bar']}), + randomCol.add({foo: []}), + ]) + .then(() => randomCol.where('foo', 'array-contains', 'bar').get()) + .then(res => { + expect(res.size).to.equal(1); + expect(res.docs[0].get('foo')).to.deep.equal(['bar']); + }); + }); + + describe('vector search', () => { + it('supports findNearest by EUCLIDEAN distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest({ + vectorField: 'embedding', + queryVector: [10, 10], + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(3); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([10, 0]))) + .to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1]))).to + .be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0]))) + .to.be.true; + }); + + it('supports findNearest by COSINE distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + '4': {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + '5': {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + '6': {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest({ + vectorField: 'embedding', + queryVector: [10, 10], + limit: 3, + distanceMeasure: 'COSINE', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(3); + + if (res.docs[0].get('embedding').isEqual(FieldValue.vector([1, 1]))) { + expect( + res.docs[1].get('embedding').isEqual(FieldValue.vector([100, 100])), + ).to.be.true; + } else { + expect( + res.docs[0].get('embedding').isEqual(FieldValue.vector([100, 100])), + ).to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1]))) + .to.be.true; + } + + expect( + res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0])) || + res.docs[2].get('embedding').isEqual(FieldValue.vector([10, 0])), + ).to.be.true; + }); + + it('supports findNearest by DOT_PRODUCT distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest({ + vectorField: 'embedding', + queryVector: [10, 10], + limit: 3, + distanceMeasure: 'DOT_PRODUCT', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(3); + expect( + res.docs[0].get('embedding').isEqual(FieldValue.vector([100, 100])), + ).to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([20, 0]))) + .to.be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([10, 0]))) + .to.be.true; + }); + + it('findNearest works with converters', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + class FooDistance { + constructor( + readonly foo: string, + readonly embedding: Array, + ) {} + } + + const fooConverter = { + toFirestore(d: FooDistance): DocumentData { + return {title: d.foo, embedding: FieldValue.vector(d.embedding)}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): FooDistance { + const data = snapshot.data(); + return new FooDistance(data.foo, data.embedding.toArray()); + }, + }; + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar', embedding: FieldValue.vector([5, 5])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .withConverter(fooConverter) + .where('foo', '==', 'bar') + .findNearest({ + vectorField: 'embedding', + queryVector: [10, 10], + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(1); + expect(res.docs[0].data().foo).to.equal('bar'); + expect(res.docs[0].data().embedding).to.deep.equal([5, 5]); + }); + + it('supports findNearest skipping fields of wrong types', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + + // These documents are skipped because it is not really a vector value + {foo: 'bar', embedding: [10, 10]}, + {foo: 'bar', embedding: 'not actually a vector'}, + {foo: 'bar', embedding: null}, + + // Actual vector values + {foo: 'bar', embedding: FieldValue.vector([9, 9])}, + {foo: 'bar', embedding: FieldValue.vector([50, 50])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .where('foo', '==', 'bar') + .findNearest({ + vectorField: 'embedding', + queryVector: [10, 10], + limit: 100, // Intentionally large to get all matches. + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(3); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([9, 9]))).to + .be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([50, 50]))) + .to.be.true; + expect( + res.docs[2].get('embedding').isEqual(FieldValue.vector([100, 100])), + ).to.be.true; + }); + + it('findNearest ignores mismatching dimensions', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + + // Vectors with dimension mismatch + {foo: 'bar', embedding: FieldValue.vector([10])}, + + // Vectors with dimension match + {foo: 'bar', embedding: FieldValue.vector([9, 9])}, + {foo: 'bar', embedding: FieldValue.vector([50, 50])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .where('foo', '==', 'bar') + .findNearest({ + vectorField: 'embedding', + queryVector: [10, 10], + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(2); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([9, 9]))).to + .be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([50, 50]))) + .to.be.true; + }); + + it('supports findNearest on non-existent field', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'bar', otherField: [10, 10]}, + {foo: 'bar', otherField: 'not actually a vector'}, + {foo: 'bar', otherField: null}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .where('foo', '==', 'bar') + .findNearest({ + vectorField: 'embedding', + queryVector: [10, 10], + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(0); + }); + + it('supports findNearest on vector nested in a map', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {nested: {foo: 'bar'}}, + {nested: {foo: 'xxx', embedding: FieldValue.vector([10, 10])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([1, 1])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([10, 0])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([20, 0])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([100, 100])}}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'nested.embedding', + queryVector: [10, 10], + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(3); + expect( + res.docs[0] + .get('nested.embedding') + .isEqual(FieldValue.vector([10, 10])), + ).to.be.true; + expect( + res.docs[1].get('nested.embedding').isEqual(FieldValue.vector([10, 0])), + ).to.be.true; + expect( + res.docs[2].get('nested.embedding').isEqual(FieldValue.vector([1, 1])), + ).to.be.true; + }); + + it('supports findNearest with select to exclude vector data in response', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 1}, + {foo: 2, embedding: FieldValue.vector([10, 10])}, + {foo: 3, embedding: FieldValue.vector([1, 1])}, + {foo: 4, embedding: FieldValue.vector([10, 0])}, + {foo: 5, embedding: FieldValue.vector([20, 0])}, + {foo: 6, embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', 'in', [1, 2, 3, 4, 5, 6]) + .select('foo') + .findNearest({ + vectorField: 'embedding', + queryVector: [10, 10], + limit: 10, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(5); + expect(res.docs[0].get('foo')).to.equal(2); + expect(res.docs[1].get('foo')).to.equal(4); + expect(res.docs[2].get('foo')).to.equal(3); + expect(res.docs[3].get('foo')).to.equal(5); + expect(res.docs[4].get('foo')).to.equal(6); + + res.docs.forEach(ds => expect(ds.get('embedding')).to.be.undefined); + }); + + it('supports findNearest limits', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const embeddingVector = []; + const queryVector = []; + for (let i = 0; i < 2048; i++) { + embeddingVector.push(i + 1); + queryVector.push(i - 1); + } + + const collectionReference = await indexTestHelper.createTestDocs([ + {embedding: FieldValue.vector(embeddingVector)}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: queryVector, + limit: 1000, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(1); + expect( + (res.docs[0].get('embedding') as VectorValue).toArray(), + ).to.deep.equal(embeddingVector); + }); + + describe('preview API (deprecated)', () => { + it('supports findNearest with EUCLIDEAN', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'bar', embedding: FieldValue.vector([10, 10])}, + {foo: 'bar', embedding: FieldValue.vector([1, 1.1])}, + {foo: 'x', embedding: FieldValue.vector([1, 1])}, + {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + {foo: 'bar', embedding: FieldValue.vector([-100, -100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest('embedding', [1, 1], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(3); + expect( + res.docs[0].get('embedding').isEqual(FieldValue.vector([1, 1.1])), + ).to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([10, 0]))) + .to.be.true; + expect( + res.docs[2].get('embedding').isEqual(FieldValue.vector([10, 10])), + ).to.be.true; + }); + + it('supports findNearest with COSINE', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'bar', embedding: FieldValue.vector([10, 10])}, + {foo: 'bar', embedding: FieldValue.vector([1, 1.1])}, + {foo: 'x', embedding: FieldValue.vector([1, 1])}, + {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + {foo: 'bar', embedding: FieldValue.vector([-100, -100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest('embedding', [1, 1], { + limit: 3, + distanceMeasure: 'COSINE', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(3); + expect( + res.docs[0].get('embedding').isEqual(FieldValue.vector([10, 10])), + ).to.be.true; + expect( + res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1.1])), + ).to.be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([10, 0]))) + .to.be.true; + }); + }); + + describe('requesting computed distance', () => { + it('supports requesting computed COSINE distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([1, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([0, 1])}, + '4': {foo: 'bar', embedding: FieldValue.vector([0, -0.1])}, + '5': {foo: 'bar', embedding: FieldValue.vector([-1, 0])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'COSINE', + distanceResultField: 'distance', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(4); + + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([1, 0]))) + .to.be.true; + expect(res.docs[0].get('distance')).to.equal(0); + + expect(res.docs[1].get('distance')).to.equal(1); + expect(res.docs[2].get('distance')).to.equal(1); + + expect(res.docs[3].get('embedding').isEqual(FieldValue.vector([-1, 0]))) + .to.be.true; + expect(res.docs[3].get('distance')).to.equal(2); + }); + + it('supports requesting computed EUCLIDEAN distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([2, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 100])}, + '4': {foo: 'bar', embedding: FieldValue.vector([1, -0.1])}, + '5': {foo: 'bar', embedding: FieldValue.vector([4, 4])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'EUCLIDEAN', + distanceResultField: 'distance', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(4); + + expect( + res.docs[0].get('embedding').isEqual(FieldValue.vector([1, -0.1])), + ).to.be.true; + expect(res.docs[0].get('distance')).to.equal(0.1); + + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([2, 0]))) + .to.be.true; + expect(res.docs[1].get('distance')).to.equal(1); + + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([4, 4]))) + .to.be.true; + expect(res.docs[2].get('distance')).to.equal(5); + + expect( + res.docs[3].get('embedding').isEqual(FieldValue.vector([1, 100])), + ).to.be.true; + expect(res.docs[3].get('distance')).to.equal(100); + }); + + it('supports requesting computed DOT_PRODUCT distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([2, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 100])}, + '4': {foo: 'bar', embedding: FieldValue.vector([-20, 0])}, + '5': {foo: 'bar', embedding: FieldValue.vector([0.1, 4])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'DOT_PRODUCT', + distanceResultField: 'distance', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(4); + + expect(res.docs[0].get('distance')).to.equal(2); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([2, 0]))) + .to.be.true; + + expect(res.docs[1].get('distance')).to.equal(1); + expect( + res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 100])), + ).to.be.true; + + expect(res.docs[2].get('distance')).to.equal(0.1); + expect( + res.docs[2].get('embedding').isEqual(FieldValue.vector([0.1, 4])), + ).to.be.true; + + expect(res.docs[3].get('distance')).to.equal(-20); + expect( + res.docs[3].get('embedding').isEqual(FieldValue.vector([-20, 0])), + ).to.be.true; + }); + + it('overwrites distance result field on conflict', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': { + foo: 'bar', + embedding: FieldValue.vector([0, 1]), + distance: '100 miles', + }, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'COSINE', + distanceResultField: 'distance', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(1); + + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([0, 1]))) + .to.be.true; + expect(res.docs[0].get('distance')).to.equal(1); + }); + + it('supports requesting computed distance in select queries', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([1, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([0, 1])}, + '4': {foo: 'bar', embedding: FieldValue.vector([0, -0.1])}, + '5': {foo: 'bar', embedding: FieldValue.vector([-1, 0])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + // value of `distanceResultField` must also be in select statement + .select('embedding', 'distance') + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'COSINE', + distanceResultField: 'distance', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(4); + + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([1, 0]))) + .to.be.true; + expect(res.docs[0].get('distance')).to.equal(0); + + expect(res.docs[1].get('distance')).to.equal(1); + expect(res.docs[2].get('distance')).to.equal(1); + + expect(res.docs[3].get('embedding').isEqual(FieldValue.vector([-1, 0]))) + .to.be.true; + expect(res.docs[3].get('distance')).to.equal(2); + }); + }); + + describe('querying with distance threshold', () => { + it('supports querying with distance threshold using COSINE distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([1, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + '4': {foo: 'bar', embedding: FieldValue.vector([0, -0.1])}, + '5': {foo: 'bar', embedding: FieldValue.vector([-1, 0])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'COSINE', + distanceThreshold: 1, + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(3); + + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([1, 0]))) + .to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1]))) + .to.be.true; + expect( + res.docs[2].get('embedding').isEqual(FieldValue.vector([0, -0.1])), + ).to.be.true; + }); + + it('supports querying with distance threshold using EUCLIDEAN distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([2, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 100])}, + '4': {foo: 'bar', embedding: FieldValue.vector([1, -0.1])}, + '5': {foo: 'bar', embedding: FieldValue.vector([4, 4])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'EUCLIDEAN', + distanceThreshold: 5, + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(3); + + expect( + res.docs[0].get('embedding').isEqual(FieldValue.vector([1, -0.1])), + ).to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([2, 0]))) + .to.be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([4, 4]))) + .to.be.true; + }); + + it('supports querying with distance threshold using DOT_PRODUCT distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([2, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 100])}, + '4': {foo: 'bar', embedding: FieldValue.vector([-20, 0])}, + '5': {foo: 'bar', embedding: FieldValue.vector([0.1, 4])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'DOT_PRODUCT', + distanceThreshold: 1, + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(2); + + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([2, 0]))) + .to.be.true; + + expect( + res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 100])), + ).to.be.true; + }); + + it('works with distance result field', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([2, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 100])}, + '4': {foo: 'bar', embedding: FieldValue.vector([-20, 0])}, + '5': {foo: 'bar', embedding: FieldValue.vector([0.1, 4])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'DOT_PRODUCT', + distanceThreshold: 0.11, + distanceResultField: 'foo', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(2); + + expect(res.docs[0].get('foo')).to.equal(2); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([2, 0]))) + .to.be.true; + + expect(res.docs[1].get('foo')).to.equal(1); + expect( + res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 100])), + ).to.be.true; + }); + + it('will not exceed limit even if there are more results more similar than distanceThreshold', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([2, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 100])}, + '4': {foo: 'bar', embedding: FieldValue.vector([-20, 0])}, + '5': {foo: 'bar', embedding: FieldValue.vector([0.1, 4])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 2, + distanceMeasure: 'DOT_PRODUCT', + distanceThreshold: 0.0, + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(2); + + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([2, 0]))) + .to.be.true; + + expect( + res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 100])), + ).to.be.true; + }); + }); + }); + + it('supports !=', async () => { + await addDocs( + {zip: NaN}, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + {zip: null}, + ); + + let res = await randomCol + .where('zip', '!=', 98101) + .orderBy('zip') + .orderBy(FieldPath.documentId()) + .get(); + expectDocs( + res, + {zip: NaN}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + + res = await randomCol.where('zip', '!=', NaN).get(); + expectDocs( + res, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + + res = await randomCol.where('zip', '!=', null).get(); + expectDocs( + res, + {zip: NaN}, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + }); + + it('supports != with document ID', async () => { + const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); + const res = await randomCol + .where(FieldPath.documentId(), '!=', refs[0].id) + .orderBy(FieldPath.documentId()) + .get(); + expectDocs(res, {count: 2}, {count: 3}); + }); + + it('supports not-in', async () => { + await addDocs( + {zip: 98101}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + let res = await randomCol.where('zip', 'not-in', [98101, 98103]).get(); + expectDocs( + res, + {zip: 91102}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + + res = await randomCol.where('zip', 'not-in', [NaN]).get(); + + expectDocs( + res, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + + res = await randomCol.where('zip', 'not-in', [null]).get(); + + expect(res.size).to.equal(0); + }); + + it('supports not-in with document ID array', async () => { + const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); + const res = await randomCol + .where(FieldPath.documentId(), 'not-in', [refs[0].id, refs[1]]) + .get(); + expectDocs(res, {count: 3}); + }); + + it('supports "in"', async () => { + await addDocs( + {zip: 98101}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + const res = await randomCol + .where('zip', 'in', [98101, 98103]) + .orderBy('zip') + .get(); + expectDocs(res, {zip: 98101}, {zip: 98103}); + }); + + it('supports "in" with document ID array', async () => { + const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); + const res = await randomCol + .where(FieldPath.documentId(), 'in', [refs[0].id, refs[1]]) + .get(); + expectDocs(res, {count: 1}, {count: 2}); + }); + + it('supports array-contains-any', async () => { + await addDocs( + {array: [42]}, + {array: ['a', 42, 'c']}, + {array: [41.999, '42', {a: [42]}]}, + {array: [42], array2: ['sigh']}, + {array: [43]}, + {array: [{a: 42}]}, + {array: 42}, + ); + + const res = await randomCol + .where('array', 'array-contains-any', [42, 43]) + .get(); + + expectDocs( + res, + {array: [42]}, + {array: ['a', 42, 'c']}, + { + array: [42], + array2: ['sigh'], + }, + {array: [43]}, + ); + }); + + it('can query by FieldPath.documentId()', () => { + const ref = randomCol.doc('foo'); + + return ref + .set({}) + .then(() => { + return randomCol.where(FieldPath.documentId(), '>=', 'bar').get(); + }) + .then(res => { + expect(res.docs.length).to.equal(1); + }); + }); + + it('has orderBy() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + + let res = await randomCol.orderBy('foo').get(); + expectDocs(res, {foo: 'a'}, {foo: 'b'}); + + res = await randomCol.orderBy('foo', 'desc').get(); + expectDocs(res, {foo: 'b'}, {foo: 'a'}); + }); + + it('can order by FieldPath.documentId()', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + return Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'b'})]) + .then(() => { + return randomCol.orderBy(FieldPath.documentId()).get(); + }) + .then(res => { + expect(res.docs[0].data()).to.deep.equal({foo: 'a'}); + expect(res.docs[1].data()).to.deep.equal({foo: 'b'}); + }); + }); + + it('can run get() on empty collection', async () => { + return randomCol.get().then(res => { + return expect(res.empty); + }); + }); + + it('can run stream() on empty collection', async () => { + let received = 0; + const stream = randomCol.stream(); + + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(0); + }); + + it('has limit() method on get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').limit(1).get(); + expectDocs(res, {foo: 'a'}); + }); + + it('has limit() method on stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + + const stream = randomCol.orderBy('foo').limit(1).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(1); + }); + + it('can run limit(num), where num is larger than the collection size on get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').limit(3).get(); + expectDocs(res, {foo: 'a'}, {foo: 'b'}); + }); + + it('can run limit(num), where num is larger than the collection size on stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + + const stream = randomCol.orderBy('foo').limit(3).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(2); + }); + + it('has limitToLast() method', async () => { + await addDocs({doc: 1}, {doc: 2}, {doc: 3}); + const res = await randomCol.orderBy('doc').limitToLast(2).get(); + expectDocs(res, {doc: 2}, {doc: 3}); + }); + + it('limitToLast() supports Query cursors', async () => { + await addDocs({doc: 1}, {doc: 2}, {doc: 3}, {doc: 4}, {doc: 5}); + const res = await randomCol + .orderBy('doc') + .startAt(2) + .endAt(4) + .limitToLast(5) + .get(); + expectDocs(res, {doc: 2}, {doc: 3}, {doc: 4}); + }); + + it('can use offset() method with get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').offset(1).get(); + expectDocs(res, {foo: 'b'}); + }); + + it('can use offset() method with stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + + const stream = randomCol.orderBy('foo').offset(1).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(1); + }); + + it('can run offset(num), where num is larger than the collection size on get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').offset(3).get(); + expect(res.empty); + }); + + it('can run offset(num), where num is larger than the collection size on stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + const stream = randomCol.orderBy('foo').offset(3).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + expect(received).to.equal(0); + }); + + it('supports Unicode in document names', async () => { + const collRef = randomCol.doc('доброеутро').collection('coll'); + await collRef.add({}); + const snapshot = await collRef.get(); + expect(snapshot.size).to.equal(1); + }); + + it('supports pagination', () => { + const batch = firestore.batch(); + + for (let i = 0; i < 10; ++i) { + batch.set(randomCol.doc('doc' + i), {val: i}); + } + + const query = randomCol.orderBy('val').limit(3); + + return batch + .commit() + .then(() => paginateResults(query)) + .then(results => { + expect(results.pages).to.equal(4); + expect(results.docs).to.have.length(10); + }); + }); + + it('supports pagination with where() clauses', () => { + const batch = firestore.batch(); + + for (let i = 0; i < 10; ++i) { + batch.set(randomCol.doc('doc' + i), {val: i}); + } + + const query = randomCol.where('val', '>=', 1).limit(3); + + return batch + .commit() + .then(() => paginateResults(query)) + .then(results => { + expect(results.pages).to.equal(3); + expect(results.docs).to.have.length(9); + }); + }); + + it('supports pagination with array-contains filter', () => { + const batch = firestore.batch(); + + for (let i = 0; i < 10; ++i) { + batch.set(randomCol.doc('doc' + i), {array: ['foo']}); + } + + const query = randomCol.where('array', 'array-contains', 'foo').limit(3); + + return batch + .commit() + .then(() => paginateResults(query)) + .then(results => { + expect(results.pages).to.equal(4); + expect(results.docs).to.have.length(10); + }); + }); + + it('has startAt() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').startAt('b').get(); + expectDocs(res, {foo: 'b'}); + }); + + it('startAt() adds implicit order by for DocumentSnapshot', async () => { + const references = await addDocs({foo: 'a'}, {foo: 'b'}); + const docSnap = await references[1].get(); + const res = await randomCol.startAt(docSnap).get(); + expectDocs(res, {foo: 'b'}); + }); + + it('has startAfter() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').startAfter('a').get(); + expectDocs(res, {foo: 'b'}); + }); + + it('has endAt() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').endAt('b').get(); + expectDocs(res, {foo: 'a'}, {foo: 'b'}); + }); + + it('has endBefore() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').endBefore('b').get(); + expectDocs(res, {foo: 'a'}); + }); + + it('has stream() method', done => { + let received = 0; + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + void Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'b'})]).then(() => { + return randomCol + .stream() + .on('data', d => { + expect(d).to.be.an.instanceOf(DocumentSnapshot); + ++received; + }) + .on('end', () => { + expect(received).to.equal(2); + done(); + }); + }); + }); + + it('stream() supports readable[Symbol.asyncIterator]()', async () => { + let received = 0; + await randomCol.doc().set({foo: 'bar'}); + await randomCol.doc().set({foo: 'bar'}); + + const stream = randomCol.stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(2); + }); + + it('can query collection groups', async () => { + // Use `randomCol` to get a random collection group name to use but ensure + // it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; + + const docPaths = [ + `abc/123/${collectionGroup}/cg-doc1`, + `abc/123/${collectionGroup}/cg-doc2`, + `${collectionGroup}/cg-doc3`, + `${collectionGroup}/cg-doc4`, + `def/456/${collectionGroup}/cg-doc5`, + `${collectionGroup}/virtual-doc/nested-coll/not-cg-doc`, + `x${collectionGroup}/not-cg-doc`, + `${collectionGroup}x/not-cg-doc`, + `abc/123/${collectionGroup}x/not-cg-doc`, + `abc/123/x${collectionGroup}/not-cg-doc`, + `abc/${collectionGroup}`, + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); + + const querySnapshot = await firestore + .collectionGroup(collectionGroup) + .orderBy(FieldPath.documentId()) + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc1', + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + 'cg-doc5', + ]); + }); + + it('can query collection groups with startAt / endAt by arbitrary documentId', async () => { + // Use `randomCol` to get a random collection group name to use but + // ensure it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; + + const docPaths = [ + `a/a/${collectionGroup}/cg-doc1`, + `a/b/a/b/${collectionGroup}/cg-doc2`, + `a/b/${collectionGroup}/cg-doc3`, + `a/b/c/d/${collectionGroup}/cg-doc4`, + `a/c/${collectionGroup}/cg-doc5`, + `${collectionGroup}/cg-doc6`, + 'a/b/nope/nope', + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); + + let querySnapshot = await firestore + .collectionGroup(collectionGroup) + .orderBy(FieldPath.documentId()) + .startAt('a/b') + .endAt('a/b0') + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + ]); + + querySnapshot = await firestore + .collectionGroup(collectionGroup) + .orderBy(FieldPath.documentId()) + .startAfter('a/b') + .endBefore(`a/b/${collectionGroup}/cg-doc3`) + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); + }); + + it('can query collection groups with where filters on arbitrary documentId', async () => { + // Use `randomCol` to get a random collection group name to use but + // ensure it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; + + const docPaths = [ + `a/a/${collectionGroup}/cg-doc1`, + `a/b/a/b/${collectionGroup}/cg-doc2`, + `a/b/${collectionGroup}/cg-doc3`, + `a/b/c/d/${collectionGroup}/cg-doc4`, + `a/c/${collectionGroup}/cg-doc5`, + `${collectionGroup}/cg-doc6`, + 'a/b/nope/nope', + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); + + let querySnapshot = await firestore + .collectionGroup(collectionGroup) + .where(FieldPath.documentId(), '>=', 'a/b') + .where(FieldPath.documentId(), '<=', 'a/b0') + .orderBy(FieldPath.documentId()) + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + ]); + + querySnapshot = await firestore + .collectionGroup(collectionGroup) + .where(FieldPath.documentId(), '>', 'a/b') + .where(FieldPath.documentId(), '<', `a/b/${collectionGroup}/cg-doc3`) + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); + }); + + it('can query large collections', async () => { + // @grpc/grpc-js v0.4.1 failed to deliver the full set of query results for + // larger collections (https://github.com/grpc/grpc-node/issues/895); + const batch = firestore.batch(); + for (let i = 0; i < 100; ++i) { + batch.create(randomCol.doc(), {}); + } + await batch.commit(); + + const snapshot = await randomCol.get(); + expect(snapshot.size).to.equal(100); + }); + + it('supports OR queries', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {a: 2, b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1, b: 1}, + }); + + // Two equalities: a==1 || b==1. + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), + ) + .orderBy(FieldPath.documentId()) + .get(), + 'doc1', + 'doc2', + 'doc4', + 'doc5', + ); + + // (a==1 && b==0) || (a==3 && b==2) + expectDocs( + await collection + .where( + Filter.or( + Filter.and(Filter.where('a', '==', 1), Filter.where('b', '==', 0)), + Filter.and(Filter.where('a', '==', 3), Filter.where('b', '==', 2)), + ), + ) + .orderBy(FieldPath.documentId()) + .get(), + 'doc1', + 'doc3', + ); + + // a==1 && (b==0 || b==3). + expectDocs( + await collection + .where( + Filter.and( + Filter.where('a', '==', 1), + Filter.or(Filter.where('b', '==', 0), Filter.where('b', '==', 3)), + ), + ) + .orderBy(FieldPath.documentId()) + .get(), + 'doc1', + 'doc4', + ); + + // (a==2 || b==2) && (a==3 || b==3) + expectDocs( + await collection + .where( + Filter.and( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 2)), + Filter.or(Filter.where('a', '==', 3), Filter.where('b', '==', 3)), + ), + ) + .orderBy(FieldPath.documentId()) + .get(), + 'doc3', + ); + + // Test with limits without orderBy (the __name__ ordering is the tie breaker). + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), + ) + .limit(1) + .orderBy(FieldPath.documentId()) + .get(), + 'doc2', + ); + }); + + // TODO Enterprise - wait for implicit sort order decision + // Skip this test if running against standard production because it results in a 'missing index' error. + it.skipClassic('supports OR queries with composite indexes', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {a: 2, b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1, b: 1}, + }); + + // with one inequality: a>2 || b==1. + expectDocs( + await collection + .where(Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1))) + .orderBy(FieldPath.documentId()) + .get(), + 'doc2', + 'doc3', + 'doc5', + ); + + // Test with limits (implicit order by ASC): (a==1) || (b > 0) LIMIT 2 + expectDocs( + await collection + .where(Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0))) + .limit(2) + .orderBy(FieldPath.documentId()) + .get(), + 'doc1', + 'doc2', + ); + + // Test with limits (explicit order by): (a==1) || (b > 0) LIMIT_TO_LAST 2 + // Note: The public query API does not allow implicit ordering when limitToLast is used. + expectDocs( + await collection + .where(Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0))) + .limitToLast(2) + .orderBy('b') + .orderBy(FieldPath.documentId()) + .get(), + 'doc3', + 'doc4', + ); + + // Test with limits (explicit order by ASC): (a==2) || (b == 1) ORDER BY a LIMIT 1 + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), + ) + .limit(1) + .orderBy('a') + .orderBy(FieldPath.documentId()) + .get(), + 'doc5', + ); + + // Test with limits (explicit order by DESC): (a==2) || (b == 1) ORDER BY a LIMIT 1 + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), + ) + .limit(1) + .orderBy('a', 'desc') + .orderBy(FieldPath.documentId()) + .get(), + 'doc2', + ); + }); + + it('supports OR queries on documents with missing fields', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==1 || b==1 + // There's no explicit nor implicit orderBy. Documents with missing 'a' or missing 'b' should be + // allowed if the document matches at least one disjunction term. + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), + ) + .orderBy(FieldPath.documentId()) + .get(), + 'doc1', + 'doc2', + 'doc4', + 'doc5', + ); + }); + + // Skip this test if running against production standard DB because it results in a 'missing index' error. + // The Firestore Emulator and Enterprise-editions, however, do serve these queries. + it.skipClassic( + 'supports OR queries on documents with missing fields', + async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==1 || b==1 order by a. + // doc2 should not be included because it's missing the field 'a', and we have "orderBy a". + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), + ) + .orderBy('a') + .orderBy(FieldPath.documentId()) + .get(), + 'doc1', + 'doc4', + 'doc5', + ); + + // Query: a==1 || b==1 order by b. + // doc5 should not be included because it's missing the field 'b', and we have "orderBy b". + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), + ) + .orderBy('b') + .orderBy(FieldPath.documentId()) + .get(), + 'doc1', + 'doc2', + 'doc4', + ); + + // Query: a>2 || b==1. + // This query has an implicit 'order by a'. + // Standard Ed: doc2 should not be included because it's missing the field 'a'. + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), + ) + .get(), + 'doc3', + ); + + // Query: a>1 || b==1 order by a order by b. + // doc6 should not be included because it's missing the field 'b'. + // doc2 should not be included because it's missing the field 'a'. + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '>', 1), Filter.where('b', '==', 1)), + ) + .orderBy('a') + .orderBy('b') + .get(), + 'doc3', + ); + }, + ); + + it('supports OR queries with in', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==2 || b in [2, 3] + expectDocs( + await collection + .where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'in', [2, 3]), + ), + ) + .orderBy(FieldPath.documentId()) + .get(), + 'doc3', + 'doc4', + 'doc6', + ); + }); + + // Skip this test if running against production because it results in a 'missing index' error. + it.skipClassic('supports OR queries with not-in', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + // a==2 || (b != 2 && b != 3) + // Has implicit "orderBy b" + expectDocs( + await collection + .where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'not-in', [2, 3]), + ), + ) + .get(), + 'doc1', + 'doc2', + ); + }); + + it('supports OR queries with array membership', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: [0]}, + doc2: {b: [1]}, + doc3: {a: 3, b: [2, 7]}, + doc4: {a: 1, b: [3, 7]}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==2 || b array-contains 7 + expectDocs( + await collection + .where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'array-contains', 7), + ), + ) + .orderBy(FieldPath.documentId()) + .get(), + 'doc3', + 'doc4', + 'doc6', + ); + + // a==2 || b array-contains-any [0, 3] + // Has implicit "orderBy b" + expectDocs( + await collection + .where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'array-contains-any', [0, 3]), + ), + ) + .orderBy(FieldPath.documentId()) + .get(), + 'doc1', + 'doc4', + 'doc6', + ); + }); + + describe('watch', () => { + interface ExpectedChange { + type: string; + doc: DocumentSnapshot; + } + + const currentDeferred = new DeferredPromise(); + + const snapshot = (id: string, data: DocumentData) => { + const ref = randomCol.doc(id); + const fields = ref.firestore._serializer!.encodeFields(data); + return randomCol.firestore.snapshot_( + { + name: + 'projects/ignored/databases/(default)/documents/' + + ref._path.relativeName, + fields, + createTime: {seconds: 0, nanos: 0}, + updateTime: {seconds: 0, nanos: 0}, + }, + {seconds: 0, nanos: 0}, + ); + }; + + const docChange = ( + type: string, + id: string, + data: DocumentData, + ): ExpectedChange => { + return { + type, + doc: snapshot(id, data), + }; + }; + + const added = (id: string, data: DocumentData) => + docChange('added', id, data); + const modified = (id: string, data: DocumentData) => + docChange('modified', id, data); + const removed = (id: string, data: DocumentData) => + docChange('removed', id, data); + + function resetPromise() { + currentDeferred.promise = new Promise((resolve, reject) => { + currentDeferred.resolve = resolve; + currentDeferred.reject = reject; + }); + } + + function waitForSnapshot(): Promise { + return currentDeferred.promise!.then(snapshot => { + resetPromise(); + return snapshot; + }); + } + + function snapshotsEqual( + actual: QuerySnapshot, + expected: {docs: DocumentSnapshot[]; docChanges: ExpectedChange[]}, + ) { + let i; + expect(actual.size).to.equal(expected.docs.length); + for (i = 0; i < expected.docs.length && i < actual.size; i++) { + expect(actual.docs[i].ref.id).to.equal(expected.docs[i].ref.id); + expect(actual.docs[i].data()).to.deep.equal(expected.docs[i].data()); + } + const actualDocChanges = actual.docChanges(); + expect(actualDocChanges.length).to.equal(expected.docChanges.length); + for (i = 0; i < expected.docChanges.length; i++) { + expect(actualDocChanges[i].type).to.equal(expected.docChanges[i].type); + expect(actualDocChanges[i].doc.ref.id).to.equal( + expected.docChanges[i].doc.ref.id, + ); + expect(actualDocChanges[i].doc.data()).to.deep.equal( + expected.docChanges[i].doc.data(), + ); + expect(actualDocChanges[i].doc.readTime).to.exist; + expect(actualDocChanges[i].doc.createTime).to.exist; + expect(actualDocChanges[i].doc.updateTime).to.exist; + } + expect(actual.readTime).to.exist; + } + + beforeEach(() => resetPromise()); + + it('handles changing a doc', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + const unsubscribe = randomCol.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject!(err); + }, + ); + + return waitForSnapshot() + .then(results => { + snapshotsEqual(results, {docs: [], docChanges: []}); + // Add a result. + return ref1.set({foo: 'a'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {foo: 'a'})], + docChanges: [added('doc1', {foo: 'a'})], + }); + // Add another result. + return ref2.set({foo: 'b'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {foo: 'a'}), snapshot('doc2', {foo: 'b'})], + docChanges: [added('doc2', {foo: 'b'})], + }); + // Change a result. + return ref2.set({bar: 'c'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {foo: 'a'}), snapshot('doc2', {bar: 'c'})], + docChanges: [modified('doc2', {bar: 'c'})], + }); + unsubscribe(); + }); + }); + + it("handles changing a doc so it doesn't match", () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + const query = randomCol.where('included', '==', 'yes'); + const unsubscribe = query.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject(err); + }, + ); + + return waitForSnapshot() + .then(results => { + snapshotsEqual(results, {docs: [], docChanges: []}); + // Add a result. + return ref1.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [added('doc1', {included: 'yes'})], + }); + // Add another result. + return ref2.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [ + snapshot('doc1', {included: 'yes'}), + snapshot('doc2', {included: 'yes'}), + ], + docChanges: [added('doc2', {included: 'yes'})], + }); + // Change a result. + return ref2.set({included: 'no'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [removed('doc2', {included: 'yes'})], + }); + unsubscribe(); + }); + }); + + it('handles deleting a doc', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + const unsubscribe = randomCol.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject(err); + }, + ); + + return waitForSnapshot() + .then(results => { + snapshotsEqual(results, {docs: [], docChanges: []}); + // Add a result. + return ref1.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [added('doc1', {included: 'yes'})], + }); + // Add another result. + return ref2.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [ + snapshot('doc1', {included: 'yes'}), + snapshot('doc2', {included: 'yes'}), + ], + docChanges: [added('doc2', {included: 'yes'})], + }); + // Delete a result. + return ref2.delete(); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [removed('doc2', {included: 'yes'})], + }); + unsubscribe(); + }); + }); + + it('orders limitToLast() correctly', async () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + const ref3 = randomCol.doc('doc3'); + + await ref1.set({doc: 1}); + await ref2.set({doc: 2}); + await ref3.set({doc: 3}); + + const unsubscribe = randomCol + .orderBy('doc') + .limitToLast(2) + .onSnapshot(snapshot => currentDeferred.resolve(snapshot)); + + const results = await waitForSnapshot(); + snapshotsEqual(results, { + docs: [snapshot('doc2', {doc: 2}), snapshot('doc3', {doc: 3})], + docChanges: [added('doc2', {doc: 2}), added('doc3', {doc: 3})], + }); + + unsubscribe(); + }); + + it.skipEnterprise( + 'snapshot listener sorts query by DocumentId same way as server', + async () => { + const batch = firestore.batch(); + batch.set(randomCol.doc('A'), {a: 1}); + batch.set(randomCol.doc('a'), {a: 1}); + batch.set(randomCol.doc('Aa'), {a: 1}); + batch.set(randomCol.doc('7'), {a: 1}); + batch.set(randomCol.doc('12'), {a: 1}); + batch.set(randomCol.doc('__id7__'), {a: 1}); + batch.set(randomCol.doc('__id12__'), {a: 1}); + batch.set(randomCol.doc('__id-2__'), {a: 1}); + batch.set(randomCol.doc('__id1_'), {a: 1}); + batch.set(randomCol.doc('_id1__'), {a: 1}); + batch.set(randomCol.doc('__id'), {a: 1}); + // largest long number + batch.set(randomCol.doc('__id9223372036854775807__'), {a: 1}); + batch.set(randomCol.doc('__id9223372036854775806__'), {a: 1}); + // smallest long number + batch.set(randomCol.doc('__id-9223372036854775808__'), {a: 1}); + batch.set(randomCol.doc('__id-9223372036854775807__'), {a: 1}); + await batch.commit(); + + const query = randomCol.orderBy(FieldPath.documentId()); + const expectedDocs = isEnterprise() + ? [ + '12', + '7', + 'A', + 'Aa', + '__id', + '__id-2__', + '__id-9223372036854775807__', + '__id-9223372036854775808__', + '__id12__', + '__id1_', + '__id7__', + '__id9223372036854775806__', + '__id9223372036854775807__', + '_id1__', + 'a', + ] + : [ + '__id-9223372036854775808__', + '__id-9223372036854775807__', + '__id-2__', + '__id7__', + '__id12__', + '__id9223372036854775806__', + '__id9223372036854775807__', + '12', + '7', + 'A', + 'Aa', + '__id', + '__id1_', + '_id1__', + 'a', + ]; + + const getSnapshot = await query.get(); + expect(getSnapshot.docs.map(d => d.id)).to.deep.equal(expectedDocs); + + const unsubscribe = query.onSnapshot(snapshot => + currentDeferred.resolve(snapshot), + ); + + const watchSnapshot = await waitForSnapshot(); + // Compare the snapshot (including sort order) of a snapshot + snapshotsEqual(watchSnapshot, { + docs: getSnapshot.docs, + docChanges: getSnapshot.docChanges(), + }); + unsubscribe(); + }, + ); + + it.skipEnterprise( + 'snapshot listener sorts filtered query by DocumentId same way as server', + async () => { + const batch = firestore.batch(); + batch.set(randomCol.doc('A'), {a: 1}); + batch.set(randomCol.doc('a'), {a: 1}); + batch.set(randomCol.doc('Aa'), {a: 1}); + batch.set(randomCol.doc('7'), {a: 1}); + batch.set(randomCol.doc('12'), {a: 1}); + batch.set(randomCol.doc('__id7__'), {a: 1}); + batch.set(randomCol.doc('__id12__'), {a: 1}); + batch.set(randomCol.doc('__id-2__'), {a: 1}); + batch.set(randomCol.doc('__id1_'), {a: 1}); + batch.set(randomCol.doc('_id1__'), {a: 1}); + batch.set(randomCol.doc('__id'), {a: 1}); + // largest long number + batch.set(randomCol.doc('__id9223372036854775807__'), {a: 1}); + batch.set(randomCol.doc('__id9223372036854775806__'), {a: 1}); + // smallest long number + batch.set(randomCol.doc('__id-9223372036854775808__'), {a: 1}); + batch.set(randomCol.doc('__id-9223372036854775807__'), {a: 1}); + await batch.commit(); + + const query = randomCol + .where(FieldPath.documentId(), '>', '__id7__') + .where(FieldPath.documentId(), '<=', 'A') + .orderBy(FieldPath.documentId()); + const expectedDocs = [ + '__id12__', + '__id9223372036854775806__', + '__id9223372036854775807__', + '12', + '7', + 'A', + ]; + + const getSnapshot = await query.get(); + expect(getSnapshot.docs.map(d => d.id)).to.deep.equal(expectedDocs); + + const unsubscribe = query.onSnapshot(snapshot => + currentDeferred.resolve(snapshot), + ); + + const watchSnapshot = await waitForSnapshot(); + // Compare the snapshot (including sort order) of a snapshot + snapshotsEqual(watchSnapshot, { + docs: getSnapshot.docs, + docChanges: getSnapshot.docChanges(), + }); + unsubscribe(); + }, + ); + + it('SDK orders vector field same way as backend', async () => { + // We validate that the SDK orders the vector field the same way as the backend + // by comparing the sort order of vector fields from a Query.get() and + // Query.onSnapshot(). Query.onSnapshot() will return sort order of the SDK, + // and Query.get() will return sort order of the backend. + + // Test data in the order that we expect the backend to sort it. + const docsInOrder = [ + {embedding: [1, 2, 3, 4, 5, 6]}, + {embedding: [100]}, + {embedding: FieldValue.vector([Number.NEGATIVE_INFINITY])}, + {embedding: FieldValue.vector([-100])}, + {embedding: FieldValue.vector([100])}, + {embedding: FieldValue.vector([Number.POSITIVE_INFINITY])}, + {embedding: FieldValue.vector([1, 2])}, + {embedding: FieldValue.vector([2, 2])}, + {embedding: FieldValue.vector([1, 2, 3])}, + {embedding: FieldValue.vector([1, 2, 3, 4])}, + {embedding: FieldValue.vector([1, 2, 3, 4, 5])}, + {embedding: FieldValue.vector([1, 2, 100, 4, 4])}, + {embedding: FieldValue.vector([100, 2, 3, 4, 5])}, + {embedding: {HELLO: 'WORLD'}}, + {embedding: {hello: 'world'}}, + ]; + + const expectedSnapshots = []; + const expectedChanges = []; + + for (let i = 0; i < docsInOrder.length; i++) { + const dr = await randomCol.add(docsInOrder[i]); + expectedSnapshots.push(snapshot(dr.id, docsInOrder[i])); + expectedChanges.push(added(dr.id, docsInOrder[i])); + } + + const orderedQuery = randomCol.orderBy('embedding'); + + const unsubscribe = orderedQuery.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject!(err); + }, + ); + + const watchSnapshot = await waitForSnapshot(); + unsubscribe(); + + const getSnapshot = await orderedQuery.get(); + + // Compare the snapshot (including sort order) of a snapshot + // from Query.onSnapshot() to an actual snapshot from Query.get() + snapshotsEqual(watchSnapshot, { + docs: getSnapshot.docs, + docChanges: getSnapshot.docChanges(), + }); + + // Compare the snapshot (including sort order) of a snapshot + // from Query.onSnapshot() to the expected sort order from + // the backend. + snapshotsEqual(watchSnapshot, { + docs: expectedSnapshots, + docChanges: expectedChanges, + }); + }); + + describe('sort unicode strings', () => { + const expectedDocs = [ + 'b', + 'a', + 'h', + 'i', + 'c', + 'f', + 'e', + 'd', + 'g', + 'k', + 'j', + ]; + + it('snapshot listener sorts unicode strings same as server', async () => { + const collection = await testCollectionWithDocs({ + a: {value: 'Łukasiewicz'}, + b: {value: 'Sierpiński'}, + c: {value: '岩澤'}, + d: {value: '🄟'}, + e: {value: 'P'}, + f: {value: '︒'}, + g: {value: '🐵'}, + h: {value: '你好'}, + i: {value: '你顥'}, + j: {value: '😁'}, + k: {value: '😀'}, + }); + + const query = collection.orderBy('value'); + + const getSnapshot = await query.get(); + expect(getSnapshot.docs.map(d => d.id)).to.deep.equal(expectedDocs); + + const unsubscribe = query.onSnapshot(snapshot => + currentDeferred.resolve(snapshot), + ); + const watchSnapshot = await waitForSnapshot(); + snapshotsEqual(watchSnapshot, { + docs: getSnapshot.docs, + docChanges: getSnapshot.docChanges(), + }); + unsubscribe(); + }); + + it('snapshot listener sorts unicode strings in array same as server', async () => { + const collection = await testCollectionWithDocs({ + a: {value: ['Łukasiewicz']}, + b: {value: ['Sierpiński']}, + c: {value: ['岩澤']}, + d: {value: ['🄟']}, + e: {value: ['P']}, + f: {value: ['︒']}, + g: {value: ['🐵']}, + h: {value: ['你好']}, + i: {value: ['你顥']}, + j: {value: ['😁']}, + k: {value: ['😀']}, + }); + + const query = collection.orderBy('value'); + + const getSnapshot = await query.get(); + expect(getSnapshot.docs.map(d => d.id)).to.deep.equal(expectedDocs); + + const unsubscribe = query.onSnapshot(snapshot => + currentDeferred.resolve(snapshot), + ); + const watchSnapshot = await waitForSnapshot(); + snapshotsEqual(watchSnapshot, { + docs: getSnapshot.docs, + docChanges: getSnapshot.docChanges(), + }); + unsubscribe(); + }); + + it('snapshot listener sorts unicode strings in map same as server', async () => { + const collection = await testCollectionWithDocs({ + a: {value: {foo: 'Łukasiewicz'}}, + b: {value: {foo: 'Sierpiński'}}, + c: {value: {foo: '岩澤'}}, + d: {value: {foo: '🄟'}}, + e: {value: {foo: 'P'}}, + f: {value: {foo: '︒'}}, + g: {value: {foo: '🐵'}}, + h: {value: {foo: '你好'}}, + i: {value: {foo: '你顥'}}, + j: {value: {foo: '😁'}}, + k: {value: {foo: '😀'}}, + }); + + const query = collection.orderBy('value'); + + const getSnapshot = await query.get(); + expect(getSnapshot.docs.map(d => d.id)).to.deep.equal(expectedDocs); + + const unsubscribe = query.onSnapshot(snapshot => + currentDeferred.resolve(snapshot), + ); + const watchSnapshot = await waitForSnapshot(); + snapshotsEqual(watchSnapshot, { + docs: getSnapshot.docs, + docChanges: getSnapshot.docChanges(), + }); + unsubscribe(); + }); + + it('snapshot listener sorts unicode strings in map key same as server', async () => { + const collection = await testCollectionWithDocs({ + a: {value: {Łukasiewicz: true}}, + b: {value: {Sierpiński: true}}, + c: {value: {岩澤: true}}, + d: {value: {'🄟': true}}, + e: {value: {P: true}}, + f: {value: {'︒': true}}, + g: {value: {'🐵': true}}, + h: {value: {你好: true}}, + i: {value: {你顥: true}}, + j: {value: {'😁': true}}, + k: {value: {'😀': true}}, + }); + + const query = collection.orderBy('value'); + + const getSnapshot = await query.get(); + expect(getSnapshot.docs.map(d => d.id)).to.deep.equal(expectedDocs); + + const unsubscribe = query.onSnapshot(snapshot => + currentDeferred.resolve(snapshot), + ); + const watchSnapshot = await waitForSnapshot(); + snapshotsEqual(watchSnapshot, { + docs: getSnapshot.docs, + docChanges: getSnapshot.docChanges(), + }); + unsubscribe(); + }); + + it('snapshot listener sorts unicode strings in document key same as server', async () => { + const collection = await testCollectionWithDocs({ + Łukasiewicz: {value: true}, + Sierpiński: {value: true}, + 岩澤: {value: true}, + '🄟': {value: true}, + P: {value: true}, + '︒': {value: true}, + '🐵': {value: true}, + 你好: {value: true}, + 你顥: {value: true}, + '😁': {value: true}, + '😀': {value: true}, + }); + + const query = collection.orderBy(FieldPath.documentId()); + const expectedDocs = [ + 'Sierpiński', + 'Łukasiewicz', + '你好', + '你顥', + '岩澤', + '︒', + 'P', + '🄟', + '🐵', + '😀', + '😁', + ]; + + const getSnapshot = await query.get(); + expect(getSnapshot.docs.map(d => d.id)).to.deep.equal(expectedDocs); + + const unsubscribe = query.onSnapshot(snapshot => + currentDeferred.resolve(snapshot), + ); + const watchSnapshot = await waitForSnapshot(); + snapshotsEqual(watchSnapshot, { + docs: getSnapshot.docs, + docChanges: getSnapshot.docChanges(), + }); + unsubscribe(); + }); + }); + }); + + (process.env.FIRESTORE_EMULATOR_HOST === undefined + ? describe.skip + : describe)('multiple inequality', () => { + it('supports multiple inequality queries', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 0}, + doc2: {key: 'b', sort: 3, v: 1}, + doc3: {key: 'c', sort: 1, v: 3}, + doc4: {key: 'd', sort: 2, v: 2}, + }); + + // Multiple inequality fields + let results = await collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .where('v', '>', 2) + .get(); + expectDocs(results, 'doc3'); + + // Duplicate inequality fields + results = await collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .where('sort', '>', 1) + .get(); + expectDocs(results, 'doc4'); + + // With multiple IN + results = await collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .where('v', 'in', [2, 3, 4]) + .where('sort', 'in', [2, 3]) + .get(); + expectDocs(results, 'doc4'); + + // With NOT-IN + results = await collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .where('v', 'not-in', [2, 4, 5]) + .get(); + expectDocs(results, 'doc1', 'doc3'); + + // With orderby + results = await collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .orderBy('v', 'desc') + .get(); + expectDocs(results, 'doc3', 'doc4', 'doc1'); + + // With limit + results = await collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .orderBy('v', 'desc') + .limit(2) + .get(); + expectDocs(results, 'doc3', 'doc4'); + + // With limitToLast + results = await collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .orderBy('v', 'desc') + .limitToLast(2) + .get(); + expectDocs(results, 'doc4', 'doc1'); + }); + + it('can use on special values', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 0}, + doc2: {key: 'b', sort: NaN, v: 1}, + doc3: {key: 'c', sort: null, v: 3}, + doc4: {key: 'd', v: 0}, + doc5: {key: 'e', sort: 1}, + doc6: {key: 'f', sort: 1, v: 1}, + }); + + let results = await collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .get(); + expectDocs(results, 'doc5', 'doc6'); + + results = await collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .where('v', '<=', 1) + .get(); + expectDocs(results, 'doc6'); + }); + + it('can use with array membership', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: [0]}, + doc2: {key: 'b', sort: 1, v: [0, 1, 3]}, + doc3: {key: 'c', sort: 1, v: []}, + doc4: {key: 'd', sort: 2, v: [1]}, + doc5: {key: 'e', sort: 3, v: [2, 4]}, + doc6: {key: 'f', sort: 4, v: [NaN]}, + doc7: {key: 'g', sort: 4, v: [null]}, + }); + + let results = await collection + .where('key', '!=', 'a') + .where('sort', '>=', 1) + .where('v', 'array-contains', 0) + .get(); + expectDocs(results, 'doc2'); + + results = await collection + .where('key', '!=', 'a') + .where('sort', '>=', 1) + .where('v', 'array-contains-any', [0, 1]) + .get(); + expectDocs(results, 'doc2', 'doc4'); + }); + + // Use cursor in following test cases to add implicit order by fields in the sdk and compare the + // result with the query fields normalized in the server. + it('can use with nested field', async () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const testData = (n?: number): any => { + n = n || 1; + return { + name: 'room ' + n, + metadata: { + createdAt: n, + }, + field: 'field ' + n, + 'field.dot': n, + 'field\\slash': n, + }; + }; + + const collection = await testCollectionWithDocs({ + doc1: testData(400), + doc2: testData(200), + doc3: testData(100), + doc4: testData(300), + }); + + // ordered by: name asc, metadata.createdAt asc, __name__ asc + let query = collection + .where('metadata.createdAt', '<=', 500) + .where('metadata.createdAt', '>', 100) + .where('name', '!=', 'room 200') + .orderBy('name'); + let docSnap = await collection.doc('doc4').get(); + let queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc4', 'doc1'); + expectDocs(await queryWithCursor.get(), 'doc4', 'doc1'); + + // ordered by: name desc, field desc, field.dot desc, field\\slash desc, __name__ desc + query = collection + .where('field', '>=', 'field 100') + .where(new FieldPath('field.dot'), '!=', 300) + .where('field\\slash', '<', 400) + .orderBy('name', 'desc'); + docSnap = await collection.doc('doc2').get(); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc2', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc3'); + }); + + it('can use with nested composite filters', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 5}, + doc2: {key: 'aa', sort: 4, v: 4}, + doc3: {key: 'c', sort: 3, v: 3}, + doc4: {key: 'b', sort: 2, v: 2}, + doc5: {key: 'b', sort: 2, v: 1}, + doc6: {key: 'b', sort: 0, v: 0}, + }); + + // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc + let query = collection.where( + Filter.or( + Filter.and( + Filter.where('key', '==', 'b'), + Filter.where('sort', '<=', 2), + ), + Filter.and(Filter.where('key', '!=', 'b'), Filter.where('v', '>', 4)), + ), + ); + let docSnap = await collection.doc('doc1').get(); + let queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc1', 'doc6', 'doc5', 'doc4'); + expectDocs(await queryWithCursor.get(), 'doc1', 'doc6', 'doc5', 'doc4'); + + // Ordered by: 'sort' desc, 'key' asc, 'v' asc, __name__ asc + query = collection + .where( + Filter.or( + Filter.and( + Filter.where('key', '==', 'b'), + Filter.where('sort', '<=', 2), + ), + Filter.and( + Filter.where('key', '!=', 'b'), + Filter.where('v', '>', 4), + ), + ), + ) + .orderBy('sort', 'desc') + .orderBy('key'); + docSnap = await collection.doc('doc5').get(); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc5', 'doc4', 'doc1', 'doc6'); + expectDocs(await queryWithCursor.get(), 'doc5', 'doc4', 'doc1', 'doc6'); + + // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc + query = collection.where( + Filter.and( + Filter.or( + Filter.and( + Filter.where('key', '==', 'b'), + Filter.where('sort', '<=', 4), + ), + Filter.and( + Filter.where('key', '!=', 'b'), + Filter.where('v', '>=', 4), + ), + ), + Filter.or( + Filter.and( + Filter.where('key', '>', 'b'), + Filter.where('sort', '>=', 1), + ), + Filter.and( + Filter.where('key', '<', 'b'), + Filter.where('v', '>', 0), + ), + ), + ), + ); + docSnap = await collection.doc('doc1').get(); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc1', 'doc2'); + expectDocs(await queryWithCursor.get(), 'doc1', 'doc2'); + }); + + it('inequality fields will be implicitly ordered lexicographically by the server', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 5}, + doc2: {key: 'aa', sort: 4, v: 4}, + doc3: {key: 'b', sort: 3, v: 3}, + doc4: {key: 'b', sort: 2, v: 2}, + doc5: {key: 'b', sort: 2, v: 1}, + doc6: {key: 'b', sort: 0, v: 0}, + }); + + const docSnap = await collection.doc('doc2').get(); + + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + let query = collection + .where('key', '!=', 'a') + .where('sort', '>', 1) + .where('v', 'in', [1, 2, 3, 4]); + let queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc2', 'doc4', 'doc5', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc5', 'doc3'); + + // Changing filters order will not effect implicit order. + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + query = collection + .where('sort', '>', 1) + .where('key', '!=', 'a') + .where('v', 'in', [1, 2, 3, 4]); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc2', 'doc4', 'doc5', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc5', 'doc3'); + }); + + it('can use multiple explicit order by field', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 5, v: 0}, + doc2: {key: 'aa', sort: 4, v: 0}, + doc3: {key: 'b', sort: 3, v: 1}, + doc4: {key: 'b', sort: 2, v: 1}, + doc5: {key: 'bb', sort: 1, v: 1}, + doc6: {key: 'c', sort: 0, v: 2}, + }); + + let docSnap = await collection.doc('doc2').get(); + + // Ordered by: 'v' asc, 'key' asc, 'sort' asc, __name__ asc + let query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v'); + let queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc2', 'doc4', 'doc3', 'doc5'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3', 'doc5'); + + // Ordered by: 'v asc, 'sort' asc, 'key' asc, __name__ asc + query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v') + .orderBy('sort'); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc2', 'doc5', 'doc4', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc5', 'doc4', 'doc3'); + + docSnap = await collection.doc('doc5').get(); + + // Implicit order by matches the direction of last explicit order by. + // Ordered by: 'v' desc, 'key' desc, 'sort' desc, __name__ desc + query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v', 'desc'); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc5', 'doc3', 'doc4', 'doc2'); + expectDocs(await queryWithCursor.get(), 'doc5', 'doc3', 'doc4', 'doc2'); + + // Ordered by: 'v desc, 'sort' asc, 'key' asc, __name__ asc + query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v', 'desc') + .orderBy('sort'); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc5', 'doc4', 'doc3', 'doc2'); + expectDocs(await queryWithCursor.get(), 'doc5', 'doc4', 'doc3', 'doc2'); + }); + + it('can use in aggregate query', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 5, v: 0}, + doc2: {key: 'aa', sort: 4, v: 0}, + doc3: {key: 'b', sort: 3, v: 1}, + doc4: {key: 'b', sort: 2, v: 1}, + doc5: {key: 'bb', sort: 1, v: 1}, + }); + + const results = await collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v') + .count() + .get(); + expect(results.data().count).to.be.equal(4); + //TODO(MIEQ): Add sum and average when they are public. + }); + + it('can use document ID im multiple inequality query', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 5}, + doc2: {key: 'aa', sort: 4}, + doc3: {key: 'b', sort: 3}, + doc4: {key: 'b', sort: 2}, + doc5: {key: 'bb', sort: 1}, + }); + + const docSnap = await collection.doc('doc2').get(); + + // Document Key in inequality field will implicitly ordered to the last. + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + let query = collection + .where('sort', '>=', 1) + .where('key', '!=', 'a') + .where(FieldPath.documentId(), '<', 'doc5'); + let queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc2', 'doc4', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3'); + + // Changing filters order will not effect implicit order. + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + query = collection + .where(FieldPath.documentId(), '<', 'doc5') + .where('sort', '>=', 1) + .where('key', '!=', 'a'); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc2', 'doc4', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3'); + + // Ordered by: 'sort' desc,'key' desc, __name__ desc + query = collection + .where(FieldPath.documentId(), '<', 'doc5') + .where('sort', '>=', 1) + .where('key', '!=', 'a') + .orderBy('sort', 'desc'); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc2', 'doc3', 'doc4'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc3', 'doc4'); + }); + }); +}); + +describe('count queries', () => { + let firestore: Firestore; + let randomCol: CollectionReference; + + beforeEach(() => { + randomCol = getTestRoot(); + firestore = randomCol.firestore; + }); + + afterEach(() => verifyInstance(firestore)); + + describe('Run outside Transaction', () => { + countTests(async (q, n) => { + const res = await q.get(); + expect(res.data().count).to.equal(n); + }); + }); + + describe('Run within Transaction', () => { + countTests(async (q, n) => { + const res = await firestore.runTransaction(f => f.get(q)); + expect(res.data().count).to.equal(n); + }); + }); + + function countTests( + runQueryAndExpectCount: ( + query: FirebaseFirestore.AggregateQuery<{ + count: FirebaseFirestore.AggregateField; + }>, + expectedCount: number, + ) => Promise, + ) { + it('counts 0 document from non-existent collection', async () => { + const count = randomCol.count(); + await runQueryAndExpectCount(count, 0); + }); + + it('counts 0 document from filtered empty collection', async () => { + await randomCol.doc('doc').set({foo: 'bar'}); + const count = randomCol.where('foo', '==', 'notbar').count(); + await runQueryAndExpectCount(count, 0); + }); + + it('counts 1 document', async () => { + await randomCol.doc('doc').set({foo: 'bar'}); + const count = randomCol.count(); + await runQueryAndExpectCount(count, 1); + }); + + it('counts 1 document', async () => { + await randomCol.doc('doc').set({foo: 'bar'}); + const count = randomCol.count(); + await runQueryAndExpectCount(count, 1); + }); + + it('counts 1 document', async () => { + await randomCol.doc('doc').set({foo: 'bar'}); + const count = randomCol.count(); + await runQueryAndExpectCount(count, 1); + }); + + it('counts multiple documents with filter', async () => { + await randomCol.doc('doc1').set({foo: 'bar'}); + await randomCol.doc('doc2').set({foo: 'bar'}); + await randomCol.doc('doc3').set({foo: 'notbar'}); + await randomCol.doc('doc3').set({notfoo: 'bar'}); + const count = randomCol.where('foo', '==', 'bar').count(); + await runQueryAndExpectCount(count, 2); + }); + + it('counts up to limit', async () => { + await randomCol.doc('doc1').set({foo: 'bar'}); + await randomCol.doc('doc2').set({foo: 'bar'}); + await randomCol.doc('doc3').set({foo: 'bar'}); + await randomCol.doc('doc4').set({foo: 'bar'}); + await randomCol.doc('doc5').set({foo: 'bar'}); + await randomCol.doc('doc6').set({foo: 'bar'}); + await randomCol.doc('doc7').set({foo: 'bar'}); + await randomCol.doc('doc8').set({foo: 'bar'}); + const count = randomCol.limit(5).count(); + await runQueryAndExpectCount(count, 5); + }); + + it('counts with orderBy', async () => { + await randomCol.doc('doc1').set({foo1: 'bar1'}); + await randomCol.doc('doc2').set({foo1: 'bar2'}); + await randomCol.doc('doc3').set({foo1: 'bar3'}); + await randomCol.doc('doc4').set({foo1: 'bar4'}); + await randomCol.doc('doc5').set({foo1: 'bar5'}); + await randomCol.doc('doc6').set({foo2: 'bar6'}); + await randomCol.doc('doc7').set({foo2: 'bar7'}); + await randomCol.doc('doc8').set({foo2: 'bar8'}); + + const count1 = randomCol.orderBy('foo2').count(); + await runQueryAndExpectCount(count1, 3); + + const count2 = randomCol.orderBy('foo3').count(); + await runQueryAndExpectCount(count2, 0); + }); + + it('counts with startAt, endAt and offset', async () => { + await randomCol.doc('doc1').set({foo: 'bar'}); + await randomCol.doc('doc2').set({foo: 'bar'}); + await randomCol.doc('doc3').set({foo: 'bar'}); + await randomCol.doc('doc4').set({foo: 'bar'}); + await randomCol.doc('doc5').set({foo: 'bar'}); + await randomCol.doc('doc6').set({foo: 'bar'}); + await randomCol.doc('doc7').set({foo: 'bar'}); + + const docSnap = await randomCol.doc('doc3').get(); + + const count1 = randomCol.startAfter(docSnap).count(); + await runQueryAndExpectCount(count1, 4); + + const count2 = randomCol.startAt(docSnap).count(); + await runQueryAndExpectCount(count2, 5); + + const count3 = randomCol.endAt(docSnap).count(); + await runQueryAndExpectCount(count3, 3); + + const count4 = randomCol.endBefore(docSnap).count(); + await runQueryAndExpectCount(count4, 2); + + const count5 = randomCol.offset(6).count(); + await runQueryAndExpectCount(count5, 1); + }); + } + + // Only verify the error message for missing indexes when running against + // production, since the Firestore Emulator does not require index creation + // and will, therefore, never fail in this situation. + // eslint-disable-next-line no-restricted-properties + // TODO (b/429419330) re-enable test when this bug is fixed + (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it.skip)( + 'count query error message contains console link if missing index', + () => { + const query = randomCol.where('key1', '==', 42).where('key2', '<', 42); + const countQuery = query.count(); + const databaseId = query.firestore._settings.databaseId ?? '(default)'; + // TODO(b/316359394) Remove this check for the default databases once + // cl/582465034 is rolled out to production. + if (databaseId === '(default)') { + return expect(countQuery.get()).to.be.eventually.rejectedWith( + /index.*https:\/\/console\.firebase\.google\.com/, + ); + } else { + return expect(countQuery.get()).to.be.eventually.rejectedWith(/index/); + } + }, + ); +}); + +describe('count queries using aggregate api', () => { + let firestore: Firestore; + let randomCol: CollectionReference; + + beforeEach(() => { + randomCol = getTestRoot(); + firestore = randomCol.firestore; + }); + + afterEach(() => verifyInstance(firestore)); + + describe('Run outside Transaction', () => { + countTests(async (q, n) => { + const res = await q.get(); + expect(res.data().count).to.equal(n); + }); + }); + + describe('Run within Transaction', () => { + countTests(async (q, n) => { + const res = await firestore.runTransaction(f => f.get(q)); + expect(res.data().count).to.equal(n); + }); + }); + + function countTests( + runQueryAndExpectCount: ( + query: FirebaseFirestore.AggregateQuery<{ + count: FirebaseFirestore.AggregateField; + }>, + expectedCount: number, + ) => Promise, + ) { + it('counts 0 document from non-existent collection', async () => { + const count = randomCol.aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count, 0); + }); + + it('counts 0 document from filtered empty collection', async () => { + await randomCol.doc('doc').set({foo: 'bar'}); + const count = randomCol + .where('foo', '==', 'notbar') + .aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count, 0); + }); + + it('counts 1 document', async () => { + await randomCol.doc('doc').set({foo: 'bar'}); + const count = randomCol.aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count, 1); + }); + + it('counts multiple documents with filter', async () => { + await randomCol.doc('doc1').set({foo: 'bar'}); + await randomCol.doc('doc2').set({foo: 'bar'}); + await randomCol.doc('doc3').set({foo: 'notbar'}); + await randomCol.doc('doc3').set({notfoo: 'bar'}); + const count = randomCol + .where('foo', '==', 'bar') + .aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count, 2); + }); + + it('counts up to limit', async () => { + await randomCol.doc('doc1').set({foo: 'bar'}); + await randomCol.doc('doc2').set({foo: 'bar'}); + await randomCol.doc('doc3').set({foo: 'bar'}); + await randomCol.doc('doc4').set({foo: 'bar'}); + await randomCol.doc('doc5').set({foo: 'bar'}); + await randomCol.doc('doc6').set({foo: 'bar'}); + await randomCol.doc('doc7').set({foo: 'bar'}); + await randomCol.doc('doc8').set({foo: 'bar'}); + const count = randomCol + .limit(5) + .aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count, 5); + }); + + it('counts with orderBy', async () => { + await randomCol.doc('doc1').set({foo1: 'bar1'}); + await randomCol.doc('doc2').set({foo1: 'bar2'}); + await randomCol.doc('doc3').set({foo1: 'bar3'}); + await randomCol.doc('doc4').set({foo1: 'bar4'}); + await randomCol.doc('doc5').set({foo1: 'bar5'}); + await randomCol.doc('doc6').set({foo2: 'bar6'}); + await randomCol.doc('doc7').set({foo2: 'bar7'}); + await randomCol.doc('doc8').set({foo2: 'bar8'}); + + const count1 = randomCol + .orderBy('foo2') + .aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count1, 3); + + const count2 = randomCol + .orderBy('foo3') + .aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count2, 0); + }); + + it('counts with startAt, endAt and offset with DocumentReference cursor', async () => { + await randomCol.doc('doc1').set({foo: 'bar'}); + await randomCol.doc('doc2').set({foo: 'bar'}); + await randomCol.doc('doc3').set({foo: 'bar'}); + await randomCol.doc('doc4').set({foo: 'bar'}); + await randomCol.doc('doc5').set({foo: 'bar'}); + await randomCol.doc('doc6').set({foo: 'bar'}); + await randomCol.doc('doc7').set({foo: 'bar'}); + + const count1 = randomCol + .orderBy(FieldPath.documentId()) + .startAfter(randomCol.doc('doc3')) + .aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count1, 4); + + const count2 = randomCol + .orderBy(FieldPath.documentId()) + .startAt(randomCol.doc('doc3')) + .aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count2, 5); + + const count3 = randomCol + .orderBy(FieldPath.documentId()) + .endAt(randomCol.doc('doc3')) + .aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count3, 3); + + const count4 = randomCol + .orderBy(FieldPath.documentId()) + .endBefore(randomCol.doc('doc3')) + .aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count4, 2); + + const count5 = randomCol + .offset(6) + .aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count5, 1); + }); + + it('counts with startAt, endAt and offset with DocumentSnapshot cursor', async () => { + await randomCol.doc('doc1').set({foo: 'bar'}); + await randomCol.doc('doc2').set({foo: 'bar'}); + await randomCol.doc('doc3').set({foo: 'bar'}); + await randomCol.doc('doc4').set({foo: 'bar'}); + await randomCol.doc('doc5').set({foo: 'bar'}); + await randomCol.doc('doc6').set({foo: 'bar'}); + await randomCol.doc('doc7').set({foo: 'bar'}); + const docSnap = await randomCol.doc('doc3').get(); + + const count1 = randomCol + .startAfter(docSnap) + .aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count1, 4); + + const count2 = randomCol + .startAt(docSnap) + .aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count2, 5); + + const count3 = randomCol + .endAt(docSnap) + .aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count3, 3); + + const count4 = randomCol + .endBefore(docSnap) + .aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count4, 2); + + const count5 = randomCol + .offset(6) + .aggregate({count: AggregateField.count()}); + await runQueryAndExpectCount(count5, 1); + }); + } +}); + +describe('Aggregation queries', () => { + let firestore: Firestore; + let col: CollectionReference; + + beforeEach(() => { + col = getTestRoot(); + firestore = col.firestore; + }); + + afterEach(() => verifyInstance(firestore)); + + async function addTestDocs(docs: { + [key: string]: DocumentData; + }): Promise[]> { + const sets: Array> = []; + Object.keys(docs).forEach(key => { + sets.push(col.doc(key).set(docs[key])); + }); + return Promise.all(sets); + } + + it('can run count within a transaction with readtime', async () => { + const doc = col.doc(); + const writeResult: WriteResult = await doc.create({some: 'data'}); + + const count = await firestore.runTransaction(t => t.get(col.count()), { + readOnly: true, + readTime: writeResult.writeTime, + }); + expect(count.data().count).to.equal(1); + + const countBefore = await firestore.runTransaction( + t => t.get(col.count()), + { + readOnly: true, + readTime: Timestamp.fromMillis(writeResult.writeTime.toMillis() - 1), + }, + ); + expect(countBefore.data().count).to.equal(0); + }); + + it('can run count query using aggregate api', async () => { + const testDocs = { + a: {author: 'authorA', title: 'titleA'}, + b: {author: 'authorB', title: 'titleB'}, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + count: AggregateField.count(), + }) + .get(); + expect(snapshot.data().count).to.equal(2); + }); + + it('can alias aggregations using aggregate api', async () => { + const testDocs = { + a: {author: 'authorA', title: 'titleA'}, + b: {author: 'authorB', title: 'titleB'}, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + foo: AggregateField.count(), + 'with.dots': AggregateField.count(), + }) + .get(); + expect(snapshot.data().foo).to.equal(2); + expect(snapshot.data()['with.dots']).to.equal(2); + }); + + it('allows special chars in aliases when using aggregate api', async () => { + const testDocs = { + a: {author: 'authorA', title: 'titleA'}, + b: {author: 'authorB', title: 'titleB'}, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + 'with-un/su+pp[or]ted': AggregateField.count(), + }) + .get(); + + expect(snapshot.data()['with-un/su+pp[or]ted']).to.equal(2); + }); + + it('allows backticks in aliases when using aggregate api', async () => { + const testDocs = { + a: {author: 'authorA', title: 'titleA'}, + b: {author: 'authorB', title: 'titleB'}, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + '`with-un/su+pp[or]ted`': AggregateField.count(), + }) + .get(); + + expect(snapshot.data()['`with-un/su+pp[or]ted`']).to.equal(2); + }); + + it('allows backslash in aliases when using aggregate api', async () => { + const testDocs = { + a: {author: 'authorA', title: 'titleA'}, + b: {author: 'authorB', title: 'titleB'}, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + 'with\\backshash\\es': AggregateField.count(), + }) + .get(); + + expect(snapshot.data()['with\\backshash\\es']).to.equal(2); + }); + + it('can get duplicate aggregations using aggregate api', async () => { + const testDocs = { + a: {author: 'authorA', title: 'titleA'}, + b: {author: 'authorB', title: 'titleB'}, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + count: AggregateField.count(), + foo: AggregateField.count(), + }) + .get(); + expect(snapshot.data().foo).to.equal(2); + expect(snapshot.data().count).to.equal(2); + }); + + it("aggregate() doesn't use converter", async () => { + const testDocs = { + a: {author: 'authorA', title: 'titleA'}, + b: {author: 'authorB', title: 'titleB'}, + }; + const throwingConverter = { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + toFirestore(obj: never): DocumentData { + throw new Error('should never be called'); + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + fromFirestore(snapshot: QueryDocumentSnapshot): never { + throw new Error('should never be called'); + }, + }; + await addTestDocs(testDocs); + const query = col + .where('author', '==', 'authorA') + .withConverter(throwingConverter); + const snapshot = await query + .aggregate({ + count: AggregateField.count(), + }) + .get(); + expect(snapshot.data().count).to.equal(1); + }); + + it('aggregate query supports collection groups', async () => { + const collectionGroupId = autoId(); + const docPaths = [ + `${collectionGroupId}/cg-doc1`, + `abc/123/${collectionGroupId}/cg-doc2`, + `zzz${collectionGroupId}/cg-doc3`, + `abc/123/zzz${collectionGroupId}/cg-doc4`, + `abc/123/zzz/${collectionGroupId}`, + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); + const snapshot = await firestore + .collectionGroup(collectionGroupId) + .aggregate({ + count: AggregateField.count(), + }) + .get(); + expect(snapshot.data().count).to.equal(2); + }); + + it('aggregate() fails if firestore is terminated', async () => { + await firestore.terminate(); + await expect( + col.aggregate({count: AggregateField.count()}).get(), + ).to.eventually.be.rejectedWith('The client has already been terminated'); + }); + + it("terminate doesn't crash when there is aggregate query in flight", async () => { + void col.aggregate({count: AggregateField.count()}).get(); + await firestore.terminate(); + }); + + // Only verify the error message for missing indexes when running against + // production, since the Firestore Emulator does not require index creation + // and will, therefore, never fail in this situation. + // eslint-disable-next-line no-restricted-properties + // TODO (b/429419330) re-enable test when this bug is fixed + (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it.skip)( + 'aggregate query error message contains console link if missing index', + () => { + const query = col.where('key1', '==', 42).where('key2', '<', 42); + const aggregateQuery = query.aggregate({ + count: AggregateField.count(), + sum: AggregateField.sum('pages'), + average: AggregateField.average('pages'), + }); + const databaseId = query.firestore._settings.databaseId ?? '(default)'; + // TODO(b/316359394) Remove this check for the default databases once + // cl/582465034 is rolled out to production. + if (databaseId === '(default)') { + return expect(aggregateQuery.get()).to.be.eventually.rejectedWith( + /index.*https:\/\/console\.firebase\.google\.com/, + ); + } else { + return expect(aggregateQuery.get()).to.be.eventually.rejectedWith( + /index/, + ); + } + }, + ); + + describe('Aggregation queries - sum / average using aggregate() api', () => { + it('can run sum query', async () => { + const testDocs = { + a: {author: 'authorA', title: 'titleA', pages: 100}, + b: {author: 'authorB', title: 'titleB', pages: 50}, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({totalPages: AggregateField.sum('pages')}) + .get(); + expect(snapshot.data().totalPages).to.equal(150); + }); + + it('can run average query', async () => { + const testDocs = { + a: {author: 'authorA', title: 'titleA', pages: 100}, + b: {author: 'authorB', title: 'titleB', pages: 50}, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({averagePages: AggregateField.average('pages')}) + .get(); + expect(snapshot.data().averagePages).to.equal(75); + }); + + it('can get multiple aggregations', async () => { + const testDocs = { + a: {author: 'authorA', title: 'titleA', pages: 100}, + b: {author: 'authorB', title: 'titleB', pages: 50}, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalPages: AggregateField.sum('pages'), + averagePages: AggregateField.average('pages'), + count: AggregateField.count(), + }) + .get(); + expect(snapshot.data().totalPages).to.equal(150); + expect(snapshot.data().averagePages).to.equal(75); + expect(snapshot.data().count).to.equal(2); + }); + + it('can get duplicate aggregations', async () => { + const testDocs = { + a: {author: 'authorA', title: 'titleA', pages: 100}, + b: {author: 'authorB', title: 'titleB', pages: 50}, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalPages: AggregateField.sum('pages'), + averagePages: AggregateField.average('pages'), + totalPagesX: AggregateField.sum('pages'), + averagePagesY: AggregateField.average('pages'), + }) + .get(); + expect(snapshot.data().totalPages).to.equal(150); + expect(snapshot.data().averagePages).to.equal(75); + expect(snapshot.data().totalPagesX).to.equal(150); + expect(snapshot.data().averagePagesY).to.equal(75); + }); + + it('can perform max (5) aggregations', async () => { + const testDocs = { + a: {author: 'authorA', title: 'titleA', pages: 100}, + b: {author: 'authorB', title: 'titleB', pages: 50}, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalPages: AggregateField.sum('pages'), + averagePages: AggregateField.average('pages'), + count: AggregateField.count(), + totalPagesX: AggregateField.sum('pages'), + averagePagesY: AggregateField.average('pages'), + }) + .get(); + expect(snapshot.data().totalPages).to.equal(150); + expect(snapshot.data().averagePages).to.equal(75); + expect(snapshot.data().count).to.equal(2); + expect(snapshot.data().totalPagesX).to.equal(150); + expect(snapshot.data().averagePagesY).to.equal(75); + }); + + // TODO (b/429419330) re-enable test when this bug is fixed + it.skip('fails when exceeding the max (5) aggregations', async () => { + const testDocs = { + a: {author: 'authorA', title: 'titleA', pages: 100}, + b: {author: 'authorB', title: 'titleB', pages: 50}, + }; + await addTestDocs(testDocs); + const aggregateQuery = await col.aggregate({ + totalPages: AggregateField.sum('pages'), + averagePages: AggregateField.average('pages'), + count: AggregateField.count(), + totalPagesX: AggregateField.sum('pages'), + averagePagesY: AggregateField.average('pages'), + countZ: AggregateField.count(), + }); + await expect(aggregateQuery.get()).to.eventually.be.rejectedWith( + /maximum number of aggregations/, + ); + }); + + it('returns undefined when getting the result of an unrequested aggregation', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 5, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 4, + }, + c: { + author: 'authorC', + title: 'titleC', + pages: 100, + year: 1980, + rating: 3, + }, + d: { + author: 'authorD', + title: 'titleD', + pages: 50, + year: 2020, + rating: 0, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalRating: AggregateField.sum('rating'), + averageRating: AggregateField.average('rating'), + }) + .get(); + // @ts-expect-error expected error as 'totalPages' is not in the AggregateSpec. + const totalPages = snapshot.data().totalPages; + expect(totalPages).to.equal(undefined); + }); + + it('performs sum that results in float', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 5, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 4.5, + }, + c: { + author: 'authorB', + title: 'titleB', + pages: 150, + year: 2021, + rating: 3, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalRating: AggregateField.sum('rating'), + }) + .get(); + expect(snapshot.data().totalRating).to.equal(12.5); + }); + + it('performs sum of ints and floats that results in an int', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 5, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 4.5, + }, + c: { + author: 'authorB', + title: 'titleB', + pages: 150, + year: 2021, + rating: 3.5, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalRating: AggregateField.sum('rating'), + }) + .get(); + expect(snapshot.data().totalRating).to.equal(13); + }); + + it('performs sum that overflows max int', async () => { + // A large value that will be represented as a Long on the server, but + // doubling (2x) this value must overflow Long and force the result to be + // represented as a Double type on the server. + const maxLong = Math.pow(2, 63) - 1; + + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: maxLong, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: maxLong, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalRating: AggregateField.sum('rating'), + }) + .get(); + expect(snapshot.data().totalRating).to.equal(maxLong + maxLong); + }); + + it('performs sum that can overflow integer values during accumulation', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: Number.MAX_SAFE_INTEGER, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 1, + }, + c: { + author: 'authorC', + title: 'titleC', + pages: 50, + year: 2020, + rating: -101, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalRating: AggregateField.sum('rating'), + }) + .get(); + expect(snapshot.data().totalRating).to.equal( + Number.MAX_SAFE_INTEGER - 100, + ); + }); + + it('performs sum that is negative', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: Number.MAX_SAFE_INTEGER, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: Number.MIN_SAFE_INTEGER, + }, + c: { + author: 'authorC', + title: 'titleC', + pages: 50, + year: 2020, + rating: -101, + }, + d: { + author: 'authorD', + title: 'titleD', + pages: 50, + year: 2020, + rating: -10000, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalRating: AggregateField.sum('rating'), + }) + .get(); + expect(snapshot.data().totalRating).to.equal(-10101); + }); + + it('performs sum that is positive infinity', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: Number.MAX_VALUE, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: Number.MAX_VALUE, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalRating: AggregateField.sum('rating'), + }) + .get(); + expect(snapshot.data().totalRating).to.equal(Number.POSITIVE_INFINITY); + }); + + it('performs sum that is positive infinity v2', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: Number.MAX_VALUE, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 1e293, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalRating: AggregateField.sum('rating'), + }) + .get(); + expect(snapshot.data().totalRating).to.equal(Number.POSITIVE_INFINITY); + }); + + it('performs sum that is negative infinity', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: -Number.MAX_VALUE, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: -Number.MAX_VALUE, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalRating: AggregateField.sum('rating'), + }) + .get(); + expect(snapshot.data().totalRating).to.equal(Number.NEGATIVE_INFINITY); + }); + + it('performs sum that is valid but could overflow during aggregation', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: Number.MAX_VALUE, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: Number.MAX_VALUE, + }, + c: { + author: 'authorC', + title: 'titleC', + pages: 100, + year: 1980, + rating: -Number.MAX_VALUE, + }, + d: { + author: 'authorD', + title: 'titleD', + pages: 50, + year: 2020, + rating: -Number.MAX_VALUE, + }, + e: { + author: 'authorE', + title: 'titleE', + pages: 100, + year: 1980, + rating: Number.MAX_VALUE, + }, + f: { + author: 'authorF', + title: 'titleF', + pages: 50, + year: 2020, + rating: -Number.MAX_VALUE, + }, + g: { + author: 'authorG', + title: 'titleG', + pages: 100, + year: 1980, + rating: -Number.MAX_VALUE, + }, + h: { + author: 'authorH', + title: 'titleDH', + pages: 50, + year: 2020, + rating: Number.MAX_VALUE, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalRating: AggregateField.sum('rating'), + }) + .get(); + expect(snapshot.data().totalRating).to.oneOf([ + 0, + Number.NEGATIVE_INFINITY, + Number.POSITIVE_INFINITY, + ]); + }); + + it('performs sum that includes NaN', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 5, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 4, + }, + c: { + author: 'authorC', + title: 'titleC', + pages: 100, + year: 1980, + rating: Number.NaN, + }, + d: { + author: 'authorD', + title: 'titleD', + pages: 50, + year: 2020, + rating: 0, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalRating: AggregateField.sum('rating'), + }) + .get(); + expect(snapshot.data().totalRating).to.be.NaN; + }); + + it('performs sum over a result set of zero documents', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 4, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 4, + }, + c: { + author: 'authorC', + title: 'titleC', + pages: 100, + year: 1980, + rating: 3, + }, + d: { + author: 'authorD', + title: 'titleD', + pages: 50, + year: 2020, + rating: 0, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .where('rating', '>', 4) + .aggregate({ + totalRating: AggregateField.sum('rating'), + }) + .get(); + if (isEnterprise()) { + expect(snapshot.data().totalRating).to.equal(null); + } else { + expect(snapshot.data().totalRating).to.equal(0); + } + }); + + it('performs sum only on numeric fields', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 5, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 4, + }, + c: { + author: 'authorC', + title: 'titleC', + pages: 100, + year: 1980, + rating: '3', + }, + d: { + author: 'authorD', + title: 'titleD', + pages: 50, + year: 2020, + rating: 1, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalRating: AggregateField.sum('rating'), + countOfDocs: AggregateField.count(), + }) + .get(); + expect(snapshot.data().totalRating).to.equal(10); + expect(snapshot.data().countOfDocs).to.equal(4); + }); + + it('performs sum of min IEEE754', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: Number.MIN_VALUE, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalRating: AggregateField.sum('rating'), + }) + .get(); + expect(snapshot.data().totalRating).to.equal(Number.MIN_VALUE); + }); + + it('performs average of ints that results in an int', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 10, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 5, + }, + c: { + author: 'authorB', + title: 'titleB', + pages: 150, + year: 2021, + rating: 0, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + averageRating: AggregateField.average('rating'), + }) + .get(); + expect(snapshot.data().averageRating).to.equal(5); + }); + + it('performs average of floats that results in an int', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 10.5, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 9.5, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + averageRating: AggregateField.average('rating'), + }) + .get(); + expect(snapshot.data().averageRating).to.equal(10); + }); + + it('performs average of floats and ints that results in an int', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 10, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 9.5, + }, + c: { + author: 'authorC', + title: 'titleC', + pages: 150, + year: 2021, + rating: 10.5, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + averageRating: AggregateField.average('rating'), + }) + .get(); + expect(snapshot.data().averageRating).to.equal(10); + }); + + it('performs average of float that results in float', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 5.5, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 4.5, + }, + c: { + author: 'authorB', + title: 'titleB', + pages: 150, + year: 2021, + rating: 3.5, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + averageRating: AggregateField.average('rating'), + }) + .get(); + expect(snapshot.data().averageRating).to.equal(4.5); + }); + + it('performs average of floats and ints that results in a float', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 8.6, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 9, + }, + c: { + author: 'authorC', + title: 'titleC', + pages: 150, + year: 2021, + rating: 10, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + averageRating: AggregateField.average('rating'), + }) + .get(); + expect(snapshot.data().averageRating).to.be.approximately(9.2, 0.0000001); + }); + + it('performs average of ints that results in a float', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 10, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 9, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + averageRating: AggregateField.average('rating'), + }) + .get(); + expect(snapshot.data().averageRating).to.equal(9.5); + }); + + it('performs average causing underflow', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: Number.MIN_VALUE, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 0, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + averageRating: AggregateField.average('rating'), + }) + .get(); + expect(snapshot.data().averageRating).to.equal(0); + }); + + it('performs average of min IEEE754', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: Number.MIN_VALUE, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + averageRating: AggregateField.average('rating'), + }) + .get(); + expect(snapshot.data().averageRating).to.equal(Number.MIN_VALUE); + }); + + it('performs average that overflows IEEE754 during accumulation', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: Number.MAX_VALUE, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: Number.MAX_VALUE, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + averageRating: AggregateField.average('rating'), + }) + .get(); + expect(snapshot.data().averageRating).to.equal(Number.POSITIVE_INFINITY); + }); + + it('performs average that includes NaN', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 5, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 4, + }, + c: { + author: 'authorC', + title: 'titleC', + pages: 100, + year: 1980, + rating: Number.NaN, + }, + d: { + author: 'authorD', + title: 'titleD', + pages: 50, + year: 2020, + rating: 0, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + averageRating: AggregateField.average('rating'), + }) + .get(); + expect(snapshot.data().averageRating).to.be.NaN; + }); + + it('performs average over a result set of zero documents', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 4, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 4, + }, + c: { + author: 'authorC', + title: 'titleC', + pages: 100, + year: 1980, + rating: 3, + }, + d: { + author: 'authorD', + title: 'titleD', + pages: 50, + year: 2020, + rating: 0, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .where('rating', '>', 4) + .aggregate({ + averageRating: AggregateField.average('rating'), + }) + .get(); + expect(snapshot.data().averageRating).to.be.null; + }); + + it('performs average only on numeric fields', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 5, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 4, + }, + c: { + author: 'authorC', + title: 'titleC', + pages: 100, + year: 1980, + rating: '3', + }, + d: { + author: 'authorD', + title: 'titleD', + pages: 50, + year: 2020, + rating: 6, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + averageRating: AggregateField.average('rating'), + countOfDocs: AggregateField.count(), + }) + .get(); + expect(snapshot.data().averageRating).to.equal(5); + expect(snapshot.data().countOfDocs).to.equal(4); + }); + + it('allows aliases with length greater than 1500 bytes', async () => { + // Alias string length is bytes of UTF-8 encoded alias + 1; + let longAlias = ''; + for (let i = 0; i < 1500; i++) { + longAlias += '0123456789'; + } + + const longerAlias = longAlias + longAlias; + + const testDocs = { + a: {num: 3}, + b: {num: 5}, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + [longAlias]: AggregateField.count(), + [longerAlias]: AggregateField.count(), + }) + .get(); + expect(snapshot.data()[longAlias]).to.equal(2); + expect(snapshot.data()[longerAlias]).to.equal(2); + }); + + it('performs aggregations on nested map values', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + metadata: {pages: 100, rating: {critic: 2, user: 5}}, + }, + b: { + author: 'authorB', + title: 'titleB', + metadata: {pages: 50, rating: {critic: 4, user: 4}}, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalPages: AggregateField.sum('metadata.pages'), + averagePages: AggregateField.average('metadata.pages'), + count: AggregateField.count(), + }) + .get(); + expect(snapshot.data().totalPages).to.equal(150); + expect(snapshot.data().averagePages).to.equal(75); + expect(snapshot.data().count).to.equal(2); + }); + + it('performs aggregates when using `in` operator', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 5, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 4, + }, + c: { + author: 'authorC', + title: 'titleC', + pages: 100, + year: 1980, + rating: 3, + }, + d: { + author: 'authorD', + title: 'titleD', + pages: 50, + year: 2020, + rating: 0, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .where('rating', 'in', [5, 3]) + .aggregate({ + totalRating: AggregateField.sum('rating'), + averageRating: AggregateField.average('rating'), + countOfDocs: AggregateField.count(), + }) + .get(); + expect(snapshot.data().totalRating).to.equal(8); + expect(snapshot.data().averageRating).to.equal(4); + expect(snapshot.data().countOfDocs).to.equal(2); + }); + }); + + // Only run tests that require indexes against the emulator, because we don't + // have a way to dynamically create the indexes when running the tests. + (process.env.FIRESTORE_EMULATOR_HOST ? describe : describe.skip)( + 'queries requiring indexes', + () => { + it('aggregate query supports collection groups', async () => { + const collectionGroupId = autoId(); + const docPaths = [ + `${collectionGroupId}/cg-doc1`, + `abc/123/${collectionGroupId}/cg-doc2`, + `zzz${collectionGroupId}/cg-doc3`, + `abc/123/zzz${collectionGroupId}/cg-doc4`, + `abc/123/zzz/${collectionGroupId}`, + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 2}); + } + await batch.commit(); + const snapshot = await firestore + .collectionGroup(collectionGroupId) + .aggregate({ + count: AggregateField.count(), + sum: AggregateField.sum('x'), + avg: AggregateField.average('x'), + }) + .get(); + expect(snapshot.data().count).to.equal(2); + expect(snapshot.data().sum).to.equal(4); + expect(snapshot.data().avg).to.equal(2); + }); + + it('performs aggregations on documents with all aggregated fields', async () => { + const testDocs = { + a: {author: 'authorA', title: 'titleA', pages: 100, year: 1980}, + b: {author: 'authorB', title: 'titleB', pages: 50, year: 2020}, + c: {author: 'authorC', title: 'titleC', pages: 150, year: 2021}, + d: {author: 'authorD', title: 'titleD', pages: 50}, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalPages: AggregateField.sum('pages'), + averagePages: AggregateField.average('pages'), + averageYear: AggregateField.average('year'), + count: AggregateField.count(), + }) + .get(); + expect(snapshot.data().totalPages).to.equal(300); + expect(snapshot.data().averagePages).to.equal(100); + expect(snapshot.data().averageYear).to.equal(2007); + expect(snapshot.data().count).to.equal(3); + }); + + it('performs aggregates on multiple fields where one aggregate could cause short-circuit due to NaN', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: 5, + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: 4, + }, + c: { + author: 'authorC', + title: 'titleC', + pages: 100, + year: 1980, + rating: Number.NaN, + }, + d: { + author: 'authorD', + title: 'titleD', + pages: 50, + year: 2020, + rating: 0, + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .aggregate({ + totalRating: AggregateField.sum('rating'), + totalPages: AggregateField.sum('pages'), + averageYear: AggregateField.average('year'), + }) + .get(); + expect(snapshot.data().totalRating).to.be.NaN; + expect(snapshot.data().totalPages).to.equal(300); + expect(snapshot.data().averageYear).to.equal(2000); + }); + + it('performs aggregates when using `array-contains-any` operator', async () => { + const testDocs = { + a: { + author: 'authorA', + title: 'titleA', + pages: 100, + year: 1980, + rating: [5, 1000], + }, + b: { + author: 'authorB', + title: 'titleB', + pages: 50, + year: 2020, + rating: [4], + }, + c: { + author: 'authorC', + title: 'titleC', + pages: 100, + year: 1980, + rating: [2222, 3], + }, + d: { + author: 'authorD', + title: 'titleD', + pages: 50, + year: 2020, + rating: [0], + }, + }; + await addTestDocs(testDocs); + const snapshot = await col + .where('rating', 'array-contains-any', [5, 3]) + .aggregate({ + totalRating: AggregateField.sum('rating'), + averageRating: AggregateField.average('rating'), + totalPages: AggregateField.sum('pages'), + averagePages: AggregateField.average('pages'), + countOfDocs: AggregateField.count(), + }) + .get(); + expect(snapshot.data().totalRating).to.equal(0); + expect(snapshot.data().averageRating).to.be.null; + expect(snapshot.data().totalPages).to.equal(200); + expect(snapshot.data().averagePages).to.equal(100); + expect(snapshot.data().countOfDocs).to.equal(2); + }); + }, + ); + + describe('Aggregation queries - orderBy Normalization Checks', () => { + async function addTwoDocs(): Promise { + const testDocs = { + a: {author: 'authorA', title: 'titleA', num: 5, foo: 1}, + b: {author: 'authorB', title: 'titleB', num: 7, foo: 2}, + }; + await addTestDocs(testDocs); + } + + it('no filter, no orderBy, no cursor', async () => { + await addTwoDocs(); + const snapshot = await col + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(12); + }); + + it('equality filter, no orderBy, no cursor', async () => { + await addTwoDocs(); + const snapshot = await col + .where('num', '==', 5) + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(5); + }); + + it('inequality filter, no orderBy, no cursor', async () => { + await addTwoDocs(); + const snapshot = await col + .where('num', '>', 5) + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(7); + }); + + it('no filter, explicit orderBy, no cursor', async () => { + await addTwoDocs(); + const snapshot = await col + .orderBy('num') + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(12); + }); + + it('equality filter, explicit orderBy, no cursor', async () => { + await addTwoDocs(); + const snapshot = await col + .where('num', '==', 5) + .orderBy('num') + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(5); + }); + + it('inequality filter, explicit orderBy, no cursor', async () => { + await addTwoDocs(); + const snapshot = await col + .where('num', '>', 5) + .orderBy('num') + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(7); + }); + + it('no filter, explicit orderBy, field value cursor', async () => { + await addTwoDocs(); + const snapshot = await col + .orderBy('num') + .startAfter(5) + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(7); + }); + + // This is expected to fail because it requires the `__name__, num` index. + // SDK sends: orderBy __name__ + it.skip('no filter, explicit orderBy, document reference cursor', async () => { + await addTwoDocs(); + const snapshot = await col + .orderBy(FieldPath.documentId()) + .startAfter(col.doc('a')) + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(7); + }); + + // This is expected to fail because it requires the `__name__, num` index. + // SDK sends: orderBy __name__ + it.skip('no filter, no orderBy, document reference cursor', async () => { + await addTwoDocs(); + const docSnap = await col.doc('a').get(); + const snapshot = await col + .startAfter(docSnap) + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(7); + }); + + // This is expected to fail because it requires the `foo, __name__, num` index. + // SDK sends: orderBy foo, __name__ + it.skip('no filter, explicit orderBy, document reference cursor', async () => { + await addTwoDocs(); + const docSnap = await col.doc('a').get(); + const snapshot = await col + .orderBy('foo') + .startAfter(docSnap) + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(7); + }); + + // This just happens to work because the orderBy field matches the aggregation field. + // SDK sends: orderBy num, __name__ + it('no filter, explicit orderBy, document reference cursor', async () => { + await addTwoDocs(); + const docSnap = await col.doc('a').get(); + const snapshot = await col + .orderBy('num') + .startAfter(docSnap) + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(7); + }); + + it('equality filter, explicit orderBy, field value cursor', async () => { + await addTwoDocs(); + const snapshot = await col + .where('num', '==', 5) + .orderBy('num') + .startAt(5) + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(5); + }); + + it('inequality filter, explicit orderBy, field value cursor', async () => { + await addTwoDocs(); + const snapshot = await col + .where('num', '>', 5) + .orderBy('num') + .startAt(5) + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(7); + }); + + // This is expected to fail because it requires the `__name__, num` index. + // SDK sends: orderBy __name__ + it.skip('equality filter, explicit orderBy, document reference cursor', async () => { + await addTwoDocs(); + const snapshot = await col + .where('num', '==', 7) + .orderBy(FieldPath.documentId()) + .startAfter(col.doc('a')) + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(7); + }); + + // Full orderBy is provided. + // SDK sends: orderBy num, __name__ + it('inequality filter, explicit orderBy, document reference cursor', async () => { + await addTwoDocs(); + const snapshot = await col + .where('num', '>', 5) + .orderBy('num') + .orderBy(FieldPath.documentId()) + .startAfter(5, col.doc('a')) + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(7); + }); + + // This is expected to fail because it requires the `__name__, num` index. + // SDK sends: orderBy __name__ + it.skip('equality filter, no orderBy, document reference cursor', async () => { + await addTwoDocs(); + const docSnap = await col.doc('a').get(); + const snapshot = await col + .where('num', '==', 7) + .startAfter(docSnap) + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(7); + }); + + // This just happens to work because the orderBy field matches the aggregation field. + // SDK sends: orderBy num, __name__ + it('inequality filter, no orderBy, document reference cursor', async () => { + await addTwoDocs(); + const docSnap = await col.doc('a').get(); + const snapshot = await col + .where('num', '>', 0) + .startAfter(docSnap) + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(7); + }); + + // This is expected to fail because it requires the `foo, __name__, num` index. + // SDK sends: orderBy foo, __name__ + it.skip('inequality filter, no orderBy, document reference cursor 2', async () => { + await addTwoDocs(); + const docSnap = await col.doc('a').get(); + const snapshot = await col + .where('foo', '>', 0) + .startAfter(docSnap) + .aggregate({sum: AggregateField.sum('num')}) + .get(); + expect(snapshot.data().sum).to.equal(7); + }); + }); +}); + +describe('Transaction class', () => { + let firestore: Firestore; + let randomCol: CollectionReference; + + beforeEach(() => { + randomCol = getTestRoot(); + firestore = randomCol.firestore; + }); + + afterEach(() => verifyInstance(firestore)); + + it('has get() method', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar'}) + .then(() => { + return firestore.runTransaction(updateFunction => { + return updateFunction.get(ref).then(doc => { + return Promise.resolve(doc.get('foo')); + }); + }); + }) + .then(res => { + expect(res).to.equal('bar'); + }); + }); + + it('has getAll() method', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + return Promise.all([ref1.set({}), ref2.set({})]) + .then(() => { + return firestore.runTransaction(updateFunction => { + return updateFunction.getAll(ref1, ref2).then(docs => { + return Promise.resolve(docs.length); + }); + }); + }) + .then(res => { + expect(res).to.equal(2); + }); + }); + + it('getAll() supports array destructuring', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + return Promise.all([ref1.set({}), ref2.set({})]) + .then(() => { + return firestore.runTransaction(updateFunction => { + return updateFunction.getAll(...[ref1, ref2]).then(docs => { + return Promise.resolve(docs.length); + }); + }); + }) + .then(res => { + expect(res).to.equal(2); + }); + }); + + it('getAll() supports field mask', () => { + const ref1 = randomCol.doc('doc1'); + return ref1.set({foo: 'a', bar: 'b'}).then(() => { + return firestore + .runTransaction(updateFunction => { + return updateFunction + .getAll(ref1, {fieldMask: ['foo']}) + .then(([doc]) => doc); + }) + .then(doc => { + expect(doc.data()).to.deep.equal({foo: 'a'}); + }); + }); + }); + + it('getAll() supports array destructuring with field mask', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + return Promise.all([ + ref1.set({f: 'a', b: 'b'}), + ref2.set({f: 'a', b: 'b'}), + ]).then(() => { + return firestore + .runTransaction(updateFunction => { + return updateFunction + .getAll(...[ref1, ref2], {fieldMask: ['f']}) + .then(docs => docs); + }) + .then(docs => { + expect(docs[0].data()).to.deep.equal({f: 'a'}); + expect(docs[1].data()).to.deep.equal({f: 'a'}); + }); + }); + }); + + it('getAll() supports withConverter()', async () => { + const ref1 = randomCol.doc('doc1').withConverter(postConverter); + const ref2 = randomCol.doc('doc2').withConverter(postConverter); + await ref1.set(new Post('post1', 'author1')); + await ref2.set(new Post('post2', 'author2')); + + const docs = await firestore.runTransaction(updateFunction => { + return updateFunction.getAll(ref1, ref2); + }); + + expect(docs[0].data()!.toString()).to.equal('post1, by author1'); + expect(docs[1].data()!.toString()).to.equal('post2, by author2'); + }); + + it('set() and get() support withConverter()', async () => { + const ref = randomCol.doc('doc1').withConverter(postConverter); + await ref.set(new Post('post', 'author')); + await firestore.runTransaction(async txn => { + await txn.get(ref); + await txn.set(ref, new Post('new post', 'author')); + }); + const doc = await ref.get(); + expect(doc.data()!.toString()).to.equal('new post, by author'); + }); + + it('has get() with query', () => { + const ref = randomCol.doc('doc'); + const query = randomCol.where('foo', '==', 'bar'); + return ref + .set({foo: 'bar'}) + .then(() => { + return firestore.runTransaction(updateFunction => { + return updateFunction.get(query).then(res => { + return Promise.resolve(res.docs[0].get('foo')); + }); + }); + }) + .then(res => { + expect(res).to.equal('bar'); + }); + }); + + it('has set() method', () => { + const ref = randomCol.doc('doc'); + return firestore + .runTransaction(updateFunction => { + updateFunction.set(ref, {foo: 'foobar'}); + return Promise.resolve(); + }) + .then(() => { + return ref.get(); + }) + .then(doc => { + expect(doc.get('foo')).to.equal('foobar'); + }); + }); + + it('has update() method', () => { + const ref = randomCol.doc('doc'); + return ref + .set({ + boo: ['ghost', 'sebastian'], + moo: 'chicken', + }) + .then(() => { + return firestore.runTransaction(updateFunction => { + return updateFunction.get(ref).then(() => { + updateFunction.update(ref, { + boo: FieldValue.arrayRemove('sebastian'), + moo: 'cow', + }); + }); + }); + }) + .then(() => { + return ref.get(); + }) + .then(doc => { + expect(doc.data()).to.deep.equal({ + boo: ['ghost'], + moo: 'cow', + }); + }); + }); + + it('has delete() method', () => { + let success = false; + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar'}) + .then(() => { + return firestore.runTransaction(updateFunction => { + updateFunction.delete(ref); + return Promise.resolve(); + }); + }) + .then(() => { + success = true; + return ref.get(); + }) + .then(result => { + expect(success).to.be.true; + expect(result.exists).to.be.false; + }); + }); + + // TODO (b/429419330) re-enable test when this bug is fixed + it.skip('does not retry transaction that fail with FAILED_PRECONDITION', async () => { + const ref = firestore.collection('col').doc(); + + let attempts = 0; + + const promise = firestore.runTransaction(async transaction => { + ++attempts; + transaction.update(ref, {foo: 'b'}); + }); + + // Validate the error message when testing against the firestore backend. + if (process.env.FIRESTORE_EMULATOR_HOST === undefined) { + await expect(promise).to.eventually.be.rejectedWith( + /No document to update/, + ); + } else { + // The emulator generates a different error message, do not validate the error message. + await expect(promise).to.eventually.be.rejected; + } + + expect(attempts).to.equal(1); + }); + + // Skip this test when running against the emulator because it does not work + // against the emulator. Contention in the emulator may behave differently. + (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it.skip)( + 'retries transactions that fail with contention', + async () => { + const ref = randomCol.doc('doc'); + + let attempts = 0; + + // Create two transactions that both read and update the same document. + // `contentionPromise` is used to ensure that both transactions are active + // on commit, which causes one of transactions to fail with Code ABORTED + // and be retried. + const contentionPromise = [new Deferred(), new Deferred()]; + + const firstTransaction = firestore.runTransaction(async transaction => { + ++attempts; + await transaction.get(ref); + contentionPromise[0].resolve(); + await contentionPromise[1].promise; + transaction.set(ref, {first: true}, {merge: true}); + }); + + const secondTransaction = firestore.runTransaction(async transaction => { + ++attempts; + await transaction.get(ref); + contentionPromise[1].resolve(); + await contentionPromise[0].promise; + transaction.set(ref, {second: true}, {merge: true}); + }); + + await firstTransaction; + await secondTransaction; + + expect(attempts).to.equal(3); + + const finalSnapshot = await ref.get(); + expect(finalSnapshot.data()).to.deep.equal({first: true, second: true}); + }, + ); + + it('supports read-only transactions', async () => { + const ref = randomCol.doc('doc'); + await ref.set({foo: 'bar'}); + const snapshot = await firestore.runTransaction( + updateFunction => updateFunction.get(ref), + {readOnly: true}, + ); + expect(snapshot.exists).to.be.true; + }); + + it('supports read-only transactions with custom read-time', async () => { + const ref = randomCol.doc('doc'); + const writeResult = await ref.set({foo: 1}); + await ref.set({foo: 2}); + const snapshot = await firestore.runTransaction( + updateFunction => updateFunction.get(ref), + {readOnly: true, readTime: writeResult.writeTime}, + ); + expect(snapshot.exists).to.be.true; + expect(snapshot.get('foo')).to.equal(1); + }); +}); + +describe('WriteBatch class', () => { + let firestore: Firestore; + let randomCol: CollectionReference; + + beforeEach(() => { + randomCol = getTestRoot(); + firestore = randomCol.firestore; + }); + + afterEach(() => verifyInstance(firestore)); + + it('supports empty batches', () => { + return firestore.batch().commit(); + }); + + it('has create() method', () => { + const ref = randomCol.doc(); + const batch = firestore.batch(); + batch.create(ref, {foo: 'a'}); + return batch + .commit() + .then(() => { + return ref.get(); + }) + .then(doc => { + expect(doc.get('foo')).to.equal('a'); + }); + }); + + it('has set() method', () => { + const ref = randomCol.doc('doc'); + const batch = firestore.batch(); + batch.set(ref, {foo: 'a'}); + return batch + .commit() + .then(() => { + return ref.get(); + }) + .then(doc => { + expect(doc.get('foo')).to.equal('a'); + }); + }); + + it('set supports partials', async () => { + const ref = randomCol.doc('doc').withConverter(postConverterMerge); + await ref.set(new Post('walnut', 'author')); + const batch = firestore.batch(); + batch.set(ref, {title: 'olive'}, {merge: true}); + return batch + .commit() + .then(() => { + return ref.get(); + }) + .then(doc => { + expect(doc.get('title')).to.equal('olive'); + expect(doc.get('author')).to.equal('author'); + }); + }); + + it('set()', () => { + const ref = randomCol.doc('doc'); + const batch = firestore.batch(); + batch.set(ref, {foo: 'a'}); + return batch + .commit() + .then(() => { + return ref.get(); + }) + .then(doc => { + expect(doc.get('foo')).to.equal('a'); + }); + }); + + it('has a full stack trace if set() errors', async () => { + // Use an invalid document name that the backend will reject. + const ref = randomCol.doc('__doc__'); + const batch = firestore.batch(); + batch.set(ref, {foo: 'a'}); + await batch + .commit() + .then(() => Promise.reject('commit() should have failed')) + .catch((err: Error) => { + expect(err.stack).to.contain('WriteBatch.commit'); + }); + }); + + it('has update() method', () => { + const ref = randomCol.doc('doc'); + const batch = firestore.batch(); + batch.set(ref, {foo: 'a'}); + batch.update(ref, {foo: 'b'}); + return batch + .commit() + .then(() => { + return ref.get(); + }) + .then(doc => { + expect(doc.get('foo')).to.equal('b'); + }); + }); + + it('omits document transforms from write results', () => { + const batch = firestore.batch(); + batch.set(randomCol.doc(), {foo: 'a'}); + batch.set(randomCol.doc(), {foo: FieldValue.serverTimestamp()}); + return batch.commit().then(writeResults => { + expect(writeResults).to.have.length(2); + }); + }); + + it('enforces that updated document exists', () => { + const ref = randomCol.doc(); + const batch = firestore.batch(); + batch.update(ref, {foo: 'b'}); + return batch + .commit() + .then(() => { + expect.fail(); + }) + .catch(err => { + expect(err.message.match(/No document to update/)); + }); + }); + + it('has delete() method', () => { + let success = false; + + const ref = randomCol.doc('doc'); + const batch = firestore.batch(); + batch.set(ref, {foo: 'a'}); + batch.delete(ref); + return batch + .commit() + .then(() => { + success = true; + return ref.get(); + }) + .then(result => { + expect(success).to.be.true; + expect(result.exists).to.be.false; + }); + }); +}); + +describe('QuerySnapshot class', () => { + let firestore: Firestore; + let querySnapshot: Promise; + + beforeEach(() => { + const randomCol = getTestRoot(); + firestore = randomCol.firestore; + + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + querySnapshot = Promise.all([ + ref1.set({foo: 'a'}), + ref2.set({foo: 'a'}), + ]).then(() => { + return randomCol.get(); + }); + }); + + afterEach(() => verifyInstance(firestore)); + + it('has query property', () => { + return querySnapshot + .then(snapshot => { + return snapshot.query.get(); + }) + .then(snapshot => { + expect(snapshot.size).to.equal(2); + }); + }); + + it('has empty property', () => { + return querySnapshot + .then(snapshot => { + expect(snapshot.empty).to.be.false; + expect(snapshot.readTime).to.exist; + return snapshot.query.where('foo', '==', 'bar').get(); + }) + .then(snapshot => { + expect(snapshot.empty).to.be.true; + expect(snapshot.readTime).to.exist; + }); + }); + + it('has size property', () => { + return querySnapshot.then(snapshot => { + expect(snapshot.size).to.equal(2); + }); + }); + + it('has docs property', () => { + return querySnapshot.then(snapshot => { + expect(snapshot.docs).to.have.length(2); + expect(snapshot.docs[0].get('foo')).to.equal('a'); + }); + }); + + it('has forEach() method', () => { + let count = 0; + + return querySnapshot.then(snapshot => { + snapshot.forEach(doc => { + expect(doc.get('foo')).to.equal('a'); + ++count; + }); + expect(count).to.equal(2); + }); + }); +}); + +describe('BulkWriter class', () => { + let firestore: Firestore; + let randomCol: CollectionReference; + let writer: BulkWriter; + + beforeEach(() => { + randomCol = getTestRoot(); + firestore = randomCol.firestore; + writer = firestore.bulkWriter(); + }); + + afterEach(async () => { + await writer.close(); + await verifyInstance(firestore); + await firestore.terminate(); + }); + + it('has create() method', async () => { + const ref = randomCol.doc('doc1'); + const singleOp = writer.create(ref, {foo: 'bar'}); + await writer.close(); + const result = await ref.get(); + expect(result.data()).to.deep.equal({foo: 'bar'}); + const writeTime = (await singleOp).writeTime; + expect(writeTime).to.not.be.null; + }); + + it('has set() method', async () => { + const ref = randomCol.doc('doc1'); + const singleOp = writer.set(ref, {foo: 'bar'}); + await writer.close(); + const result = await ref.get(); + expect(result.data()).to.deep.equal({foo: 'bar'}); + const writeTime = (await singleOp).writeTime; + expect(writeTime).to.not.be.null; + }); + + it('has update() method', async () => { + const ref = randomCol.doc('doc1'); + await ref.set({foo: 'bar'}); + const singleOp = writer.update(ref, {foo: 'bar2'}); + await writer.close(); + const result = await ref.get(); + expect(result.data()).to.deep.equal({foo: 'bar2'}); + const writeTime = (await singleOp).writeTime; + expect(writeTime).to.not.be.null; + }); + + it('has delete() method', async () => { + const ref = randomCol.doc('doc1'); + await ref.set({foo: 'bar'}); + const singleOp = writer.delete(ref); + await writer.close(); + const result = await ref.get(); + expect(result.exists).to.be.false; + // TODO(b/158502664): Remove this check once we can get write times. + const deleteResult = await singleOp; + expect(deleteResult.writeTime).to.deep.equal(new Timestamp(0, 0)); + }); + + it('can write to the same document twice', async () => { + const ref = randomCol.doc('doc1'); + const op1 = writer.set(ref, {foo: 'bar'}); + const op2 = writer.set(ref, {foo: 'bar2'}); + await writer.close(); + const result = await ref.get(); + // The order of writes is not guaranteed. + expect(result.get('foo')).to.not.be.undefined; + const writeTime1 = (await op1).writeTime; + const writeTime2 = (await op2).writeTime; + expect(writeTime1).to.not.be.null; + expect(writeTime2).to.not.be.null; + }); + + it('can terminate once BulkWriter is closed', async () => { + const ref = randomCol.doc('doc1'); + void writer.set(ref, {foo: 'bar'}); + await writer.close(); + return firestore.terminate(); + }); + + describe('recursiveDelete()', () => { + async function countDocumentChildren( + ref: DocumentReference, + ): Promise { + let count = 0; + const collections = await ref.listCollections(); + for (const collection of collections) { + count += await countCollectionChildren(collection); + } + return count; + } + + async function countCollectionChildren( + ref: CollectionReference, + ): Promise { + let count = 0; + const docs = await ref.listDocuments(); + for (const doc of docs) { + count += (await countDocumentChildren(doc)) + 1; + } + return count; + } + + beforeEach(async () => { + // ROOT-DB + // └── randomCol + // ├── anna + // └── bob + // └── parentsCol + // ├── charlie + // └── daniel + // └── childCol + // ├── ernie + // └── francis + const batch = firestore.batch(); + batch.set(randomCol.doc('anna'), {name: 'anna'}); + batch.set(randomCol.doc('bob'), {name: 'bob'}); + batch.set(randomCol.doc('bob/parentsCol/charlie'), {name: 'charlie'}); + batch.set(randomCol.doc('bob/parentsCol/daniel'), {name: 'daniel'}); + batch.set(randomCol.doc('bob/parentsCol/daniel/childCol/ernie'), { + name: 'ernie', + }); + batch.set(randomCol.doc('bob/parentsCol/daniel/childCol/francis'), { + name: 'francis', + }); + await batch.commit(); + }); + + it.skipEnterprise('on top-level collection', async () => { + await firestore.recursiveDelete(randomCol); + expect(await countCollectionChildren(randomCol)).to.equal(0); + }); + + it.skipEnterprise('on nested collection', async () => { + const coll = randomCol.doc('bob').collection('parentsCol'); + await firestore.recursiveDelete(coll); + + expect(await countCollectionChildren(coll)).to.equal(0); + expect(await countCollectionChildren(randomCol)).to.equal(2); + }); + + // TODO enterprise waiting on b/469490062 + it.skip('on nested document', async () => { + const doc = randomCol.doc('bob/parentsCol/daniel'); + await firestore.recursiveDelete(doc); + + const docSnap = await doc.get(); + expect(docSnap.exists).to.be.false; + expect(await countDocumentChildren(randomCol.doc('bob'))).to.equal(1); + expect(await countCollectionChildren(randomCol)).to.equal(3); + }); + + // TODO enterprise b/469490062 + it.skipEnterprise('on leaf document', async () => { + const doc = randomCol.doc('bob/parentsCol/daniel/childCol/ernie'); + await firestore.recursiveDelete(doc); + + const docSnap = await doc.get(); + expect(docSnap.exists).to.be.false; + expect(await countCollectionChildren(randomCol)).to.equal(5); + }); + + // TODO enterprise b/469490062 + it.skipEnterprise('does not affect other collections', async () => { + // Add other nested collection that shouldn't be deleted. + const collB = firestore.collection('doggos'); + await collB.doc('doggo').set({name: 'goodboi'}); + + await firestore.recursiveDelete(collB); + expect(await countCollectionChildren(randomCol)).to.equal(6); + expect(await countCollectionChildren(collB)).to.equal(0); + }); + + it('with custom BulkWriter instance', async () => { + const bulkWriter = firestore.bulkWriter(); + let callbackCount = 0; + bulkWriter.onWriteResult(() => { + callbackCount++; + }); + await firestore.recursiveDelete(randomCol, bulkWriter); + expect(callbackCount).to.equal(6); + await bulkWriter.close(); + }); + }); + + it('can retry failed writes with a provided callback', async () => { + let retryCount = 0; + let code: Status = -1 as Status; + writer.onWriteError(error => { + retryCount = error.failedAttempts; + return error.failedAttempts < 3; + }); + + // Use an invalid document name that the backend will reject. + const ref = randomCol.doc('__doc__'); + writer.create(ref, {foo: 'bar'}).catch(err => { + code = err.code; + }); + await writer.close(); + expect(retryCount).to.equal(3); + if (firestore._settings.preferRest) { + expect(code).to.equal(400); + } else { + expect(code).to.equal(Status.INVALID_ARGUMENT); + } + }); +}); + +describe('Client initialization', () => { + const ops: Array< + [ + string, + (coll: CollectionReference) => Promise, + /* skip */ boolean?, + ] + > = [ + ['CollectionReference.get()', randomColl => randomColl.get()], + ['CollectionReference.add()', randomColl => randomColl.add({})], + [ + 'CollectionReference.stream()', + randomColl => { + const deferred = new Deferred(); + randomColl.stream().on('finish', () => { + deferred.resolve(); + }); + return deferred.promise; + }, + ], + [ + 'CollectionReference.listDocuments()', + + randomColl => { + if (process.env.RUN_ENTERPRISE_TESTS) return Promise.resolve(); + return randomColl.listDocuments(); + }, + ], + [ + 'CollectionReference.onSnapshot()', + randomColl => { + const deferred = new Deferred(); + const unsubscribe = randomColl.onSnapshot(() => { + unsubscribe(); + deferred.resolve(); + }); + return deferred.promise; + }, + ], + ['DocumentReference.get()', randomColl => randomColl.doc().get()], + ['DocumentReference.create()', randomColl => randomColl.doc().create({})], + ['DocumentReference.set()', randomColl => randomColl.doc().set({})], + [ + 'DocumentReference.update()', + async randomColl => { + const update = randomColl.doc().update('foo', 'bar'); + + // Don't validate the error message when running against the emulator. + // Emulator gives different error message. + // TODO (b/429419330) re-enable assertion when this bug is fixed + if (process.env.FIRESTORE_EMULATOR_HOST === undefined) { + // await expect(update).to.eventually.be.rejectedWith( + // 'No document to update', + // ); + await expect(update).to.eventually.be.rejected; + } else { + await expect(update).to.eventually.be.rejected; + } + }, + ], + ['DocumentReference.delete()', randomColl => randomColl.doc().delete()], + [ + 'DocumentReference.listCollections()', + randomColl => { + // TODO enterprise waiting on b/469490062, skip for now + if (isEnterprise()) return Promise.resolve(); + return randomColl.doc().listCollections(); + }, + ], + [ + 'DocumentReference.onSnapshot()', + randomColl => { + const deferred = new Deferred(); + const unsubscribe = randomColl.doc().onSnapshot(() => { + unsubscribe(); + deferred.resolve(); + }); + return deferred.promise; + }, + ], + [ + 'CollectionGroup.getPartitions()', + async randomColl => { + // Requires PartitionQuery support + if (process.env.RUN_ENTERPRISE_TESTS) return; + + const partitions = randomColl.firestore + .collectionGroup('id') + .getPartitions(2); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + for await (const _ of partitions); + }, + // Skip this test when running against the emulator because partition queries + // are not supported in the emulator. + !!process.env.FIRESTORE_EMULATOR_HOST, + ], + [ + 'Firestore.runTransaction()', + randomColl => randomColl.firestore.runTransaction(t => t.get(randomColl)), + ], + [ + 'Firestore.getAll()', + randomColl => randomColl.firestore.getAll(randomColl.doc()), + ], + ['Firestore.batch()', randomColl => randomColl.firestore.batch().commit()], + ['Firestore.terminate()', randomColl => randomColl.firestore.terminate()], + ]; + + for (const [description, op, skip] of ops) { + (!skip ? it : it.skip)(`succeeds for ${description}`, () => { + const randomCol = getTestRoot(); + return op(randomCol); + }); + } +}); + +describe('Bundle building', () => { + let firestore: Firestore; + let testCol: CollectionReference; + + beforeEach(async () => { + testCol = getTestRoot(); + firestore = testCol.firestore; + + const ref1 = testCol.doc('doc1'); + const ref2 = testCol.doc('doc2'); + const ref3 = testCol.doc('doc3'); + const ref4 = testCol.doc('doc4'); + + await Promise.all([ + ref1.set({name: '1', sort: 1, value: 'string value'}), + ref2.set({name: '2', sort: 2, value: 42}), + ref3.set({name: '3', sort: 3, value: {nested: 'nested value'}}), + ref4.set({ + name: '4', + sort: 4, + value: FieldValue.serverTimestamp(), + }), + ]); + }); + + afterEach(() => verifyInstance(firestore)); + + it('succeeds when there are no results', async () => { + const bundle = firestore.bundle(TEST_BUNDLE_ID); + const query = testCol.where('value', '==', '42'); + const snap = await query.get(); + + bundle.add('query', snap); + // `elements` is expected to be [bundleMeta, query]. + const elements = await bundleToElementArray(bundle.build()); + + const meta = (elements[0] as IBundleElement).metadata; + verifyMetadata(meta!, snap.readTime.toProto().timestampValue!, 0); + + const namedQuery = (elements[1] as IBundleElement).namedQuery; + // Verify saved query. + expect(namedQuery).to.deep.equal({ + name: 'query', + readTime: snap.readTime.toProto().timestampValue, + // TODO(wuandy): Fix query.toProto to skip undefined fields, so we can stop using `extend` here. + bundledQuery: extend( + true, + {}, + { + parent: query.toProto().parent, + structuredQuery: query.toProto().structuredQuery, + }, + ), + }); + }); + + it('succeeds when added document does not exist', async () => { + const bundle = firestore.bundle(TEST_BUNDLE_ID); + const snap = await testCol.doc('doc5-not-exist').get(); + + bundle.add(snap); + // `elements` is expected to be [bundleMeta, docMeta]. + const elements = await bundleToElementArray(bundle.build()); + expect(elements.length).to.equal(2); + + const meta = (elements[0] as IBundleElement).metadata; + verifyMetadata(meta!, snap.readTime.toProto().timestampValue!, 1); + + const docMeta = (elements[1] as IBundleElement).documentMetadata; + expect(docMeta).to.deep.equal({ + name: snap.toDocumentProto().name, + readTime: snap.readTime.toProto().timestampValue, + exists: false, + }); + }); + + it('succeeds to save limit and limitToLast queries', async () => { + const bundle = firestore.bundle(TEST_BUNDLE_ID); + const limitQuery = testCol.orderBy('sort', 'desc').limit(1); + const limitSnap = await limitQuery.get(); + const limitToLastQuery = testCol.orderBy('sort', 'asc').limitToLast(1); + const limitToLastSnap = await limitToLastQuery.get(); + + bundle.add('limitQuery', limitSnap); + bundle.add('limitToLastQuery', limitToLastSnap); + // `elements` is expected to be [bundleMeta, limitQuery, limitToLastQuery, doc4Meta, doc4Snap]. + const elements = await bundleToElementArray(await bundle.build()); + + const meta = (elements[0] as IBundleElement).metadata; + verifyMetadata( + meta!, + limitToLastSnap.readTime.toProto().timestampValue!, + 1, + ); + + let namedQuery1 = (elements[1] as IBundleElement).namedQuery; + let namedQuery2 = (elements[2] as IBundleElement).namedQuery; + // We might need to swap them. + if (namedQuery1!.name === 'limitToLastQuery') { + const temp = namedQuery2; + namedQuery2 = namedQuery1; + namedQuery1 = temp; + } + + // Verify saved limit query. + expect(namedQuery1).to.deep.equal({ + name: 'limitQuery', + readTime: limitSnap.readTime.toProto().timestampValue, + bundledQuery: extend( + true, + {}, + { + parent: limitQuery.toProto().parent, + structuredQuery: limitQuery.toProto().structuredQuery, + limitType: 'FIRST', + }, + ), + }); + + // `limitToLastQuery`'s structured query should be the same as this one. This together with + // `limitType` can re-construct a limitToLast client query by client SDKs. + const q = testCol.orderBy('sort', 'asc').limit(1); + // Verify saved limitToLast query. + expect(namedQuery2).to.deep.equal({ + name: 'limitToLastQuery', + readTime: limitToLastSnap.readTime.toProto().timestampValue, + bundledQuery: extend( + true, + {}, + { + parent: q.toProto().parent, + structuredQuery: q.toProto().structuredQuery, + limitType: 'LAST', + }, + ), + }); + + // Verify bundled document + const docMeta = (elements[3] as IBundleElement).documentMetadata; + expect(docMeta).to.deep.equal({ + name: limitToLastSnap.docs[0].toDocumentProto().name, + readTime: limitToLastSnap.readTime.toProto().timestampValue, + exists: true, + queries: ['limitQuery', 'limitToLastQuery'], + }); + + const bundledDoc = (elements[4] as IBundleElement).document; + // The `valueType` is auxiliary and does not exist in proto. + const expected = limitToLastSnap.docs[0].toDocumentProto(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + delete (expected.fields!.name as any).valueType; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + delete (expected.fields!.sort as any).valueType; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + delete (expected.fields!.value as any).valueType; + expect(bundledDoc).to.deep.equal(expected); + }); +}); + +describe('Types test', () => { + let firestore: Firestore; + let randomCol: CollectionReference; + let doc: DocumentReference; + + class TestObject { + constructor( + readonly outerString: string, + readonly outerArr: string[], + readonly nested: { + innerNested: { + innerNestedNum: number; + }; + innerArr: number[]; + timestamp: Timestamp; + }, + ) {} + } + + const testConverter = { + toFirestore(testObj: WithFieldValue) { + return {...testObj}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): TestObject { + const data = snapshot.data(); + return new TestObject(data.outerString, data.outerArr, data.nested); + }, + }; + + const initialData = { + outerString: 'foo', + outerArr: [], + nested: { + innerNested: { + innerNestedNum: 2, + }, + innerArr: FieldValue.arrayUnion(2), + timestamp: FieldValue.serverTimestamp(), + }, + }; + + beforeEach(async () => { + randomCol = getTestRoot(); + firestore = randomCol.firestore; + doc = randomCol.doc(); + + await doc.set(initialData); + }); + + afterEach(() => verifyInstance(firestore)); + + describe('Nested partial support', () => { + const testConverterMerge = { + toFirestore( + testObj: PartialWithFieldValue, + options?: SetOptions, + ) { + if (options) { + expect(testObj).to.not.be.an.instanceOf(TestObject); + } else { + expect(testObj).to.be.an.instanceOf(TestObject); + } + return {...testObj}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): TestObject { + const data = snapshot.data(); + return new TestObject(data.outerString, data.outerArr, data.nested); + }, + }; + + it('supports FieldValues', async () => { + const ref = doc.withConverter(testConverterMerge); + + // Allow Field Values in nested partials. + await ref.set( + { + outerString: FieldValue.delete(), + nested: { + innerNested: { + innerNestedNum: FieldValue.increment(1), + }, + innerArr: FieldValue.arrayUnion(2), + timestamp: FieldValue.serverTimestamp(), + }, + }, + {merge: true}, + ); + + // Allow setting FieldValue on entire object field. + await ref.set( + { + nested: FieldValue.delete(), + }, + {merge: true}, + ); + }); + + it('validates types in outer and inner fields', async () => { + const ref = doc.withConverter(testConverterMerge); + + // Check top-level fields. + await ref.set( + { + // @ts-expect-error Should fail to transpile. + outerString: 3, + // @ts-expect-error Should fail to transpile. + outerArr: null, + }, + {merge: true}, + ); + + // Check nested fields. + await ref.set( + { + nested: { + innerNested: { + // @ts-expect-error Should fail to transpile. + innerNestedNum: 'string', + }, + // @ts-expect-error Should fail to transpile. + innerArr: null, + }, + }, + {merge: true}, + ); + await ref.set( + { + // @ts-expect-error Should fail to transpile. + nested: 3, + }, + {merge: true}, + ); + }); + + it('checks for nonexistent properties', async () => { + const ref = doc.withConverter(testConverterMerge); + // Top-level property. + await ref.set( + { + // @ts-expect-error Should fail to transpile. + nonexistent: 'foo', + }, + {merge: true}, + ); + + // Nested property + await ref.set( + { + nested: { + // @ts-expect-error Should fail to transpile. + nonexistent: 'foo', + }, + }, + {merge: true}, + ); + }); + + it('allows omitting fields', async () => { + const ref = doc.withConverter(testConverterMerge); + // Omit outer fields. + await ref.set( + { + outerString: '', + nested: { + innerNested: { + innerNestedNum: FieldValue.increment(1), + }, + innerArr: FieldValue.arrayUnion(2), + timestamp: FieldValue.serverTimestamp(), + }, + }, + {merge: true}, + ); + + // Omit inner fields + await ref.set( + { + outerString: '', + outerArr: [], + nested: { + innerNested: { + innerNestedNum: FieldValue.increment(1), + }, + timestamp: FieldValue.serverTimestamp(), + }, + }, + {merge: true}, + ); + }); + }); + + describe('NestedPartial', () => { + const testConverterMerge = { + toFirestore( + testObj: PartialWithFieldValue, + options?: SetOptions, + ) { + if (options) { + expect(testObj).to.not.be.an.instanceOf(TestObject); + } else { + expect(testObj).to.be.an.instanceOf(TestObject); + } + return {...testObj}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): TestObject { + const data = snapshot.data(); + return new TestObject(data.outerString, data.outerArr, data.nested); + }, + }; + + it('supports FieldValues', async () => { + const ref = doc.withConverter(testConverterMerge); + + // Allow Field Values in nested partials. + await ref.set( + { + outerString: FieldValue.delete(), + nested: { + innerNested: { + innerNestedNum: FieldValue.increment(1), + }, + innerArr: FieldValue.arrayUnion(2), + timestamp: FieldValue.serverTimestamp(), + }, + }, + {merge: true}, + ); + + // Allow setting FieldValue on entire object field. + await ref.set( + { + nested: FieldValue.delete(), + }, + {merge: true}, + ); + }); + + it('validates types in outer and inner fields', async () => { + const ref = doc.withConverter(testConverterMerge); + + // Check top-level fields. + await ref.set( + { + // @ts-expect-error Should fail to transpile. + outerString: 3, + // @ts-expect-error Should fail to transpile. + outerArr: null, + }, + {merge: true}, + ); + + // Check nested fields. + await ref.set( + { + nested: { + innerNested: { + // @ts-expect-error Should fail to transpile. + innerNestedNum: 'string', + }, + // @ts-expect-error Should fail to transpile. + innerArr: null, + }, + }, + {merge: true}, + ); + await ref.set( + { + // @ts-expect-error Should fail to transpile. + nested: 3, + }, + {merge: true}, + ); + }); + + it('checks for nonexistent properties', async () => { + const ref = doc.withConverter(testConverterMerge); + // Top-level property. + await ref.set( + { + // @ts-expect-error Should fail to transpile. + nonexistent: 'foo', + }, + {merge: true}, + ); + + // Nested property + await ref.set( + { + nested: { + // @ts-expect-error Should fail to transpile. + nonexistent: 'foo', + }, + }, + {merge: true}, + ); + }); + }); + + describe('WithFieldValue', () => { + it('supports FieldValues', async () => { + const ref = doc.withConverter(testConverter); + + // Allow Field Values and nested partials. + await ref.set({ + outerString: 'foo', + outerArr: [], + nested: { + innerNested: { + innerNestedNum: FieldValue.increment(1), + }, + innerArr: FieldValue.arrayUnion(2), + timestamp: FieldValue.serverTimestamp(), + }, + }); + }); + + it('requires all outer fields to be present', async () => { + const ref = doc.withConverter(testConverter); + + // @ts-expect-error Should fail to transpile. + await ref.set({ + outerArr: [], + nested: { + innerNested: { + innerNestedNum: FieldValue.increment(1), + }, + innerArr: FieldValue.arrayUnion(2), + timestamp: FieldValue.serverTimestamp(), + }, + }); + }); + + it('requires all inner fields to be present', async () => { + const ref = doc.withConverter(testConverter); + + await ref.set({ + outerString: '', + outerArr: [], + // @ts-expect-error Should fail to transpile. + nested: { + innerNested: { + innerNestedNum: FieldValue.increment(1), + }, + timestamp: FieldValue.serverTimestamp(), + }, + }); + }); + + it('validates inner and outer fields', async () => { + const ref = doc.withConverter(testConverter); + + await ref.set({ + outerString: 'foo', + // @ts-expect-error Should fail to transpile. + outerArr: 2, + nested: { + innerNested: { + // @ts-expect-error Should fail to transpile. + innerNestedNum: 'string', + }, + innerArr: FieldValue.arrayUnion(2), + timestamp: FieldValue.serverTimestamp(), + }, + }); + }); + + it('checks for nonexistent properties', async () => { + const ref = doc.withConverter(testConverter); + + // Top-level nonexistent fields should error + await ref.set({ + outerString: 'foo', + // @ts-expect-error Should fail to transpile. + outerNum: 3, + outerArr: [], + nested: { + innerNested: { + innerNestedNum: 2, + }, + innerArr: FieldValue.arrayUnion(2), + timestamp: FieldValue.serverTimestamp(), + }, + }); + + // Nested nonexistent fields should error + await ref.set({ + outerString: 'foo', + outerNum: 3, + outerArr: [], + nested: { + innerNested: { + // @ts-expect-error Should fail to transpile. + nonexistent: 'string', + innerNestedNum: 2, + }, + innerArr: FieldValue.arrayUnion(2), + timestamp: FieldValue.serverTimestamp(), + }, + }); + }); + + it('allows certain types for not others', async () => { + const withTryCatch = async ( + fn: () => Promise, + ): Promise => { + try { + await fn(); + } catch { + // This is expected. + } + }; + + // These tests exist to establish which object types are allowed to be + // passed in by default when `T = DocumentData`. Some objects extend + // the Javascript `{}`, which is why they're allowed whereas others + // throw an error. + // @ts-expect-error This should fail to transpile. + await withTryCatch(() => doc.set(1)); + // @ts-expect-error This should fail to transpile. + await withTryCatch(() => doc.set('foo')); + // @ts-expect-error This should fail to transpile. + await withTryCatch(() => doc.set(false)); + // @ts-expect-error This should fail to transpile. + await withTryCatch(() => doc.set(undefined)); + // @ts-expect-error This should fail to transpile. + await withTryCatch(() => doc.set(null)); + await withTryCatch(() => doc.set([0])); + await withTryCatch(() => doc.set(new Set())); + await withTryCatch(() => doc.set(new Map())); + }); + + describe('used as a type', () => { + class ObjectWrapper { + withFieldValueT(value: WithFieldValue): WithFieldValue { + return value; + } + + withPartialFieldValueT( + value: PartialWithFieldValue, + ): PartialWithFieldValue { + return value; + } + + // Wrapper to avoid having Firebase types in non-Firebase code. + withT(value: T): void { + this.withFieldValueT(value); + } + + // Wrapper to avoid having Firebase types in non-Firebase code. + withPartialT(value: Partial): void { + this.withPartialFieldValueT(value); + } + } + + it('supports passing in the object as `T`', () => { + interface Foo { + id: string; + foo: number; + } + + const foo = new ObjectWrapper(); + foo.withFieldValueT({id: '', foo: FieldValue.increment(1)}); + foo.withPartialFieldValueT({foo: FieldValue.increment(1)}); + foo.withT({id: '', foo: 1}); + foo.withPartialT({foo: 1}); + }); + + it('does not allow primitive types to use FieldValue', () => { + type Bar = number; + const bar = new ObjectWrapper(); + // @ts-expect-error This should fail to transpile. + bar.withFieldValueT(FieldValue.increment(1)); + // @ts-expect-error This should fail to transpile. + bar.withPartialFieldValueT(FieldValue.increment(1)); + }); + }); + }); + + describe('UpdateData', () => { + it('supports FieldValues', async () => { + const ref = doc.withConverter(testConverter); + await ref.update({ + outerString: FieldValue.delete(), + nested: { + innerNested: { + innerNestedNum: FieldValue.increment(2), + }, + innerArr: FieldValue.arrayUnion(3), + }, + }); + }); + + it('validates inner and outer fields', async () => { + const ref = doc.withConverter(testConverter); + await ref.update({ + // @ts-expect-error Should fail to transpile. + outerString: 3, + nested: { + innerNested: { + // @ts-expect-error Should fail to transpile. + innerNestedNum: 'string', + }, + // @ts-expect-error Should fail to transpile. + innerArr: 2, + }, + }); + }); + + it('supports string-separated fields', async () => { + const ref = doc.withConverter(testConverter); + await ref.update({ + // @ts-expect-error Should fail to transpile. + outerString: 3, + // @ts-expect-error Should fail to transpile. + 'nested.innerNested.innerNestedNum': 'string', + // @ts-expect-error Should fail to transpile. + 'nested.innerArr': 3, + 'nested.timestamp': FieldValue.serverTimestamp(), + }); + + // String comprehension works in nested fields. + await ref.update({ + nested: { + innerNested: { + // @ts-expect-error Should fail to transpile. + innerNestedNum: 'string', + }, + // @ts-expect-error Should fail to transpile. + innerArr: 3, + }, + }); + }); + + it('supports optional fields', async () => { + interface TestObjectOptional { + optionalStr?: string; + nested?: { + requiredStr: string; + }; + } + + const testConverterOptional = { + toFirestore(testObj: WithFieldValue) { + return {...testObj}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): TestObjectOptional { + const data = snapshot.data(); + return { + optionalStr: data.optionalStr, + nested: data.nested, + }; + }, + }; + + const ref = doc.withConverter(testConverterOptional); + + await ref.update({ + optionalStr: 'foo', + }); + await ref.update({ + optionalStr: 'foo', + }); + + await ref.update({ + nested: { + requiredStr: 'foo', + }, + }); + await ref.update({ + 'nested.requiredStr': 'foo', + }); + }); + + it('supports null fields', async () => { + interface TestObjectOptional { + optionalStr?: string; + nested?: { + strOrNull: string | null; + }; + } + + const testConverterOptional = { + toFirestore(testObj: WithFieldValue) { + return {...testObj}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): TestObjectOptional { + const data = snapshot.data(); + return { + optionalStr: data.optionalStr, + nested: data.nested, + }; + }, + }; + const ref = doc.withConverter(testConverterOptional); + + await ref.update({ + nested: { + strOrNull: null, + }, + }); + await ref.update({ + 'nested.strOrNull': null, + }); + }); + + it('supports union fields', async () => { + interface TestObjectUnion { + optionalStr?: string; + nested?: + | { + requiredStr: string; + } + | {requiredNumber: number}; + } + + const testConverterUnion = { + toFirestore(testObj: WithFieldValue) { + return {...testObj}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): TestObjectUnion { + const data = snapshot.data(); + return { + optionalStr: data.optionalStr, + nested: data.nested, + }; + }, + }; + + const ref = doc.withConverter(testConverterUnion); + + await ref.update({ + nested: { + requiredStr: 'foo', + }, + }); + + await ref.update({ + 'nested.requiredStr': 'foo', + }); + await ref.update({ + // @ts-expect-error Should fail to transpile. + 'nested.requiredStr': 1, + }); + + await ref.update({ + 'nested.requiredNumber': 1, + }); + + await ref.update({ + // @ts-expect-error Should fail to transpile. + 'nested.requiredNumber': 'foo', + }); + await ref.update({ + // @ts-expect-error Should fail to transpile. + 'nested.requiredNumber': null, + }); + }); + + it('checks for nonexistent fields', async () => { + const ref = doc.withConverter(testConverter); + + // Top-level fields. + await ref.update({ + // @ts-expect-error Should fail to transpile. + nonexistent: 'foo', + }); + + // Nested Fields. + await ref.update({ + nested: { + // @ts-expect-error Should fail to transpile. + nonexistent: 'foo', + }, + }); + + // String fields. + await ref.update({ + // @ts-expect-error Should fail to transpile. + nonexistent: 'foo', + }); + await ref.update({ + // @ts-expect-error Should fail to transpile. + 'nested.nonexistent': 'foo', + }); + }); + }); + + describe('methods', () => { + it('CollectionReference.add()', async () => { + const ref = randomCol.withConverter(testConverter); + + // Requires all fields to be present + // @ts-expect-error Should fail to transpile. + await ref.add({ + outerArr: [], + nested: { + innerNested: { + innerNestedNum: 2, + }, + innerArr: [], + timestamp: FieldValue.serverTimestamp(), + }, + }); + }); + + it('WriteBatch.set()', () => { + const ref = doc.withConverter(testConverter); + const batch = firestore.batch(); + + // Requires full object if {merge: true} is not set. + // @ts-expect-error Should fail to transpile. + batch.set(ref, { + outerArr: [], + nested: { + innerNested: { + innerNestedNum: FieldValue.increment(1), + }, + innerArr: FieldValue.arrayUnion(2), + timestamp: FieldValue.serverTimestamp(), + }, + }); + + batch.set( + ref, + { + outerArr: [], + nested: { + innerNested: { + innerNestedNum: FieldValue.increment(1), + }, + innerArr: FieldValue.arrayUnion(2), + timestamp: FieldValue.serverTimestamp(), + }, + }, + {merge: true}, + ); + }); + + it('WriteBatch.update()', () => { + const ref = doc.withConverter(testConverter); + const batch = firestore.batch(); + + batch.update(ref, { + outerArr: [], + nested: { + 'innerNested.innerNestedNum': FieldValue.increment(1), + innerArr: FieldValue.arrayUnion(2), + timestamp: FieldValue.serverTimestamp(), + }, + }); + }); + + it('Transaction.set()', async () => { + const ref = doc.withConverter(testConverter); + + return firestore.runTransaction(async tx => { + // Requires full object if {merge: true} is not set. + // @ts-expect-error Should fail to transpile. + tx.set(ref, { + outerArr: [], + nested: { + innerNested: { + innerNestedNum: FieldValue.increment(1), + }, + innerArr: FieldValue.arrayUnion(2), + timestamp: FieldValue.serverTimestamp(), + }, + }); + + tx.set( + ref, + { + outerArr: [], + nested: { + innerNested: { + innerNestedNum: FieldValue.increment(1), + }, + innerArr: FieldValue.arrayUnion(2), + timestamp: FieldValue.serverTimestamp(), + }, + }, + {merge: true}, + ); + }); + }); + + it('Transaction.update()', async () => { + const ref = doc.withConverter(testConverter); + + return firestore.runTransaction(async tx => { + tx.update(ref, { + outerArr: [], + nested: { + innerNested: { + innerNestedNum: FieldValue.increment(1), + }, + innerArr: FieldValue.arrayUnion(2), + timestamp: FieldValue.serverTimestamp(), + }, + }); + }); + }); + }); +}); diff --git a/handwritten/firestore/dev/system-test/index_test_helper.ts b/handwritten/firestore/dev/system-test/index_test_helper.ts new file mode 100644 index 00000000000..6abb7a2034f --- /dev/null +++ b/handwritten/firestore/dev/system-test/index_test_helper.ts @@ -0,0 +1,205 @@ +/*! + * Copyright 2024 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + CollectionReference, + DocumentReference, + DocumentSnapshot, + FieldPath, + Filter, + Firestore, + Query, + Timestamp, +} from '../src'; +import {autoId} from '../src/util'; + +import { + DocumentData, + QuerySnapshot, + WithFieldValue, + UpdateData, +} from '@google-cloud/firestore'; +export const INDEX_TEST_COLLECTION = 'index-test-collection'; + +/** + * This helper class is designed to facilitate integration testing of Firestore queries that + * require manually created indexes within a controlled testing environment. + * + *

Key Features: + * + *

    + *
  • Runs tests against the dedicated test collection with predefined indexes. + *
  • Automatically associates a test ID with documents for data isolation. + *
  • Utilizes TTL policy for automatic test data cleanup. + *
  • Constructs Firestore queries with test ID filters. + *
+ */ +export class IndexTestHelper { + private readonly testId: string; + private readonly TEST_ID_FIELD: string = 'testId'; + private readonly TTL_FIELD: string = 'expireAt'; + + // Creates a new instance of the CompositeIndexTestHelper class, with a unique test + // identifier for data isolation. + constructor(public readonly db: Firestore) { + this.testId = 'test-id-' + autoId(); + } + + // Runs a test with specified documents in the INDEX_TEST_COLLECTION. + async setTestDocs(docs: { + [key: string]: DocumentData; + }): Promise { + const testDocs = this.prepareTestDocuments(docs); + const collectionRef = this.db.collection(INDEX_TEST_COLLECTION); + for (const id in testDocs) { + const ref = collectionRef.doc(id); + await ref.set(testDocs[id]); + } + return collectionRef; + } + + // Runs a test with specified documents in the INDEX_TEST_COLLECTION. + async createTestDocs(docs: DocumentData[]): Promise { + // convert docsArray without IDs to a map with IDs + const docsMap = docs.reduce<{[key: string]: DocumentData}>( + (result, doc) => { + result[autoId()] = doc; + return result; + }, + {}, + ); + return this.setTestDocs(docsMap); + } + + // Runs a test on INDEX_TEST_COLLECTION. + async withTestCollection(): Promise { + const collectionRef = this.db.collection(INDEX_TEST_COLLECTION); + return collectionRef; + } + + // Hash the document key with testId. + private toHashedId(docId: string): string { + return docId + '-' + this.testId; + } + + private toHashedIds(docs: string[]): string[] { + return docs.map(docId => this.toHashedId(docId)); + } + + // Adds test-specific fields to a document, including the testId and expiration date. + addTestSpecificFieldsToDoc(doc: DocumentData): DocumentData { + return { + ...doc, + [this.TEST_ID_FIELD]: this.testId, + [this.TTL_FIELD]: new Timestamp( // Expire test data after 24 hours + Timestamp.now().seconds + 24 * 60 * 60, + Timestamp.now().nanoseconds, + ), + }; + } + + // Remove test-specific fields from a document, including the testId and expiration date. + private removeTestSpecificFieldsFromDoc(doc: DocumentData): void { + doc._document?.data?.delete(new FieldPath(this.TEST_ID_FIELD)); + doc._document?.data?.delete(new FieldPath(this.TTL_FIELD)); + } + + // Helper method to hash document keys and add test-specific fields for the provided documents. + private prepareTestDocuments(docs: {[key: string]: DocumentData}): { + [key: string]: DocumentData; + } { + const result: {[key: string]: DocumentData} = {}; + for (const key in docs) { + // eslint-disable-next-line no-prototype-builtins + if (docs.hasOwnProperty(key)) { + result[this.toHashedId(key)] = this.addTestSpecificFieldsToDoc( + docs[key], + ); + } + } + return result; + } + + // Adds a filter on test id for a query. + query(query_: Query, ...filters: Filter[]): Query { + return filters.reduce>( + (query, filter) => { + return query.where(filter); + }, + query_.where(this.TEST_ID_FIELD, '==', this.testId), + ); + } + + // Get document reference from a document key. + getDocRef( + coll: CollectionReference, + docId: string, + ): DocumentReference { + if (!docId.includes('test-id-')) { + docId = this.toHashedId(docId); + } + return coll.doc(docId); + } + + // Adds a document to a Firestore collection with test-specific fields. + addDoc( + reference: CollectionReference, + data: object, + ): Promise> { + const processedData = this.addTestSpecificFieldsToDoc( + data, + ) as WithFieldValue; + return reference.add(processedData); + } + + // Sets a document in Firestore with test-specific fields. + async setDoc( + reference: DocumentReference, + data: object, + ): Promise { + const processedData = this.addTestSpecificFieldsToDoc( + data, + ) as WithFieldValue; + await reference.set(processedData); + } + + async updateDoc( + reference: DocumentReference, + data: UpdateData, + ): Promise { + await reference.update(data); + } + + async deleteDoc(reference: DocumentReference): Promise { + await reference.delete(); + } + + // Retrieves a single document from Firestore with test-specific fields removed. + async getDoc(docRef: DocumentReference): Promise> { + const docSnapshot = await docRef.get(); + this.removeTestSpecificFieldsFromDoc(docSnapshot); + return docSnapshot; + } + + // Retrieves multiple documents from Firestore with test-specific fields removed. + async getDocs(query_: Query): Promise> { + const querySnapshot = await this.query(query_).get(); + querySnapshot.forEach(doc => { + this.removeTestSpecificFieldsFromDoc(doc); + }); + return querySnapshot; + } +} diff --git a/handwritten/firestore/dev/system-test/pipeline.ts b/handwritten/firestore/dev/system-test/pipeline.ts new file mode 100644 index 00000000000..783d8280a07 --- /dev/null +++ b/handwritten/firestore/dev/system-test/pipeline.ts @@ -0,0 +1,5451 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { + DocumentData, + DocumentReference, + Pipelines, +} from '@google-cloud/firestore'; + +import { + map, + array, + field, + ceil, + floor, + exp, + xor, + AggregateFunction, + arrayGet, + timestampToUnixMicros, + timestampToUnixSeconds, + unixMicrosToTimestamp, + timestampToUnixMillis, + timestampSubtract, + timestampAdd, + byteLength, + multiply, + sum, + maximum, + descending, + FunctionExpression, + minimum, + count, + countIf, + arrayLength, + stringContains, + charLength, + divide, + mod, + reverse, + trim, + toUpper, + toLower, + vectorLength, + exists, + isAbsent, + ifError, + isError, + substring, + documentId, + arrayContainsAll, + mapRemove, + mapMerge, + unixSecondsToTimestamp, + unixMillisToTimestamp, + add, + and, + arrayContains, + arrayContainsAny, + arrayReverse, + average, + countAll, + endsWith, + equal, + greaterThan, + like, + lessThan, + notEqual, + ascending, + not, + or, + regexContains, + regexMatch, + regexFind, + regexFindAll, + startsWith, + stringConcat, + subtract, + cosineDistance, + dotProduct, + euclideanDistance, + mapGet, + mapEntries, + mapKeys, + mapSet, + mapValues, + lessThanOrEqual, + equalAny, + notEqualAny, + logicalMinimum, + logicalMaximum, + conditional, + constant, + PipelineResult, + PipelineSnapshot, + Pipeline, + countDistinct, + pow, + rand, + round, + trunc, + collectionId, + length, + ln, + sqrt, + stringReverse, + abs, + log10, + concat, + ifAbsent, + join, + arraySum, + currentTimestamp, + arrayConcat, + type, + isType, + timestampTruncate, + split, + // TODO(new-expression): add new expression imports above this line +} from '../src/pipelines'; + +import { + Timestamp, + GeoPoint, + Filter, + FieldValue, + CollectionReference, + FieldPath, + Firestore, +} from '../src'; + +import {expect, use} from 'chai'; +import * as chaiAsPromised from 'chai-as-promised'; + +import {afterEach, describe, it} from 'mocha'; +import '../test/util/mocha_extensions'; +import {verifyInstance} from '../test/util/helpers'; +import {getTestDb, getTestRoot} from './firestore'; + +import {Firestore as InternalFirestore} from '../src'; +import {ServiceError} from 'google-gax'; + +use(chaiAsPromised); + +const timestampDeltaMS = 3000; + +describe.skipClassic('Pipeline class', () => { + let firestore: Firestore; + let randomCol: CollectionReference; + let beginDocCreation = 0; + let endDocCreation = 0; + + async function testCollectionWithDocs(docs: { + [id: string]: DocumentData; + }): Promise> { + beginDocCreation = new Date().valueOf(); + for (const id in docs) { + const ref = randomCol.doc(id); + await ref.set(docs[id]); + } + endDocCreation = new Date().valueOf(); + return randomCol; + } + + function expectResults(result: PipelineSnapshot, ...docs: string[]): void; + function expectResults( + result: PipelineSnapshot, + ...data: DocumentData[] + ): void; + function expectResults( + result: PipelineSnapshot, + ...data: DocumentData[] | string[] + ): void { + if (data.length > 0) { + if (typeof data[0] === 'string') { + const actualIds = result.results.map(result => result.id); + expect(actualIds).to.deep.equal(data); + } else { + result.results.forEach(r => { + expect(r.data()).to.deep.equal(data.shift()); + }); + } + } else { + expect(result.results.length).to.equal(data.length); + } + } + + async function setupBookDocs(): Promise> { + const bookDocs: {[id: string]: DocumentData} = { + book1: { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + embedding: FieldValue.vector([10, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + }, + book2: { + title: 'Pride and Prejudice', + author: 'Jane Austen', + genre: 'Romance', + published: 1813, + rating: 4.5, + tags: ['classic', 'social commentary', 'love'], + awards: {none: true}, + embedding: FieldValue.vector([1, 10, 1, 1, 1, 1, 1, 1, 1, 1]), + }, + book3: { + title: 'One Hundred Years of Solitude', + author: 'Gabriel García Márquez', + genre: 'Magical Realism', + published: 1967, + rating: 4.3, + tags: ['family', 'history', 'fantasy'], + awards: {nobel: true, nebula: false}, + embedding: FieldValue.vector([1, 1, 10, 1, 1, 1, 1, 1, 1, 1]), + }, + book4: { + title: 'The Lord of the Rings', + author: 'J.R.R. Tolkien', + genre: 'Fantasy', + published: 1954, + rating: 4.7, + tags: ['adventure', 'magic', 'epic'], + awards: {hugo: false, nebula: false}, + remarks: null, + cost: NaN, + embedding: FieldValue.vector([1, 1, 1, 10, 1, 1, 1, 1, 1, 1]), + }, + book5: { + title: "The Handmaid's Tale", + author: 'Margaret Atwood', + genre: 'Dystopian', + published: 1985, + rating: 4.1, + tags: ['feminism', 'totalitarianism', 'resistance'], + awards: {'arthur c. clarke': true, 'booker prize': false}, + embedding: FieldValue.vector([1, 1, 1, 1, 10, 1, 1, 1, 1, 1]), + }, + book6: { + title: 'Crime and Punishment', + author: 'Fyodor Dostoevsky', + genre: 'Psychological Thriller', + published: 1866, + rating: 4.3, + tags: ['philosophy', 'crime', 'redemption'], + awards: {none: true}, + embedding: FieldValue.vector([1, 1, 1, 1, 1, 10, 1, 1, 1, 1]), + }, + book7: { + title: 'To Kill a Mockingbird', + author: 'Harper Lee', + genre: 'Southern Gothic', + published: 1960, + rating: 4.2, + tags: ['racism', 'injustice', 'coming-of-age'], + awards: {pulitzer: true}, + embedding: FieldValue.vector([1, 1, 1, 1, 1, 1, 10, 1, 1, 1]), + }, + book8: { + title: '1984', + author: 'George Orwell', + genre: 'Dystopian', + published: 1949, + rating: 4.2, + tags: ['surveillance', 'totalitarianism', 'propaganda'], + awards: {prometheus: true}, + embedding: FieldValue.vector([1, 1, 1, 1, 1, 1, 1, 10, 1, 1]), + }, + book9: { + title: 'The Great Gatsby', + author: 'F. Scott Fitzgerald', + genre: 'Modernist', + published: 1925, + rating: 4.0, + tags: ['wealth', 'american dream', 'love'], + awards: {none: true}, + embedding: FieldValue.vector([1, 1, 1, 1, 1, 1, 1, 1, 10, 1]), + }, + book10: { + title: 'Dune', + author: 'Frank Herbert', + genre: 'Science Fiction', + published: 1965, + rating: 4.6, + tags: ['politics', 'desert', 'ecology'], + awards: {hugo: true, nebula: true}, + embedding: FieldValue.vector([1, 1, 1, 1, 1, 1, 1, 1, 1, 10]), + }, + }; + return testCollectionWithDocs(bookDocs); + } + + before(async () => { + randomCol = getTestRoot(); + await setupBookDocs(); + firestore = randomCol.firestore; + }); + + afterEach(() => verifyInstance(firestore as unknown as InternalFirestore)); + + describe('pipeline results', () => { + it('empty snapshot as expected', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(0) + .execute(); + expect(snapshot.results.length).to.equal(0); + }); + + it('full snapshot as expected', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + const snapshot = await ppl.execute(); + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9', + ); + }); + + it('result equals works', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('title')) + .limit(1); + const snapshot1 = await ppl.execute(); + const snapshot2 = await ppl.execute(); + expect(snapshot1.results.length).to.equal(1); + expect(snapshot2.results.length).to.equal(1); + expect(snapshot1.results[0].isEqual(snapshot2.results[0])).to.be.true; + }); + + it('returns execution time', async () => { + const start = new Date().valueOf(); + const pipeline = firestore.pipeline().collection(randomCol.path); + + const snapshot = await pipeline.execute(); + const end = new Date().valueOf(); + + expect(snapshot.executionTime.toDate().valueOf()).to.approximately( + (start + end) / 2, + timestampDeltaMS, + ); + }); + + it('returns execution time for an empty query', async () => { + const start = new Date().valueOf(); + const pipeline = firestore.pipeline().collection(randomCol.path).limit(0); + + const snapshot = await pipeline.execute(); + const end = new Date().valueOf(); + + expect(snapshot.results.length).to.equal(0); + + expect(snapshot.executionTime.toDate().valueOf()).to.approximately( + (start + end) / 2, + timestampDeltaMS, + ); + }); + + it('returns create and update time for each document', async () => { + const pipeline = firestore.pipeline().collection(randomCol.path); + + let snapshot = await pipeline.execute(); + expect(snapshot.results.length).to.equal(10); + snapshot.results.forEach(doc => { + expect(doc.createTime).to.not.be.null; + expect(doc.updateTime).to.not.be.null; + + expect(doc.createTime!.toDate().valueOf()).to.approximately( + (beginDocCreation + endDocCreation) / 2, + timestampDeltaMS, + ); + expect(doc.updateTime!.toDate().valueOf()).to.approximately( + (beginDocCreation + endDocCreation) / 2, + timestampDeltaMS, + ); + expect(doc.createTime?.valueOf()).to.equal(doc.updateTime?.valueOf()); + }); + + const wb = firestore.batch(); + snapshot.results.forEach(doc => { + wb.update(doc.ref!, {newField: 'value'}); + }); + await wb.commit(); + + snapshot = await pipeline.execute(); + expect(snapshot.results.length).to.equal(10); + snapshot.results.forEach(doc => { + expect(doc.createTime).to.not.be.null; + expect(doc.updateTime).to.not.be.null; + expect(doc.createTime!.toDate().valueOf()).to.be.lessThan( + doc.updateTime!.toDate().valueOf(), + ); + }); + }); + + it('returns execution time for an aggregate query', async () => { + const start = new Date().valueOf(); + const pipeline = firestore + .pipeline() + .collection(randomCol.path) + .aggregate(average('rating').as('avgRating')); + + const snapshot = await pipeline.execute(); + const end = new Date().valueOf(); + + expect(snapshot.results.length).to.equal(1); + + expect(snapshot.executionTime.toDate().valueOf()).to.approximately( + (start + end) / 2, + timestampDeltaMS, + ); + }); + + it('returns undefined create and update time for each result in an aggregate query', async () => { + const pipeline = firestore + .pipeline() + .collection(randomCol.path) + .aggregate({ + accumulators: [average('rating').as('avgRating')], + groups: ['genre'], + }); + + const snapshot = await pipeline.execute(); + + expect(snapshot.results.length).to.equal(8); + + snapshot.results.forEach(doc => { + expect(doc.updateTime).to.be.undefined; + expect(doc.createTime).to.be.undefined; + }); + }); + }); + + describe('pipeline explain', () => { + it('mode: analyze, format: text', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + + const snapshot = await ppl.execute({ + explainOptions: { + mode: 'analyze', + outputFormat: 'text', + }, + }); + + expect(snapshot.explainStats).not.to.be.undefined; + expect(snapshot.explainStats!.text.length).to.be.greaterThan(0); + expect(snapshot.explainStats!.text.charAt(0)).not.to.equal('{'); + + expect(snapshot.explainStats!.rawData.type_url).to.equal( + 'type.googleapis.com/google.protobuf.StringValue', + ); + expect(snapshot.explainStats!.rawData.value).to.not.be.null; + expect(snapshot.explainStats!.rawData.value).to.not.be.undefined; + + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9', + ); + }); + + it('mode: analyze, format: unspecified', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + const snapshot = await ppl.execute({ + explainOptions: { + mode: 'analyze', + }, + }); + expect(snapshot.explainStats).not.to.be.undefined; + expect(snapshot.explainStats!.text.length).to.be.greaterThan(0); + expect(snapshot.explainStats!.text.charAt(0)).not.to.equal('{'); + + expect(snapshot.explainStats!.rawData.type_url).to.equal( + 'type.googleapis.com/google.protobuf.StringValue', + ); + expect(snapshot.explainStats!.rawData.value).to.not.be.null; + expect(snapshot.explainStats!.rawData.value).to.not.be.undefined; + + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9', + ); + }); + + it('mode: execute, format: text', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + const snapshot = await ppl.execute({ + explainOptions: { + mode: 'execute', + outputFormat: 'text', + }, + }); + expect(snapshot.explainStats).to.be.undefined; + + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9', + ); + }); + + it('mode: unspecified, format: text', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + const snapshot = await ppl.execute({ + explainOptions: { + mode: undefined, + }, + }); + expect(snapshot.explainStats).to.be.undefined; + + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9', + ); + }); + }); + + describe('pipeline sources', () => { + it('supports CollectionReference as source', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol) + .execute(); + expect(snapshot.results.length).to.equal(10); + }); + + it('supports list of documents as source', async () => { + const collName = randomCol.id; + + const snapshot = await firestore + .pipeline() + .documents([ + `${collName}/book1`, + randomCol.doc('book2'), + randomCol.doc('book3').path, + ]) + .execute(); + expect(snapshot.results.length).to.equal(3); + }); + + it('reject CollectionReference for another DB', async () => { + const db2 = getTestDb({databaseId: 'notDefault', projectId: 'random'}); + + expect(() => { + firestore.pipeline().collection(db2.collection('foo')); + }).to.throw(/Invalid CollectionReference/); + + await db2.terminate(); + }); + + it('reject DocumentReference for another DB', async () => { + const db2 = getTestDb({databaseId: 'notDefault', projectId: 'random'}); + + expect(() => { + firestore.pipeline().documents([db2.doc('foo/bar')]); + }).to.throw(/Invalid DocumentReference/); + + await db2.terminate(); + }); + + it('supports collection group as source', async () => { + const randomSubCollectionId = Math.random().toString(16).slice(2); + const doc1 = await randomCol + .doc('book1') + .collection(randomSubCollectionId) + .add({order: 1}); + const doc2 = await randomCol + .doc('book2') + .collection(randomSubCollectionId) + .add({order: 2}); + const snapshot = await firestore + .pipeline() + .collectionGroup(randomSubCollectionId) + .sort(ascending('order')) + .execute(); + expectResults(snapshot, doc1.id, doc2.id); + }); + + it('supports database as source', async () => { + const randomId = Math.random().toString(16).slice(2); + const doc1 = await randomCol.doc('book1').collection('sub').add({ + order: 1, + randomId, + }); + const doc2 = await randomCol.doc('book2').collection('sub').add({ + order: 2, + randomId, + }); + const snapshot = await firestore + .pipeline() + .database() + .where(equal('randomId', randomId)) + .sort(ascending('order')) + .execute(); + expectResults(snapshot, doc1.id, doc2.id); + }); + }); + + describe('supported data types', () => { + it('accepts and returns all data types', async () => { + const refDate = new Date(); + const refTimestamp = Timestamp.now(); + const constants = [ + constant(1).as('number'), + constant('a string').as('string'), + constant(true).as('boolean'), + constant(null).as('null'), + constant(new GeoPoint(0.1, 0.2)).as('geoPoint'), + constant(refTimestamp).as('timestamp'), + constant(refDate).as('date'), + constant(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0])).as('bytes'), + constant(firestore.doc('foo/bar')).as('documentReference'), + constant(FieldValue.vector([1, 2, 3])).as('vectorValue'), + map({ + number: 1, + string: 'a string', + boolean: true, + null: null, + geoPoint: new GeoPoint(0.1, 0.2), + timestamp: refTimestamp, + date: refDate, + uint8Array: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), + documentReference: firestore.doc('foo/bar'), + vectorValue: FieldValue.vector([1, 2, 3]), + map: { + number: 2, + string: 'b string', + }, + array: [1, 'c string'], + }).as('map'), + array([ + 1, + 'a string', + true, + null, + new GeoPoint(0.1, 0.2), + refTimestamp, + refDate, + new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), + firestore.doc('foo/bar'), + FieldValue.vector([1, 2, 3]), + { + number: 2, + string: 'b string', + }, + ]).as('array'), + ]; + + const snapshots = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(constants[0], ...constants.slice(1)) + .execute(); + + expectResults(snapshots, { + number: 1, + string: 'a string', + boolean: true, + null: null, + geoPoint: new GeoPoint(0.1, 0.2), + timestamp: refTimestamp, + date: Timestamp.fromDate(refDate), + bytes: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), + documentReference: firestore.collection('foo').doc('bar'), + vectorValue: FieldValue.vector([1, 2, 3]), + map: { + number: 1, + string: 'a string', + boolean: true, + null: null, + geoPoint: new GeoPoint(0.1, 0.2), + timestamp: refTimestamp, + date: Timestamp.fromDate(refDate), + uint8Array: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), + documentReference: firestore.collection('foo').doc('bar'), + vectorValue: FieldValue.vector([1, 2, 3]), + map: { + number: 2, + string: 'b string', + }, + array: [1, 'c string'], + }, + array: [ + 1, + 'a string', + true, + null, + new GeoPoint(0.1, 0.2), + refTimestamp, + Timestamp.fromDate(refDate), + new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), + firestore.collection('foo').doc('bar'), + FieldValue.vector([1, 2, 3]), + { + number: 2, + string: 'b string', + }, + ], + }); + }); + + it('throws on undefined in a map', async () => { + try { + await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select( + map({ + number: 1, + bad: undefined, + }).as('foo'), + ) + .execute(); + expect.fail('The statement above was expected to throw.'); + } catch (e: unknown) { + const error = e as Error; + console.log(error.message); + expect(error.message).to.contain( + 'Value for argument "value" is not a valid map value. Cannot use "undefined" as a Firestore value (found in field "bad").', + ); + } + }); + + it('throws on undefined in an array', async () => { + try { + await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(array([1, undefined]).as('foo')) + .execute(); + expect.fail('The statement above was expected to throw.'); + } catch (e: unknown) { + const error = e as Error; + console.log(error.message); + expect(error.message).to.contain( + 'Value for argument "value" is not a valid array value. Cannot use "undefined" as a Firestore value', + ); + } + }); + + it('ignores undefined in a map if ignoreUndefinedProperties is true', async () => { + const customFirestore = getTestDb({ + ignoreUndefinedProperties: true, + }); + + const snapshot = await customFirestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select( + map({ + number: 1, + bad: undefined, + }).as('foo'), + ) + .execute(); + + const data = snapshot.results[0].data(); + expect(data).to.deep.equal({foo: {number: 1}}); + await customFirestore.terminate(); + }); + + it('ignores undefined in an array if ignoreUndefinedProperties is true', async () => { + const customFirestore = getTestDb({ + ignoreUndefinedProperties: true, + }); + + const snapshot = await customFirestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(array([1, undefined, 3]).as('foo')) + .execute(); + + const data = snapshot.results[0].data(); + expect(data).to.deep.equal({foo: [1, 3]}); + await customFirestore.terminate(); + }); + + it('converts arrays and plain objects to functionValues if the customer intent is unspecified', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + 'title', + 'author', + 'genre', + 'rating', + 'published', + 'tags', + 'awards', + ) + .addFields( + array([ + 1, + 2, + field('genre'), + multiply('rating', 10), + [field('title')], + { + published: field('published'), + }, + ]).as('metadataArray'), + map({ + genre: field('genre'), + rating: multiply('rating', 10), + nestedArray: [field('title')], + nestedMap: { + published: field('published'), + }, + }).as('metadata'), + ) + .where( + and( + equal('metadataArray', [ + 1, + 2, + field('genre'), + multiply('rating', 10), + [field('title')], + { + published: field('published'), + }, + ]), + equal('metadata', { + genre: field('genre'), + rating: multiply('rating', 10), + nestedArray: [field('title')], + nestedMap: { + published: field('published'), + }, + }), + ), + ) + .execute(); + + expect(snapshot.results.length).to.equal(1); + + expectResults(snapshot, { + title: 'The Lord of the Rings', + author: 'J.R.R. Tolkien', + genre: 'Fantasy', + published: 1954, + rating: 4.7, + tags: ['adventure', 'magic', 'epic'], + awards: {hugo: false, nebula: false}, + metadataArray: [ + 1, + 2, + 'Fantasy', + 47, + ['The Lord of the Rings'], + { + published: 1954, + }, + ], + metadata: { + genre: 'Fantasy', + rating: 47, + nestedArray: ['The Lord of the Rings'], + nestedMap: { + published: 1954, + }, + }, + }); + }); + }); + + describe('stages', () => { + describe('aggregate stage', () => { + it('supports aggregate', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate(countAll().as('count')) + .execute(); + expectResults(snapshot, {count: 10}); + + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('genre', 'Science Fiction')) + .aggregate( + countAll().as('count'), + average('rating').as('avgRating'), + maximum('rating').as('maxRating'), + sum('rating').as('sumRating'), + ) + .execute(); + expectResults(snapshot, { + count: 2, + avgRating: 4.4, + maxRating: 4.6, + sumRating: 8.8, + }); + }); + + it('throws on duplicate aliases', async () => { + expect(() => + firestore + .pipeline() + .collection(randomCol.path) + .aggregate(countAll().as('count'), count('foo').as('count')), + ).to.throw("Duplicate alias or field 'count'"); + }); + + it('throws on duplicate group aliases', async () => { + expect(() => + firestore + .pipeline() + .collection(randomCol.path) + .aggregate({ + accumulators: [countAll().as('count')], + groups: ['bax', field('bar').as('bax')], + }), + ).to.throw("Duplicate alias or field 'bax'"); + }); + + it('supports aggregate options', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate({ + accumulators: [countAll().as('count')], + }) + .execute(); + expectResults(snapshot, {count: 10}); + + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('genre', 'Science Fiction')) + .aggregate( + countAll().as('count'), + average('rating').as('avgRating'), + maximum('rating').as('maxRating'), + sum('rating').as('sumRating'), + ) + .execute(); + expectResults(snapshot, { + count: 2, + avgRating: 4.4, + maxRating: 4.6, + sumRating: 8.8, + }); + }); + + it('rejects groups without accumulators', async () => { + void expect(async () => { + await firestore + .pipeline() + .collection(randomCol.path) + .where(lessThan('published', 1900)) + .aggregate({ + accumulators: [], + groups: ['genre'], + }) + .execute(); + }).to.throw; + }); + + it('returns group and accumulate results', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(lessThan(field('published'), 1984)) + .aggregate({ + accumulators: [average('rating').as('avgRating')], + groups: ['genre'], + }) + .where(greaterThan('avgRating', 4.3)) + .sort(field('avgRating').descending()) + .execute(); + expectResults( + snapshot, + {avgRating: 4.7, genre: 'Fantasy'}, + {avgRating: 4.5, genre: 'Romance'}, + {avgRating: 4.4, genre: 'Science Fiction'}, + ); + }); + + it('returns min, max, count, and countAll accumulations', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate( + count('cost').as('booksWithCost'), + countAll().as('count'), + maximum('rating').as('maxRating'), + minimum('published').as('minPublished'), + ) + .execute(); + expectResults(snapshot, { + booksWithCost: 1, + count: 10, + maxRating: 4.7, + minPublished: 1813, + }); + }); + + it('returns countif accumulation', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate(countIf(field('rating').greaterThan(4.3)).as('count')) + .execute(); + const expectedResults = { + count: 3, + }; + expectResults(snapshot, expectedResults); + + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate(field('rating').greaterThan(4.3).countIf().as('count')) + .execute(); + expectResults(snapshot, expectedResults); + }); + + it('returns countDistinct accumulation', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate(countDistinct('genre').as('distinctGenres')) + .execute(); + expectResults(snapshot, {distinctGenres: 8}); + }); + }); + + describe('distinct stage', () => { + it('returns distinct values as expected', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .distinct('genre', 'author') + .sort(field('genre').ascending(), field('author').ascending()) + .execute(); + expectResults( + snapshot, + {genre: 'Dystopian', author: 'George Orwell'}, + {genre: 'Dystopian', author: 'Margaret Atwood'}, + {genre: 'Fantasy', author: 'J.R.R. Tolkien'}, + {genre: 'Magical Realism', author: 'Gabriel García Márquez'}, + {genre: 'Modernist', author: 'F. Scott Fitzgerald'}, + {genre: 'Psychological Thriller', author: 'Fyodor Dostoevsky'}, + {genre: 'Romance', author: 'Jane Austen'}, + {genre: 'Science Fiction', author: 'Douglas Adams'}, + {genre: 'Science Fiction', author: 'Frank Herbert'}, + {genre: 'Southern Gothic', author: 'Harper Lee'}, + ); + }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .distinct('genre', 'author') + .sort({ + orderings: [ + field('genre').ascending(), + field('author').ascending(), + ], + }) + .execute(); + expectResults( + snapshot, + {genre: 'Dystopian', author: 'George Orwell'}, + {genre: 'Dystopian', author: 'Margaret Atwood'}, + {genre: 'Fantasy', author: 'J.R.R. Tolkien'}, + {genre: 'Magical Realism', author: 'Gabriel García Márquez'}, + {genre: 'Modernist', author: 'F. Scott Fitzgerald'}, + {genre: 'Psychological Thriller', author: 'Fyodor Dostoevsky'}, + {genre: 'Romance', author: 'Jane Austen'}, + {genre: 'Science Fiction', author: 'Douglas Adams'}, + {genre: 'Science Fiction', author: 'Frank Herbert'}, + {genre: 'Southern Gothic', author: 'Harper Lee'}, + ); + }); + }); + + describe('select stage', () => { + it('can select fields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .sort(field('author').ascending()) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + }, + {title: 'The Great Gatsby', author: 'F. Scott Fitzgerald'}, + {title: 'Dune', author: 'Frank Herbert'}, + {title: 'Crime and Punishment', author: 'Fyodor Dostoevsky'}, + { + title: 'One Hundred Years of Solitude', + author: 'Gabriel García Márquez', + }, + {title: '1984', author: 'George Orwell'}, + {title: 'To Kill a Mockingbird', author: 'Harper Lee'}, + {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'}, + {title: 'Pride and Prejudice', author: 'Jane Austen'}, + {title: "The Handmaid's Tale", author: 'Margaret Atwood'}, + ); + }); + + it('throws on duplicate aliases', async () => { + expect(() => { + firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(constant(1).as('foo'), constant(2).as('foo')); + }).to.throw("Duplicate alias or field 'foo'"); + }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select({selections: ['title', field('author').as('auth0r')]}) + .sort(field('auth0r').ascending()) + .limit(2) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + auth0r: 'Douglas Adams', + }, + {title: 'The Great Gatsby', auth0r: 'F. Scott Fitzgerald'}, + ); + }); + }); + + describe('addField stage', () => { + it('can add fields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .addFields(constant('bar').as('foo')) + .sort(field('author').ascending()) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + foo: 'bar', + }, + { + title: 'The Great Gatsby', + author: 'F. Scott Fitzgerald', + foo: 'bar', + }, + {title: 'Dune', author: 'Frank Herbert', foo: 'bar'}, + { + title: 'Crime and Punishment', + author: 'Fyodor Dostoevsky', + foo: 'bar', + }, + { + title: 'One Hundred Years of Solitude', + author: 'Gabriel García Márquez', + foo: 'bar', + }, + {title: '1984', author: 'George Orwell', foo: 'bar'}, + { + title: 'To Kill a Mockingbird', + author: 'Harper Lee', + foo: 'bar', + }, + { + title: 'The Lord of the Rings', + author: 'J.R.R. Tolkien', + foo: 'bar', + }, + {title: 'Pride and Prejudice', author: 'Jane Austen', foo: 'bar'}, + { + title: "The Handmaid's Tale", + author: 'Margaret Atwood', + foo: 'bar', + }, + ); + }); + + it('throws on duplicate aliases', async () => { + expect(() => + firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .addFields(constant('bar').as('foo'), constant('baz').as('foo')) + .sort(field('author').ascending()), + ).to.throw("Duplicate alias or field 'foo'"); + }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .addFields({ + fields: [constant('bar').as('foo')], + }) + .sort(field('author').ascending()) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + foo: 'bar', + }, + { + title: 'The Great Gatsby', + author: 'F. Scott Fitzgerald', + foo: 'bar', + }, + {title: 'Dune', author: 'Frank Herbert', foo: 'bar'}, + { + title: 'Crime and Punishment', + author: 'Fyodor Dostoevsky', + foo: 'bar', + }, + { + title: 'One Hundred Years of Solitude', + author: 'Gabriel García Márquez', + foo: 'bar', + }, + {title: '1984', author: 'George Orwell', foo: 'bar'}, + { + title: 'To Kill a Mockingbird', + author: 'Harper Lee', + foo: 'bar', + }, + { + title: 'The Lord of the Rings', + author: 'J.R.R. Tolkien', + foo: 'bar', + }, + {title: 'Pride and Prejudice', author: 'Jane Austen', foo: 'bar'}, + { + title: "The Handmaid's Tale", + author: 'Margaret Atwood', + foo: 'bar', + }, + ); + }); + }); + + describe('removeFields stage', () => { + it('can remove fields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .sort(field('author').ascending()) + .removeFields(field('author')) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + title: 'The Great Gatsby', + }, + {title: 'Dune'}, + { + title: 'Crime and Punishment', + }, + { + title: 'One Hundred Years of Solitude', + }, + {title: '1984'}, + { + title: 'To Kill a Mockingbird', + }, + { + title: 'The Lord of the Rings', + }, + {title: 'Pride and Prejudice'}, + { + title: "The Handmaid's Tale", + }, + ); + }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author', 'genre') + .sort(field('author').ascending()) + .removeFields({ + fields: [field('author'), 'genre'], + }) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + title: 'The Great Gatsby', + }, + {title: 'Dune'}, + { + title: 'Crime and Punishment', + }, + { + title: 'One Hundred Years of Solitude', + }, + {title: '1984'}, + { + title: 'To Kill a Mockingbird', + }, + { + title: 'The Lord of the Rings', + }, + {title: 'Pride and Prejudice'}, + { + title: "The Handmaid's Tale", + }, + ); + }); + }); + + describe('findNearest stage', () => { + it('can find nearest', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .sort(field('author').ascending()) + .removeFields(field('author')) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + title: 'The Great Gatsby', + }, + {title: 'Dune'}, + { + title: 'Crime and Punishment', + }, + { + title: 'One Hundred Years of Solitude', + }, + {title: '1984'}, + { + title: 'To Kill a Mockingbird', + }, + { + title: 'The Lord of the Rings', + }, + {title: 'Pride and Prejudice'}, + { + title: "The Handmaid's Tale", + }, + ); + }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author', 'genre') + .sort(field('author').ascending()) + .removeFields({ + fields: [field('author'), 'genre'], + }) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + title: 'The Great Gatsby', + }, + {title: 'Dune'}, + { + title: 'Crime and Punishment', + }, + { + title: 'One Hundred Years of Solitude', + }, + {title: '1984'}, + { + title: 'To Kill a Mockingbird', + }, + { + title: 'The Lord of the Rings', + }, + {title: 'Pride and Prejudice'}, + { + title: "The Handmaid's Tale", + }, + ); + }); + }); + + describe('where stage', () => { + it('where with and (2 conditions)', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + and( + greaterThan('rating', 4.5), + equalAny('genre', ['Science Fiction', 'Romance', 'Fantasy']), + ), + ) + .execute(); + expectResults(snapshot, 'book10', 'book4'); + }); + + it('where with and (3 conditions)', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + and( + greaterThan('rating', 4.5), + equalAny('genre', ['Science Fiction', 'Romance', 'Fantasy']), + lessThan('published', 1965), + ), + ) + .execute(); + expectResults(snapshot, 'book4'); + }); + + it('where with or', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + or( + equal('genre', 'Romance'), + equal('genre', 'Dystopian'), + equal('genre', 'Fantasy'), + ), + ) + .sort(ascending('title')) + .select('title') + .execute(); + expectResults( + snapshot, + {title: '1984'}, + {title: 'Pride and Prejudice'}, + {title: "The Handmaid's Tale"}, + {title: 'The Lord of the Rings'}, + ); + }); + + it('where with xor', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + xor( + equal('genre', 'Romance'), + equal('genre', 'Dystopian'), + equal('genre', 'Fantasy'), + equal('published', 1949), + ), + ) + .select('title') + .execute(); + expectResults( + snapshot, + {title: 'Pride and Prejudice'}, + {title: 'The Lord of the Rings'}, + {title: "The Handmaid's Tale"}, + ); + }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where({ + condition: and( + greaterThan('rating', 4.5), + equalAny('genre', ['Science Fiction', 'Romance', 'Fantasy']), + ), + }) + .execute(); + expectResults(snapshot, 'book10', 'book4'); + }); + }); + + describe('sort, offset, and limit stages', () => { + it('supports sort, offset, and limits', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('author').ascending()) + .offset(5) + .limit(3) + .select('title', 'author') + .execute(); + expectResults( + snapshot, + {title: '1984', author: 'George Orwell'}, + {title: 'To Kill a Mockingbird', author: 'Harper Lee'}, + {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'}, + ); + }); + + it('sort, offset, and limit stages support options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort({ + orderings: [field('author').ascending()], + }) + .offset({offset: 5}) + .limit({limit: 3}) + .select('title', 'author') + .execute(); + expectResults( + snapshot, + {title: '1984', author: 'George Orwell'}, + {title: 'To Kill a Mockingbird', author: 'Harper Lee'}, + {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'}, + ); + }); + }); + + describe('error handling', () => { + it('error properties are propagated from the firestore backend', async () => { + try { + await firestore + .pipeline() + .collection(randomCol.path) + .rawStage('select', [ + // incorrect parameter type + field('title'), + ]) + .execute(); + + expect.fail('expected pipeline.execute() to throw'); + } catch (e: unknown) { + expect(e instanceof Error).to.be.true; + const err = e as ServiceError; + expect(err['code']).to.equal(3); + expect(typeof err['message']).to.equal('string'); + expect(typeof err['details']).to.equal('string'); + expect(typeof err['stack']).to.equal('string'); + expect(err['metadata'] instanceof Object).to.be.true; + + expect(err['message']).to.equal( + `${err.code} INVALID_ARGUMENT: ${err.details}`, + ); + } + }); + + it('can access explain stats in error condition', async () => { + try { + await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').ascending()) + .execute({ + explainOptions: { + mode: 'analyze', + }, + rawOptions: { + memory_limit: 1, + }, + }); + + expect.fail('expected pipeline.execute() to throw'); + } catch (e: unknown) { + const err = e as {[k: string]: unknown}; + expect(err instanceof Error).to.be.true; + + expect(err['code']).to.equal(8); + expect(typeof err['message']).to.equal('string'); + expect(typeof err['details']).to.equal('string'); + expect(typeof err['stack']).to.equal('string'); + expect(err['metadata'] instanceof Object).to.be.true; + + expect(err['message']).to.equal( + `${err.code} RESOURCE_EXHAUSTED: ${err.details}`, + ); + + expect('statusDetails' in err).to.be.true; + expect(Array.isArray(err['statusDetails'])).to.be.true; + + const statusDetails = err['statusDetails'] as Array; + + const foundExplainStats = statusDetails.find(x => { + return ( + 'type_url' in x && + x['type_url'] === + 'type.googleapis.com/google.firestore.v1.ExplainStats' + ); + }); + expect(foundExplainStats).to.not.be.undefined; + } + }); + }); + + describe('raw stage', () => { + it('can select fields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .rawStage('select', [ + { + title: field('title'), + metadata: { + author: field('author'), + }, + }, + ]) + .sort(field('author').ascending()) + .limit(1) + .execute(); + expectResults(snapshot, { + metadata: { + author: 'Frank Herbert', + }, + title: 'Dune', + }); + }); + + it('can add fields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('author').ascending()) + .limit(1) + .select('title', 'author') + .rawStage('add_fields', [ + { + display: stringConcat('title', ' - ', field('author')), + }, + ]) + .execute(); + expectResults(snapshot, { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + display: "The Hitchhiker's Guide to the Galaxy - Douglas Adams", + }); + }); + + it('can filter with where', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .rawStage('where', [field('author').equal('Douglas Adams')]) + .execute(); + expectResults(snapshot, { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + }); + }); + + it('can limit, offset, and sort', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .rawStage('sort', [ + { + direction: 'ascending', + expression: field('author'), + }, + ]) + .rawStage('offset', [3]) + .rawStage('limit', [1]) + .execute(); + expectResults(snapshot, { + author: 'Fyodor Dostoevsky', + title: 'Crime and Punishment', + }); + }); + + it('can perform aggregate query', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author', 'rating') + .rawStage('aggregate', [ + {averageRating: field('rating').average()}, + {}, + ]) + .execute(); + expectResults(snapshot, { + averageRating: 4.3100000000000005, + }); + }); + + it('can perform distinct query', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author', 'rating') + .rawStage('distinct', [{rating: field('rating')}]) + .sort(field('rating').descending()) + .execute(); + expectResults( + snapshot, + { + rating: 4.7, + }, + { + rating: 4.6, + }, + { + rating: 4.5, + }, + { + rating: 4.3, + }, + { + rating: 4.2, + }, + { + rating: 4.1, + }, + { + rating: 4.0, + }, + ); + }); + + it('can perform FindNearest query', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol) + .rawStage( + 'find_nearest', + [ + field('embedding'), + FieldValue.vector([10, 1, 2, 1, 1, 1, 1, 1, 1, 1]), + 'euclidean', + ], + { + distance_field: field('computedDistance'), + limit: 2, + }, + ) + .select('title', 'computedDistance') + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + computedDistance: 1, + }, + { + title: 'One Hundred Years of Solitude', + computedDistance: 12.041594578792296, + }, + ); + }); + }); + + describe('replaceWith stage', () => { + it('run pipeline with replaceWith field name', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) + .replaceWith('awards') + .execute(); + expectResults(snapshot, { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }); + }); + + it('run pipeline with replaceWith Expression result', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) + .replaceWith( + map({ + foo: 'bar', + baz: { + title: field('title'), + }, + }), + ) + .execute(); + expectResults(snapshot, { + foo: 'bar', + baz: {title: "The Hitchhiker's Guide to the Galaxy"}, + }); + }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) + .replaceWith({map: 'awards'}) + .execute(); + expectResults(snapshot, { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }); + }); + }); + + describe('sample stage', () => { + it('run pipeline with sample limit of 3', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sample(3) + .execute(); + expect(snapshot.results.length).to.equal(3); + }); + + it('run pipeline with sample limit of {documents: 3}', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sample({documents: 3}) + .execute(); + expect(snapshot.results.length).to.equal(3); + }); + + it('run pipeline with sample limit of {percentage: 0.6}', async () => { + let avgSize = 0; + const numIterations = 30; + for (let i = 0; i < numIterations; i++) { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sample({percentage: 0.6}) + .execute(); + + avgSize += snapshot.results.length; + } + avgSize /= numIterations; + expect(avgSize).to.be.closeTo(6, 1); + }); + }); + + describe('union stage', () => { + it('run pipeline with union', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .union(firestore.pipeline().collection(randomCol.path)) + .sort(field(FieldPath.documentId()).ascending()) + .execute(); + expectResults( + snapshot, + 'book1', + 'book1', + 'book10', + 'book10', + 'book2', + 'book2', + 'book3', + 'book3', + 'book4', + 'book4', + 'book5', + 'book5', + 'book6', + 'book6', + 'book7', + 'book7', + 'book8', + 'book8', + 'book9', + 'book9', + ); + }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .union({other: firestore.pipeline().collection(randomCol.path)}) + .sort(field(FieldPath.documentId()).ascending()) + .execute(); + expectResults( + snapshot, + 'book1', + 'book1', + 'book10', + 'book10', + 'book2', + 'book2', + 'book3', + 'book3', + 'book4', + 'book4', + 'book5', + 'book5', + 'book6', + 'book6', + 'book7', + 'book7', + 'book8', + 'book8', + 'book9', + 'book9', + ); + }); + }); + + describe('unnest stage', () => { + it('run pipeline with unnest', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) + .unnest(field('tags').as('tag')) + .select( + 'title', + 'author', + 'genre', + 'published', + 'rating', + 'tags', + 'tag', + 'awards', + 'nestedField', + ) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'comedy', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'space', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'adventure', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + }, + ); + }); + + it('unnest with index field', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) + .unnest(field('tags').as('tag'), 'tagsIndex') + .select( + 'title', + 'author', + 'genre', + 'published', + 'rating', + 'tags', + 'tag', + 'awards', + 'nestedField', + 'tagsIndex', + ) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'comedy', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 0, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'space', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 1, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'adventure', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 2, + }, + ); + }); + + it('unnest an expr', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) + .unnest(array([1, 2, 3]).as('copy')) + .select( + 'title', + 'author', + 'genre', + 'published', + 'rating', + 'tags', + 'copy', + 'awards', + 'nestedField', + ) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + copy: 1, + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + copy: 2, + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + copy: 3, + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + }, + ); + }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) + .unnest({ + selectable: field('tags').as('tag'), + indexField: 'tagsIndex', + }) + .select( + 'title', + 'author', + 'genre', + 'published', + 'rating', + 'tags', + 'tag', + 'awards', + 'nestedField', + 'tagsIndex', + ) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'comedy', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 0, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'space', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 1, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'adventure', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 2, + }, + ); + }); + }); + + describe('findNearest stage', () => { + it('run pipeline with findNearest', async () => { + const measures: Array< + Pipelines.FindNearestStageOptions['distanceMeasure'] + > = ['euclidean', 'dot_product', 'cosine']; + for (const measure of measures) { + const snapshot = await firestore + .pipeline() + .collection(randomCol) + .findNearest({ + field: 'embedding', + vectorValue: FieldValue.vector([10, 1, 3, 1, 2, 1, 1, 1, 1, 1]), + limit: 3, + distanceMeasure: measure, + }) + .select('title') + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + title: 'One Hundred Years of Solitude', + }, + { + title: "The Handmaid's Tale", + }, + ); + } + }); + + it('optionally returns the computed distance', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol) + .findNearest({ + field: 'embedding', + vectorValue: FieldValue.vector([10, 1, 2, 1, 1, 1, 1, 1, 1, 1]), + limit: 2, + distanceMeasure: 'euclidean', + distanceField: 'computedDistance', + }) + .select('title', 'computedDistance') + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + computedDistance: 1, + }, + { + title: 'One Hundred Years of Solitude', + computedDistance: 12.041594578792296, + }, + ); + }); + }); + }); + + describe('function expressions', () => { + it('logical max works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select( + 'title', + logicalMaximum(constant(1960), field('published'), 1961).as( + 'published-safe', + ), + ) + .sort(field('title').ascending()) + .limit(3) + .execute(); + expectResults( + snapshot, + {title: '1984', 'published-safe': 1961}, + {title: 'Crime and Punishment', 'published-safe': 1961}, + {title: 'Dune', 'published-safe': 1965}, + ); + }); + + it('logical min works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select( + 'title', + logicalMinimum(constant(1960), field('published'), 1961).as( + 'published-safe', + ), + ) + .sort(field('title').ascending()) + .limit(3) + .execute(); + expectResults( + snapshot, + {title: '1984', 'published-safe': 1949}, + {title: 'Crime and Punishment', 'published-safe': 1866}, + {title: 'Dune', 'published-safe': 1960}, + ); + }); + + it('conditional works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select( + 'title', + conditional( + lessThan(field('published'), 1960), + constant(1960), + field('published'), + ).as('published-safe'), + field('rating') + .greaterThanOrEqual(4.5) + .conditional(constant('great'), constant('good')) + .as('rating'), + ) + .sort(field('title').ascending()) + .limit(3) + .execute(); + expectResults( + snapshot, + {title: '1984', 'published-safe': 1960, rating: 'good'}, + { + title: 'Crime and Punishment', + 'published-safe': 1960, + rating: 'good', + }, + {title: 'Dune', 'published-safe': 1965, rating: 'great'}, + ); + }); + + it('equalAny works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equalAny('published', [1979, 1999, 1967])) + .sort(descending('title')) + .select('title') + .execute(); + expectResults( + snapshot, + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'One Hundred Years of Solitude'}, + ); + }); + + it('notEqualAny works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + notEqualAny( + 'published', + [1965, 1925, 1949, 1960, 1866, 1985, 1954, 1967, 1979], + ), + ) + .select('title') + .execute(); + expectResults(snapshot, {title: 'Pride and Prejudice'}); + }); + + it('arrayContains works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(arrayContains('tags', 'comedy')) + .select('title') + .execute(); + expectResults(snapshot, { + title: "The Hitchhiker's Guide to the Galaxy", + }); + }); + + it('arrayContainsAny works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(arrayContainsAny('tags', ['comedy', 'classic'])) + .sort(descending('title')) + .select('title') + .execute(); + expectResults( + snapshot, + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'Pride and Prejudice'}, + ); + }); + + it('arrayContainsAll works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(arrayContainsAll('tags', ['adventure', 'magic'])) + .select('title') + .execute(); + expectResults(snapshot, {title: 'The Lord of the Rings'}); + }); + + it('arrayLength works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select(arrayLength('tags').as('tagsCount')) + .where(equal('tagsCount', 3)) + .execute(); + expect(snapshot.results.length).to.equal(10); + }); + + it('testStrConcat', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('author')) + .select( + field('author').stringConcat(' - ', field('title')).as('bookInfo'), + ) + .limit(1) + .execute(); + expectResults(snapshot, { + bookInfo: "Douglas Adams - The Hitchhiker's Guide to the Galaxy", + }); + }); + + it('testStartsWith', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(startsWith('title', 'The')) + .select('title') + .sort(field('title').ascending()) + .execute(); + expectResults( + snapshot, + {title: 'The Great Gatsby'}, + {title: "The Handmaid's Tale"}, + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'The Lord of the Rings'}, + ); + }); + + it('testEndsWith', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(endsWith('title', 'y')) + .select('title') + .sort(field('title').descending()) + .execute(); + expectResults( + snapshot, + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'The Great Gatsby'}, + ); + }); + + it('testStrContains', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(stringContains('title', "'s")) + .select('title') + .sort(field('title').ascending()) + .execute(); + expectResults( + snapshot, + {title: "The Handmaid's Tale"}, + {title: "The Hitchhiker's Guide to the Galaxy"}, + ); + }); + + it('testLength', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select(charLength('title').as('titleLength'), field('title')) + .where(greaterThan('titleLength', 20)) + .sort(field('title').ascending()) + .execute(); + + expectResults( + snapshot, + + { + titleLength: 29, + title: 'One Hundred Years of Solitude', + }, + { + titleLength: 36, + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + titleLength: 21, + title: 'The Lord of the Rings', + }, + { + titleLength: 21, + title: 'To Kill a Mockingbird', + }, + ); + }); + + it('testLike', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(like('title', '%Guide%')) + .select('title') + .execute(); + expectResults(snapshot, { + title: "The Hitchhiker's Guide to the Galaxy", + }); + }); + + it('testRegexContains', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(regexContains('title', '(?i)(the|of)')) + .execute(); + expect(snapshot.results.length).to.equal(5); + }); + + it('testRegexFind', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select(regexFind('title', '^\\w+').as('firstWordInTitle')) + .select('firstWordInTitle') + .sort(field('firstWordInTitle').ascending()) + .limit(3) + .execute(); + expectResults( + snapshot, + {firstWordInTitle: '1984'}, + {firstWordInTitle: 'Crime'}, + {firstWordInTitle: 'Dune'}, + ); + }); + + it('testRegexFindAll', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select(regexFindAll('title', '\\w+').as('wordsInTitle')) + .select('wordsInTitle') + .sort(field('wordsInTitle').ascending()) + .limit(3) + .execute(); + expectResults( + snapshot, + {wordsInTitle: ['1984']}, + {wordsInTitle: ['Crime', 'and', 'Punishment']}, + {wordsInTitle: ['Dune']}, + ); + }); + + it('testRegexMatches', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(regexMatch('title', '.*(?i)(the|of).*')) + .execute(); + expect(snapshot.results.length).to.equal(5); + }); + + it('testArithmeticOperations', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('title', 'To Kill a Mockingbird')) + .select( + add(field('rating'), 1).as('ratingPlusOne'), + subtract(field('published'), 1900).as('yearsSince1900'), + field('rating').multiply(10).as('ratingTimesTen'), + divide('rating', 2).as('ratingDividedByTwo'), + multiply('rating', 20).as('ratingTimes20'), + add('rating', 3).as('ratingPlus3'), + mod('rating', 2).as('ratingMod2'), + ) + .limit(1) + .execute(); + expectResults(snapshot, { + ratingPlusOne: 5.2, + yearsSince1900: 60, + ratingTimesTen: 42, + ratingDividedByTwo: 2.1, + ratingTimes20: 84, + ratingPlus3: 7.2, + ratingMod2: 0.20000000000000018, + }); + }); + + it('testComparisonOperators', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + and( + greaterThan('rating', 4.2), + lessThanOrEqual(field('rating'), 4.5), + notEqual('genre', 'Science Fiction'), + ), + ) + .select('rating', 'title') + .sort(field('title').ascending()) + .execute(); + expectResults( + snapshot, + {rating: 4.3, title: 'Crime and Punishment'}, + { + rating: 4.3, + title: 'One Hundred Years of Solitude', + }, + {rating: 4.5, title: 'Pride and Prejudice'}, + ); + }); + + it('testLogicalOperators', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + or( + and(greaterThan('rating', 4.5), equal('genre', 'Science Fiction')), + lessThan('published', 1900), + ), + ) + .select('title') + .sort(field('title').ascending()) + .execute(); + expectResults( + snapshot, + {title: 'Crime and Punishment'}, + {title: 'Dune'}, + {title: 'Pride and Prejudice'}, + ); + }); + + it('testChecks', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + equal('rating', null).as('ratingIsNull'), + equal('rating', NaN).as('ratingIsNaN'), + isError(divide(constant(1), constant(0))).as('isError'), + ifError(divide(constant(1), constant(0)), constant('was error')).as( + 'ifError', + ), + ifError( + divide(constant(1), constant(0)).greaterThan(1), + constant(true), + ) + .not() + .as('ifErrorBooleanExpression'), + isAbsent('foo').as('isAbsent'), + notEqual('title', null).as('titleIsNotNull'), + notEqual('cost', NaN).as('costIsNotNan'), + exists('fooBarBaz').as('fooBarBazExists'), + field('title').exists().as('titleExists'), + ) + .execute(); + expectResults(snapshot, { + ratingIsNull: false, + ratingIsNaN: false, + isError: true, + ifError: 'was error', + ifErrorBooleanExpression: false, + isAbsent: true, + titleIsNotNull: true, + costIsNotNan: false, + fooBarBazExists: false, + titleExists: true, + }); + + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + field('rating').equal(null).as('ratingIsNull'), + field('rating').equal(NaN).as('ratingIsNaN'), + divide(constant(1), constant(0)).isError().as('isError'), + divide(constant(1), constant(0)) + .ifError(constant('was error')) + .as('ifError'), + divide(constant(1), constant(0)) + .greaterThan(1) + .ifError(constant(true)) + .not() + .as('ifErrorBooleanExpression'), + field('foo').isAbsent().as('isAbsent'), + field('title').notEqual(null).as('titleIsNotNull'), + field('cost').notEqual(NaN).as('costIsNotNan'), + ) + .execute(); + expectResults(snapshot, { + ratingIsNull: false, + ratingIsNaN: false, + isError: true, + ifError: 'was error', + ifErrorBooleanExpression: false, + isAbsent: true, + titleIsNotNull: true, + costIsNotNan: false, + }); + }); + + it('testMapGet', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('published').descending()) + .select( + field('awards').mapGet('hugo').as('hugoAward'), + field('awards').mapGet('others').as('others'), + field('title'), + ) + .where(equal('hugoAward', true)) + .execute(); + expectResults( + snapshot, + { + hugoAward: true, + title: "The Hitchhiker's Guide to the Galaxy", + others: {unknown: {year: 1980}}, + }, + {hugoAward: true, title: 'Dune'}, + ); + }); + + it('test mapSet', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .replaceWith(map({existingField: map({foo: 1})})) + .addFields( + mapSet('existingField', 'bar', 2).as('modifiedField'), + mapSet(map({}), 'a', 1).as('simple'), + mapSet(map({a: 1}), 'b', 2).as('add'), + mapSet(map({a: 1}), 'a', 2).as('overwrite'), + mapSet(map({a: 1, b: 2}), 'a', 3, 'c', 4).as('multi'), + mapSet(map({a: 1}), 'a', field('non_existent')).as('remove'), + mapSet(map({a: 1}), 'b', null).as('setNull'), + mapSet(map({a: {b: 1}}), 'a.b', 2).as('setDotted'), + mapSet(map({}), '', 'empty').as('setEmptyKey'), + mapSet(map({a: 1}), 'b', add(constant(1), constant(2))).as( + 'setExprVal', + ), + mapSet(map({}), 'obj', map({hidden: true})).as('setNestedMap'), + mapSet(map({}), '~!@#$%^&*()_+', 'special').as('setSpecialChars'), + ) + .execute(); + expectResults(snapshot, { + existingField: {foo: 1}, + modifiedField: {foo: 1, bar: 2}, + simple: {a: 1}, + add: {a: 1, b: 2}, + overwrite: {a: 2}, + multi: {a: 3, b: 2, c: 4}, + remove: {}, + setNull: {a: 1, b: null}, + setDotted: {a: {b: 1}, 'a.b': 2}, + setEmptyKey: {'': 'empty'}, + setExprVal: {a: 1, b: 3}, + setNestedMap: {obj: {hidden: true}}, + setSpecialChars: {'~!@#$%^&*()_+': 'special'}, + }); + }); + + it('test mapKeys', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .replaceWith(map({existingField: map({foo: 1})})) + .addFields( + mapKeys('existingField').as('existingKeys'), + mapKeys(map({a: 1, b: 2})).as('keys'), + mapKeys(map({})).as('empty_keys'), + mapKeys(map({a: {nested: true}})).as('nested_keys'), + ) + .execute(); + + const res = snapshot.results[0].data(); + expect(res.existingKeys).to.have.members(['foo']); + expect(res.keys).to.have.members(['a', 'b']); + expect(res.empty_keys).to.deep.equal([]); + expect(res.nested_keys).to.have.members(['a']); + }); + + it('test mapValues', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .replaceWith(map({existingField: map({foo: 1})})) + .addFields( + mapValues('existingField').as('existingValues'), + mapValues(map({a: 1, b: 2})).as('values'), + mapValues(map({})).as('empty_values'), + mapValues(map({a: {nested: true}})).as('nested_values'), + ) + .execute(); + const res = snapshot.results[0].data(); + expect(res.existingValues).to.have.members([1]); + expect(res.values).to.have.members([1, 2]); + expect(res.empty_values).to.deep.equal([]); + expect(res.nested_values).to.deep.include.members([{nested: true}]); + }); + + it('test mapEntries', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .replaceWith(map({existingField: map({foo: 1})})) + .addFields( + mapEntries('existingField').as('existingEntries'), + mapEntries(map({a: 1, b: 2})).as('entries'), + mapEntries(map({})).as('empty_entries'), + mapEntries(map({a: {nested: true}})).as('nested_entries'), + ) + .execute(); + const res = snapshot.results[0].data(); + expect(res.existingEntries).to.deep.include.members([{k: 'foo', v: 1}]); + expect(res.entries).to.deep.include.members([ + {k: 'a', v: 1}, + {k: 'b', v: 2}, + ]); + expect(res.empty_entries).to.deep.equal([]); + expect(res.nested_entries).to.deep.include.members([ + {k: 'a', v: {nested: true}}, + ]); + }); + + it('testDistanceFunctions', async () => { + const sourceVector = FieldValue.vector([0.1, 0.1]); + const targetVector = FieldValue.vector([0.5, 0.8]); + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select( + cosineDistance(constant(sourceVector), targetVector).as( + 'cosineDistance', + ), + dotProduct(constant(sourceVector), targetVector).as( + 'dotProductDistance', + ), + euclideanDistance(constant(sourceVector), targetVector).as( + 'euclideanDistance', + ), + ) + .limit(1) + .execute(); + + expectResults(snapshot, { + cosineDistance: 0.02560880430538015, + dotProductDistance: 0.13, + euclideanDistance: 0.806225774829855, + }); + + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select( + constant(sourceVector) + .cosineDistance(targetVector) + .as('cosineDistance'), + constant(sourceVector) + .dotProduct(targetVector) + .as('dotProductDistance'), + constant(sourceVector) + .euclideanDistance(targetVector) + .as('euclideanDistance'), + ) + .limit(1) + .execute(); + + expectResults(snapshot, { + cosineDistance: 0.02560880430538015, + dotProductDistance: 0.13, + euclideanDistance: 0.806225774829855, + }); + }); + + it('testVectorLength', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select( + vectorLength(constant(FieldValue.vector([1, 2, 3]))).as( + 'vectorLength', + ), + ) + .execute(); + expectResults(snapshot, { + vectorLength: 3, + }); + }); + + it('testNestedFields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('awards.hugo', true)) + .sort(descending('title')) + .select('title', 'awards.hugo') + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + 'awards.hugo': true, + }, + {title: 'Dune', 'awards.hugo': true}, + ); + }); + + it('test mapGet with field name including . notation', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .replaceWith( + map({ + title: 'foo', + nested: { + level: { + '1': 'bar', + }, + 'level.1': { + 'level.2': 'baz', + }, + }, + }), + ) + .select( + 'title', + field('nested.level.1'), + mapGet('nested', 'level.1').mapGet('level.2').as('nested'), + ) + .execute(); + + expectResults(snapshot, { + title: 'foo', + 'nested.level.`1`': 'bar', + nested: 'baz', + }); + }); + + describe('genericFunction', () => { + it('add selectable', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(descending('rating')) + .limit(1) + .select( + new FunctionExpression('add', [field('rating'), constant(1)]).as( + 'rating', + ), + ) + .execute(); + expectResults(snapshot, { + rating: 5.7, + }); + }); + + it('and (variadic) selectable', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + new FunctionExpression('and', [ + field('rating').greaterThan(0), + field('title').charLength().lessThan(5), + field('tags').arrayContains('propaganda'), + ]).asBoolean(), + ) + .select('title') + .execute(); + expectResults(snapshot, { + title: '1984', + }); + }); + + it('array contains any', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + new FunctionExpression('array_contains_any', [ + field('tags'), + array(['politics']), + ]).asBoolean(), + ) + .select('title') + .execute(); + expectResults(snapshot, { + title: 'Dune', + }); + }); + + it('countif aggregate', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate( + new AggregateFunction('count_if', [ + field('rating').greaterThanOrEqual(4.5), + ]).as('countOfBest'), + ) + .execute(); + expectResults(snapshot, { + countOfBest: 3, + }); + }); + + it('sort by char_len', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort( + new FunctionExpression('char_length', [field('title')]).ascending(), + descending('__name__'), + ) + .limit(3) + .select('title') + .execute(); + expectResults( + snapshot, + { + title: '1984', + }, + { + title: 'Dune', + }, + { + title: 'The Great Gatsby', + }, + ); + }); + }); + + it('supports array', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(array([1, 2, 3, 4]).as('metadata')) + .execute(); + expect(snapshot.results.length).to.equal(1); + expectResults(snapshot, { + metadata: [1, 2, 3, 4], + }); + }); + + it('evaluates expression in array', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + array([1, 2, field('genre'), multiply('rating', 10)]).as('metadata'), + ) + .execute(); + expect(snapshot.results.length).to.equal(1); + expectResults(snapshot, { + metadata: [1, 2, 'Fantasy', 47], + }); + }); + + it('supports arrayGet', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(3) + .select(arrayGet('tags', 0).as('firstTag')) + .execute(); + const expectedResults = [ + { + firstTag: 'adventure', + }, + { + firstTag: 'politics', + }, + { + firstTag: 'classic', + }, + ]; + expectResults(snapshot, ...expectedResults); + + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(3) + .select(field('tags').arrayGet(0).as('firstTag')) + .execute(); + expectResults(snapshot, ...expectedResults); + }); + + it('supports map', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + map({ + foo: 'bar', + }).as('metadata'), + ) + .execute(); + + expect(snapshot.results.length).to.equal(1); + expectResults(snapshot, { + metadata: { + foo: 'bar', + }, + }); + }); + + it('evaluates expression in map', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + map({ + genre: field('genre'), + rating: field('rating').multiply(10), + }).as('metadata'), + ) + .execute(); + + expect(snapshot.results.length).to.equal(1); + expectResults(snapshot, { + metadata: { + genre: 'Fantasy', + rating: 47, + }, + }); + }); + + it('supports mapRemove', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(mapRemove('awards', 'hugo').as('awards')) + .execute(); + expectResults(snapshot, { + awards: {nebula: false}, + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('awards').mapRemove('hugo').as('awards')) + .execute(); + expectResults(snapshot, { + awards: {nebula: false}, + }); + }); + + it('supports mapMerge', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(mapMerge('awards', {fakeAward: true}).as('awards')) + .execute(); + expectResults(snapshot, { + awards: {nebula: false, hugo: false, fakeAward: true}, + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('awards').mapMerge({fakeAward: true}).as('awards')) + .execute(); + expectResults(snapshot, { + awards: {nebula: false, hugo: false, fakeAward: true}, + }); + }); + + it('supports timestamp conversions', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select( + unixSecondsToTimestamp(constant(1741380235)).as( + 'unixSecondsToTimestamp', + ), + unixMillisToTimestamp(constant(1741380235123)).as( + 'unixMillisToTimestamp', + ), + unixMicrosToTimestamp(constant(1741380235123456)).as( + 'unixMicrosToTimestamp', + ), + timestampToUnixSeconds( + constant(new Timestamp(1741380235, 123456789)), + ).as('timestampToUnixSeconds'), + timestampToUnixMicros( + constant(new Timestamp(1741380235, 123456789)), + ).as('timestampToUnixMicros'), + timestampToUnixMillis( + constant(new Timestamp(1741380235, 123456789)), + ).as('timestampToUnixMillis'), + ) + .execute(); + expectResults(snapshot, { + unixMicrosToTimestamp: new Timestamp(1741380235, 123456000), + unixMillisToTimestamp: new Timestamp(1741380235, 123000000), + unixSecondsToTimestamp: new Timestamp(1741380235, 0), + timestampToUnixSeconds: 1741380235, + timestampToUnixMicros: 1741380235123456, + timestampToUnixMillis: 1741380235123, + }); + }); + + it('supports timestamp math', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(constant(new Timestamp(1741380235, 0)).as('timestamp')) + .select( + timestampAdd('timestamp', 'day', 10).as('plus10days'), + timestampAdd('timestamp', 'hour', 10).as('plus10hours'), + timestampAdd('timestamp', 'minute', 10).as('plus10minutes'), + timestampAdd('timestamp', 'second', 10).as('plus10seconds'), + timestampAdd('timestamp', 'microsecond', 10).as('plus10micros'), + timestampAdd('timestamp', 'millisecond', 10).as('plus10millis'), + timestampSubtract('timestamp', 'day', 10).as('minus10days'), + timestampSubtract('timestamp', 'hour', 10).as('minus10hours'), + timestampSubtract('timestamp', 'minute', 10).as('minus10minutes'), + timestampSubtract('timestamp', 'second', 10).as('minus10seconds'), + timestampSubtract('timestamp', 'microsecond', 10).as('minus10micros'), + timestampSubtract('timestamp', 'millisecond', 10).as('minus10millis'), + ) + .execute(); + expectResults(snapshot, { + plus10days: new Timestamp(1742244235, 0), + plus10hours: new Timestamp(1741416235, 0), + plus10minutes: new Timestamp(1741380835, 0), + plus10seconds: new Timestamp(1741380245, 0), + plus10micros: new Timestamp(1741380235, 10000), + plus10millis: new Timestamp(1741380235, 10000000), + minus10days: new Timestamp(1740516235, 0), + minus10hours: new Timestamp(1741344235, 0), + minus10minutes: new Timestamp(1741379635, 0), + minus10seconds: new Timestamp(1741380225, 0), + minus10micros: new Timestamp(1741380234, 999990000), + minus10millis: new Timestamp(1741380234, 990000000), + }); + }); + + it('supports byteLength', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol) + .limit(1) + .select(constant(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0])).as('bytes')) + .select(byteLength('bytes').as('byteLength')) + .execute(); + + expectResults(snapshot, { + byteLength: 8, + }); + }); + + it('supports not', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol) + .limit(1) + .select(constant(true).as('trueField')) + .select('trueField', not(equal('trueField', true)).as('falseField')) + .execute(); + + expectResults(snapshot, { + trueField: true, + falseField: false, + }); + }); + + it('can reverse an array', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('tags').arrayReverse().as('reversedTags')) + .execute(); + expectResults(snapshot, { + reversedTags: ['adventure', 'space', 'comedy'], + }); + }); + + it('can reverse an array with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(arrayReverse('tags').as('reversedTags')) + .execute(); + expectResults(snapshot, { + reversedTags: ['adventure', 'space', 'comedy'], + }); + }); + + it('can compute the ceiling of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').ceil().as('ceilingRating')) + .execute(); + expectResults(snapshot, { + ceilingRating: 5, + }); + }); + + it('can compute the ceiling of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(ceil('rating').as('ceilingRating')) + .execute(); + expectResults(snapshot, { + ceilingRating: 5, + }); + }); + + it('can compute the floor of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').floor().as('floorRating')) + .execute(); + expectResults(snapshot, { + floorRating: 4, + }); + }); + + it('can compute the floor of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(floor('rating').as('floorRating')) + .execute(); + expectResults(snapshot, { + floorRating: 4, + }); + }); + + it('can compute e to the power of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('The Lord of the Rings')) + .limit(1) + .select(field('rating').exp().as('expRating')) + .execute(); + expect(snapshot.results[0].get('expRating')).to.be.approximately( + 109.94717245212352, + 0.00001, + ); + }); + + it('can compute e to the power of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('The Lord of the Rings')) + .limit(1) + .select(exp('rating').as('expRating')) + .execute(); + expect(snapshot.results[0].get('expRating')).to.be.approximately( + 109.94717245212351, + 0.000001, + ); + }); + + it('can compute the power of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').pow(2).as('powerRating')) + .execute(); + expect(snapshot.results[0].get('powerRating')).to.be.approximately( + 17.64, + 0.0001, + ); + }); + + it('can compute the power of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(pow('rating', 2).as('powerRating')) + .execute(); + expect(snapshot.results[0].get('powerRating')).to.be.approximately( + 17.64, + 0.0001, + ); + }); + + it('testRand', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select(rand().as('randomNumber')) + .limit(1) + .execute(); + expect(snapshot.results.length).to.equal(1); + const randomNumber = snapshot.results[0].get('randomNumber') as number; + expect(randomNumber).to.be.a('number'); + expect(randomNumber).to.be.gte(0); + expect(randomNumber).to.be.lt(1); + }); + + it('can round a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').round().as('roundedRating')) + .execute(); + expectResults(snapshot, { + roundedRating: 4, + }); + }); + + it('can round a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(round('rating').as('roundedRating')) + .execute(); + expectResults(snapshot, { + roundedRating: 4, + }); + }); + + it('can round a numeric value away from zero for positive half-way values', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .addFields(constant(1.5).as('positiveHalf')) + .select(field('positiveHalf').round().as('roundedRating')) + .execute(); + expectResults(snapshot, { + roundedRating: 2, + }); + }); + + it('can round a numeric value away from zero for negative half-way values', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .addFields(constant(-1.5).as('negativeHalf')) + .select(field('negativeHalf').round().as('roundedRating')) + .execute(); + expectResults(snapshot, { + roundedRating: -2, + }); + }); + + it('can round a numeric value to specified precision', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .replaceWith( + map({ + foo: 4.123456, + }), + ) + .select( + field('foo').round(0).as('0'), + round('foo', 1).as('1'), + round('foo', constant(2)).as('2'), + round(field('foo'), 4).as('4'), + ) + .execute(); + expectResults(snapshot, { + '0': 4, + '1': 4.1, + '2': 4.12, + '4': 4.1235, + }); + }); + + it('can truncate a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('Pride and Prejudice')) + .limit(1) + .select(field('rating').trunc().as('truncatedRating')) + .execute(); + expectResults(snapshot, { + truncatedRating: 4, + }); + }); + + it('can truncate a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('Pride and Prejudice')) + .limit(1) + .select(trunc('rating').as('truncatedRating')) + .execute(); + expectResults(snapshot, { + truncatedRating: 4, + }); + }); + + it('can truncate a numeric value to specified precision', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .replaceWith( + map({ + foo: 4.123456, + }), + ) + .select( + field('foo').trunc(0).as('0'), + trunc('foo', 1).as('1'), + trunc('foo', constant(2)).as('2'), + trunc(field('foo'), 4).as('4'), + ) + .execute(); + expectResults(snapshot, { + '0': 4, + '1': 4.1, + '2': 4.12, + '4': 4.1234, + }); + }); + + it('can get the collectionId from a path', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(field('__name__').collectionId().as('collectionId')) + .execute(); + expectResults(snapshot, { + collectionId: randomCol.id, + }); + }); + + it('can get the collectionId from a path with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(collectionId('__name__').as('collectionId')) + .execute(); + expectResults(snapshot, { + collectionId: randomCol.id, + }); + }); + + it('can compute the length of a string value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('title').length().as('titleLength')) + .execute(); + expectResults(snapshot, { + titleLength: 36, + }); + }); + + it('can compute the length of a string value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(length('title').as('titleLength')) + .execute(); + expectResults(snapshot, { + titleLength: 36, + }); + }); + + it('can compute the length of an array value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('tags').length().as('tagsLength')) + .execute(); + expectResults(snapshot, { + tagsLength: 3, + }); + }); + + it('can compute the length of an array value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(length('tags').as('tagsLength')) + .execute(); + expectResults(snapshot, { + tagsLength: 3, + }); + }); + + it('can compute the length of a map value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('awards').length().as('awardsLength')) + .execute(); + expectResults(snapshot, { + awardsLength: 3, + }); + }); + + it('can compute the length of a vector value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('embedding').length().as('embeddingLength')) + .execute(); + expectResults(snapshot, { + embeddingLength: 10, + }); + }); + + it('can compute the length of a bytes value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select(constant('12é').as('value')) + .limit(1) + .select(field('value').byteLength().as('valueLength')) + .execute(); + expectResults(snapshot, { + valueLength: 4, + }); + }); + + it('can compute the natural logarithm of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').ln().as('lnRating')) + .execute(); + expect(snapshot.results[0]!.data().lnRating).to.be.closeTo(1.435, 0.001); + }); + + it('can compute the natural logarithm of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(ln('rating').as('lnRating')) + .execute(); + expect(snapshot.results[0]!.data().lnRating).to.be.closeTo(1.435, 0.001); + }); + + it('can compute the natural logarithm of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(ln('rating').as('lnRating')) + .execute(); + expectResults(snapshot, { + lnRating: 1.4350845252893227, + }); + }); + + it('can round a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').round().as('roundedRating')) + .execute(); + expectResults(snapshot, { + roundedRating: 4, + }); + }); + + it('can round a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(round('rating').as('roundedRating')) + .execute(); + expectResults(snapshot, { + roundedRating: 4, + }); + }); + + it('can compute the square root of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').sqrt().as('sqrtRating')) + .execute(); + expectResults(snapshot, { + sqrtRating: 2.04939015319192, + }); + }); + + it('can compute the square root of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(sqrt('rating').as('sqrtRating')) + .execute(); + expectResults(snapshot, { + sqrtRating: 2.04939015319192, + }); + }); + + it('can reverse a string', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('title').stringReverse().as('reversedTitle')) + .execute(); + expectResults(snapshot, { + reversedTitle: "yxalaG eht ot ediuG s'rekihhctiH ehT", + }); + }); + + it('can reverse a string with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(stringReverse('title').as('reversedTitle')) + .execute(); + expectResults(snapshot, { + reversedTitle: "yxalaG eht ot ediuG s'rekihhctiH ehT", + }); + }); + + it('supports Document_id', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + documentId(field('__name__')).as('docId'), + documentId(field('__path__')).as('noDocId'), + documentId(randomCol.doc('foo')).as('fromDocRef'), + ) + .execute(); + expectResults(snapshot, { + docId: 'book4', + noDocId: null, + fromDocRef: 'foo', + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('__name__').documentId().as('docId')) + .execute(); + expectResults(snapshot, { + docId: 'book4', + }); + }); + + it('supports substring', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(substring('title', 9, 2).as('of')) + .execute(); + expectResults(snapshot, { + of: 'of', + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('title').substring(9, 2).as('of')) + .execute(); + expectResults(snapshot, { + of: 'of', + }); + }); + + it('supports substring without length', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(substring('title', 9).as('of')) + .execute(); + expectResults(snapshot, { + of: 'of the Rings', + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('title').substring(9).as('of')) + .execute(); + expectResults(snapshot, { + of: 'of the Rings', + }); + }); + + it('arrayConcat works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .select( + arrayConcat('tags', ['newTag1', 'newTag2'], field('tags'), [null]).as( + 'modifiedTags', + ), + ) + .limit(1) + .execute(); + expectResults(snapshot, { + modifiedTags: [ + 'comedy', + 'space', + 'adventure', + 'newTag1', + 'newTag2', + 'comedy', + 'space', + 'adventure', + null, + ], + }); + }); + + it('test toLower', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('title')) + .select(toLower('author').as('lowercaseAuthor')) + .limit(1) + .execute(); + expectResults(snapshot, { + lowercaseAuthor: 'george orwell', + }); + }); + + it('test toUpper', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('title')) + .select(toUpper('author').as('uppercaseAuthor')) + .limit(1) + .execute(); + expectResults(snapshot, {uppercaseAuthor: 'GEORGE ORWELL'}); + }); + + it('testTrim', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .replaceWith( + map({ + spacedTitle: " The Hitchhiker's Guide to the Galaxy ", + userNameWithQuotes: '"alice"', + bytes: Uint8Array.from([0x00, 0x01, 0x02, 0x00, 0x00]), + }), + ) + .select( + trim('spacedTitle').as('trimmedTitle'), + field('spacedTitle'), + field('userNameWithQuotes').trim('"').as('userName'), + field('bytes') + .trim(Uint8Array.from([0x00])) + .as('bytes'), + ) + .limit(1) + .execute(); + expectResults(snapshot, { + spacedTitle: " The Hitchhiker's Guide to the Galaxy ", + trimmedTitle: "The Hitchhiker's Guide to the Galaxy", + userName: 'alice', + bytes: Uint8Array.from([0x01, 0x02]), + }); + }); + + it('test reverse', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('title', '1984')) + .limit(1) + .select(reverse('title').as('reverseTitle')) + .execute(); + expectResults(snapshot, {reverseTitle: '4891'}); + }); + + it('testAbs', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select( + constant(-10).as('neg10'), + constant(-22.22).as('neg22'), + constant(1).as('pos1'), + ) + .select( + abs('neg10').as('10'), + abs(field('neg22')).as('22'), + field('pos1').as('1'), + ) + .execute(); + expectResults(snapshot, { + '10': 10, + '22': 22.22, + '1': 1, + }); + }); + + it('can compute the base-10 logarithm of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('The Lord of the Rings')) + .limit(1) + .select(field('rating').log10().as('log10Rating')) + .execute(); + expect(snapshot.results[0]!.data().log10Rating).to.be.closeTo( + 0.672, + 0.001, + ); + }); + + it('can compute the base-10 logarithm of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('The Lord of the Rings')) + .limit(1) + .select(log10('rating').as('log10Rating')) + .execute(); + expect(snapshot.results[0]!.data().log10Rating).to.be.closeTo( + 0.672, + 0.001, + ); + }); + + it('can concat fields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .addFields( + concat('author', ' ', field('title')).as('display'), + field('author').concat(': ', field('title')).as('display2'), + ) + .where(equal('author', 'Douglas Adams')) + .select('display', 'display2') + .execute(); + expectResults(snapshot, { + display: "Douglas Adams The Hitchhiker's Guide to the Galaxy", + display2: "Douglas Adams: The Hitchhiker's Guide to the Galaxy", + }); + }); + + it('supports currentTimestamp', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .addFields(currentTimestamp().as('now')) + .select('now') + .execute(); + const now = snapshot.results[0].get('now') as Timestamp; + expect(now).instanceof(Timestamp); + expect( + now.toDate().getUTCSeconds() - new Date().getUTCSeconds(), + ).lessThan(5000); + }); + + it('supports ifAbsent', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .replaceWith( + map({ + title: 'foo', + }), + ) + .select( + ifAbsent('title', 'default title').as('title'), + field('name').ifAbsent('default name').as('name'), + field('name').ifAbsent(field('title')).as('nameOrTitle'), + ) + .execute(); + + expectResults(snapshot, { + title: 'foo', + name: 'default name', + nameOrTitle: 'foo', + }); + }); + + it('supports join', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .replaceWith( + map({ + tags: ['foo', 'bar', 'baz'], + delimeter: '|', + }), + ) + .select(join('tags', ',').as('csv'), field('tags').join('|').as('or')) + .execute(); + + expectResults(snapshot, { + csv: 'foo,bar,baz', + or: 'foo|bar|baz', + }); + }); + + it('can compute the sum of the elements in an array', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('The Lord of the Rings')) + .limit(1) + .addFields(array([150, 200]).as('sales')) + .select(field('sales').arraySum().as('totalSales')) + .execute(); + expectResults(snapshot, { + totalSales: 350, + }); + }); + + it('can compute the sum of the elements in an array with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('The Lord of the Rings')) + .limit(1) + .addFields(array([150, 200]).as('sales')) + .select(arraySum('sales').as('totalSales')) + .execute(); + expectResults(snapshot, { + totalSales: 350, + }); + }); + it('truncate timestamp', async () => { + const results = await firestore + .pipeline() + .collection(randomCol) + .limit(1) + .replaceWith( + map({ + timestamp: new Timestamp( + Date.UTC(2025, 10, 30, 1, 2, 3) / 1000, + 456789, + ), + }), + ) + .select( + timestampTruncate('timestamp', 'year').as('trunc_year'), + timestampTruncate(field('timestamp'), 'month').as('trunc_month'), + timestampTruncate(field('timestamp'), constant('day')).as( + 'trunc_day', + ), + field('timestamp') + .timestampTruncate(constant('day'), 'MST') + .as('trunc_day_mst'), + field('timestamp').timestampTruncate('hour').as('trunc_hour'), + field('timestamp') + .timestampTruncate(constant('minute')) + .as('trunc_minute'), + field('timestamp').timestampTruncate('second').as('trunc_second'), + ) + .execute(); + + expectResults(results, { + trunc_year: new Timestamp(Date.UTC(2025, 0) / 1000, 0), + trunc_month: new Timestamp(Date.UTC(2025, 10) / 1000, 0), + trunc_day: new Timestamp(Date.UTC(2025, 10, 30) / 1000, 0), + trunc_day_mst: new Timestamp( + Date.UTC(2025, 10, 29) / 1000 + 7 * 3600, + 0, + ), + trunc_hour: new Timestamp(Date.UTC(2025, 10, 30, 1) / 1000, 0), + trunc_minute: new Timestamp(Date.UTC(2025, 10, 30, 1, 2) / 1000, 0), + trunc_second: new Timestamp(Date.UTC(2025, 10, 30, 1, 2, 3) / 1000, 0), + }); + }); + + it('supports split', async () => { + const results = await firestore + .pipeline() + .collection(randomCol) + .limit(1) + .replaceWith( + map({ + csv: 'foo,bar,baz', + data: 'baz:bar:foo', + csvDelimeter: ',', + bytes: Uint8Array.from([0x01, 0x00, 0x02, 0x00, 0x03]), + }), + ) + .select( + split('csv', field('csvDelimeter')).as('csv'), + split(field('data'), ':').as('data'), + field('bytes') + .split(constant(Uint8Array.from([0x00]))) + .as('bytes'), + ) + .execute(); + + expectResults(results, { + csv: ['foo', 'bar', 'baz'], + data: ['baz', 'bar', 'foo'], + bytes: [ + Uint8Array.from([0x01]), + Uint8Array.from([0x02]), + Uint8Array.from([0x03]), + ], + }); + + void expect( + firestore + .pipeline() + .collection(randomCol) + .limit(1) + .replaceWith( + map({ + csv: 'foo,bar,baz', + }), + ) + .select( + field('csv') + .split(constant(Uint8Array.from([0x00]))) + .as('dontSplitStringAndBytes'), + ) + .execute(), + ).to.be.rejected; + }); + + it('supports type', async () => { + const result = await firestore + .pipeline() + .collection(randomCol) + .limit(1) + .replaceWith( + map({ + int: constant(1), + float: constant(1.1), + str: constant('a string'), + bool: constant(true), + null: constant(null), + geoPoint: constant(new GeoPoint(0.1, 0.2)), + timestamp: constant(new Timestamp(123456, 0)), + date: constant(new Date()), + bytes: constant(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0])), + docRef: constant(firestore.doc('foo/bar')), + vector: constant(FieldValue.vector([1, 2, 3])), + map: map({ + number: 1, + string: 'a string', + }), + array: array([1, 'a string']), + }), + ) + .select( + type('int').as('int'), + field('float').type().as('float'), + field('str').type().as('str'), + type('bool').as('bool'), + type('null').as('null'), + type('geoPoint').as('geoPoint'), + type('timestamp').as('timestamp'), + type('date').as('date'), + type('bytes').as('bytes'), + type('docRef').as('docRef'), + type('vector').as('vector'), + type('map').as('map'), + type('array').as('array'), + ) + .execute(); + + expectResults(result, { + int: 'int64', + float: 'float64', + str: 'string', + bool: 'boolean', + null: 'null', + geoPoint: 'geo_point', + timestamp: 'timestamp', + date: 'timestamp', + bytes: 'bytes', + docRef: 'reference', + vector: 'vector', + map: 'map', + array: 'array', + }); + }); + + it('supports isType', async () => { + const result = await firestore + .pipeline() + .collection(randomCol.path) + .replaceWith( + map({ + int: constant(1), + float: constant(1.1), + str: constant('a string'), + bool: constant(true), + null: constant(null), + geoPoint: constant(new GeoPoint(0.1, 0.2)), + timestamp: constant(new Timestamp(123456, 0)), + bytes: constant(new Uint8Array([1, 2, 3])), + docRef: constant(firestore.doc(`${randomCol.path}/bar`)), + vector: constant(FieldValue.vector([1, 2, 3])), + map: map({ + numberK: 1, + stringK: 'a string', + }), + array: array([1, '2', true]), + }), + ) + .select( + isType(field('int'), 'int64').as('isInt64'), + isType(field('int'), 'number').as('isInt64IsNumber'), + isType(field('int'), 'decimal128').as('isInt64IsDecimal128'), + field('float').isType('float64').as('isFloat64'), + field('float').isType('number').as('isFloat64IsNumber'), + field('float').isType('decimal128').as('isFloat64IsDecimal128'), + isType('str', 'string').as('isStr'), + isType('int', 'string').as('isNumStr'), + field('bool').isType('boolean').as('isBool'), + isType('null', 'null').as('isNull'), + field('geoPoint').isType('geo_point').as('isGeoPoint'), + isType('timestamp', 'timestamp').as('isTimestamp'), + field('bytes').isType('bytes').as('isBytes'), + isType('docRef', 'reference').as('isDocRef'), + field('vector').isType('vector').as('isVector'), + isType('map', 'map').as('isMap'), + field('array').isType('array').as('isArray'), + field('str').isType('int64').as('isStrNum'), + ) + .limit(1) + .execute(); + + expectResults(result, { + isInt64: true, + isInt64IsNumber: true, + isInt64IsDecimal128: false, + isFloat64: true, + isFloat64IsNumber: true, + isFloat64IsDecimal128: false, + isStr: true, + isNumStr: false, + isBool: true, + isNull: true, + isGeoPoint: true, + isTimestamp: true, + isBytes: true, + isDocRef: true, + isVector: true, + isMap: true, + isArray: true, + isStrNum: false, + }); + }); + + // TODO(new-expression): Add new expression tests above this line + }); + + describe('pagination', () => { + let addedDocs: DocumentReference[] = []; + + /** + * Adds several books to the test collection. These + * additional books support pagination test scenarios + * that would otherwise not be possible with the original + * set of books. + * @param collectionReference + */ + async function addBooks( + collectionReference: CollectionReference, + ): Promise { + let docRef = collectionReference.doc('book11'); + addedDocs.push(docRef); + await docRef.set({ + title: 'Jonathan Strange & Mr Norrell', + author: 'Susanna Clarke', + genre: 'Fantasy', + published: 2004, + rating: 4.6, + tags: ['historical fantasy', 'magic', 'alternate history', 'england'], + awards: {hugo: false, nebula: false}, + }); + docRef = collectionReference.doc('book12'); + addedDocs.push(collectionReference.doc('book12')); + await docRef.set({ + title: 'The Master and Margarita', + author: 'Mikhail Bulgakov', + genre: 'Satire', + published: 1967, // Though written much earlier + rating: 4.6, + tags: [ + 'russian literature', + 'supernatural', + 'philosophy', + 'dark comedy', + ], + awards: {}, + }); + docRef = collectionReference.doc('book13'); + addedDocs.push(docRef); + await docRef.set({ + title: 'A Long Way to a Small, Angry Planet', + author: 'Becky Chambers', + genre: 'Science Fiction', + published: 2014, + rating: 4.6, + tags: ['space opera', 'found family', 'character-driven', 'optimistic'], + awards: {hugo: false, nebula: false, kitschies: true}, + }); + } + + afterEach(async () => { + for (let i = 0; i < addedDocs.length; i++) { + await addedDocs[i].delete(); + } + addedDocs = []; + }); + + it('supports pagination with filters', async () => { + await addBooks(randomCol); + const pageSize = 2; + const pipeline = firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'rating', '__name__') + .sort(field('rating').descending(), field('__name__').ascending()); + + let snapshot = await pipeline.limit(pageSize).execute(); + + snapshot.results.forEach(r => console.log(JSON.stringify(r.data()))); + + expectResults( + snapshot, + {title: 'The Lord of the Rings', rating: 4.7}, + {title: 'Dune', rating: 4.6}, + ); + + const lastDoc = snapshot.results[snapshot.results.length - 1]; + + snapshot = await pipeline + .where( + or( + and( + field('rating').equal(lastDoc.get('rating')), + field('__name__').greaterThan(lastDoc.ref), + ), + field('rating').lessThan(lastDoc.get('rating')), + ), + ) + .limit(pageSize) + .execute(); + expectResults( + snapshot, + {title: 'Jonathan Strange & Mr Norrell', rating: 4.6}, + {title: 'The Master and Margarita', rating: 4.6}, + ); + }); + + it('supports pagination with offsets', async () => { + await addBooks(randomCol); + + const secondFilterField = '__name__'; + + const pipeline = firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'rating', secondFilterField) + .sort( + field('rating').descending(), + field(secondFilterField).ascending(), + ); + + const pageSize = 2; + let currPage = 0; + + let snapshot = await pipeline + .offset(currPage++ * pageSize) + .limit(pageSize) + .execute(); + + expectResults( + snapshot, + { + title: 'The Lord of the Rings', + rating: 4.7, + }, + {title: 'Dune', rating: 4.6}, + ); + + snapshot = await pipeline + .offset(currPage++ * pageSize) + .limit(pageSize) + .execute(); + expectResults( + snapshot, + { + title: 'Jonathan Strange & Mr Norrell', + rating: 4.6, + }, + {title: 'The Master and Margarita', rating: 4.6}, + ); + + snapshot = await pipeline + .offset(currPage++ * pageSize) + .limit(pageSize) + .execute(); + expectResults( + snapshot, + { + title: 'A Long Way to a Small, Angry Planet', + rating: 4.6, + }, + { + title: 'Pride and Prejudice', + rating: 4.5, + }, + ); + }); + }); + + describe('stage options', () => { + describe('forceIndex', () => { + // SKIP: requires pre-existing index + it.skip('Collection Stage', async () => { + const snapshot = await firestore + .pipeline() + .collection({ + collection: randomCol, + forceIndex: 'unknown', + }) + .execute(); + expect(snapshot.results.length).to.equal(10); + }); + + // SKIP: requires pre-existing index + it.skip('CollectionGroup Stage', async () => { + const snapshot = await firestore + .pipeline() + .collectionGroup({ + collectionId: randomCol.id, + forceIndex: 'unknown', + }) + .execute(); + expect(snapshot.results.length).to.equal(10); + }); + }); + }); + + describe('stream', () => { + it('full results as expected', done => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + const snapshotStream = ppl.stream(); + + const expected = [ + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9', + ]; + + let received = 0; + snapshotStream + .on('data', d => { + expect(d).to.be.an.instanceOf(PipelineResult); + const rslt = d as PipelineResult; + expect(rslt.id).to.equal(expected.shift()); + ++received; + }) + .on('end', () => { + expect(received).to.equal(10); + done(); + }); + }); + + it('empty snapshot', done => { + const ppl = firestore.pipeline().collection(randomCol.path).limit(0); + const snapshotStream = ppl.stream(); + + let received = 0; + snapshotStream + .on('data', _ => { + ++received; + }) + .on('end', () => { + expect(received).to.equal(0); + done(); + }); + }); + + it('document transform', done => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')) + .limit(2) + .select('title'); + const snapshotStream = ppl.stream(); + + const expected = [ + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'Dune'}, + ]; + + let received = 0; + snapshotStream + .on('data', d => { + expect(d).to.be.an.instanceOf(PipelineResult); + const rslt = d as PipelineResult; + expect(rslt.data()).to.deep.equal(expected.shift()); + ++received; + }) + .on('end', () => { + expect(received).to.equal(2); + done(); + }); + }); + }); +}); + +// This is the Query integration tests from the lite API (no cache support) +// with some additional test cases added for more complete coverage. +// eslint-disable-next-line no-restricted-properties +describe.skipClassic('Query to Pipeline', () => { + async function execute(ppl: Pipeline): Promise { + return ppl.execute(); + } + + async function testCollectionWithDocs( + docs: { + [id: string]: DocumentData; + }, + callback: (collRef: CollectionReference, db: Firestore) => Promise, + ): Promise { + const randomCol = getTestRoot(); + const firestore = randomCol.firestore; + for (const id in docs) { + const ref = randomCol.doc(id); + await ref.set(docs[id]); + } + + try { + await callback(randomCol, firestore); + } finally { + await firestore.terminate(); + } + } + + function verifyResults( + actual: PipelineSnapshot, + ...expected: DocumentData[] + ): void { + const results = actual.results; + expect(results.length).to.equal(expected.length); + + for (let i = 0; i < expected.length; ++i) { + expect(results[i].data()).to.deep.equal(expected[i]); + } + } + + it('supports default query', () => { + return testCollectionWithDocs({1: {foo: 1}}, async (collRef, db) => { + const snapshot = await execute(db.pipeline().createFrom(collRef)); + verifyResults(snapshot, {foo: 1}); + }); + }); + + it('supports filtered query', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.where('foo', '==', 1); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}); + }, + ); + }); + + it('supports filtered query (with FieldPath)', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.where(new FieldPath('foo'), '==', 1); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}); + }, + ); + }); + + it('supports ordered query (with default order)', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo'); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}, {foo: 2}); + }, + ); + }); + + it('supports ordered query (with asc)', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo', 'asc'); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}, {foo: 2}); + }, + ); + }); + + it('supports ordered query (with desc)', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo', 'desc'); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}, {foo: 1}); + }, + ); + }); + + it('supports limit query', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').limit(1); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}); + }, + ); + }); + + it('supports limitToLast query', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + 3: {foo: 3}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').limitToLast(2); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}, {foo: 3}); + }, + ); + }); + + it('supports startAt', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').startAt(2); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}); + }, + ); + }); + + it('supports startAt with limitToLast', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + 3: {foo: 3}, + 4: {foo: 4}, + 5: {foo: 5}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').startAt(3).limitToLast(4); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 3}, {foo: 4}, {foo: 5}); + }, + ); + }); + + it('supports endAt with limitToLast', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + 3: {foo: 3}, + 4: {foo: 4}, + 5: {foo: 5}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').endAt(3).limitToLast(2); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}, {foo: 3}); + }, + ); + }); + + it('supports startAfter (with DocumentSnapshot)', () => { + return testCollectionWithDocs( + { + 1: {id: 1, foo: 1, bar: 1, baz: 1}, + 2: {id: 2, foo: 1, bar: 1, baz: 2}, + 3: {id: 3, foo: 1, bar: 1, baz: 2}, + 4: {id: 4, foo: 1, bar: 2, baz: 1}, + 5: {id: 5, foo: 1, bar: 2, baz: 2}, + 6: {id: 6, foo: 1, bar: 2, baz: 2}, + 7: {id: 7, foo: 2, bar: 1, baz: 1}, + 8: {id: 8, foo: 2, bar: 1, baz: 2}, + 9: {id: 9, foo: 2, bar: 1, baz: 2}, + 10: {id: 10, foo: 2, bar: 2, baz: 1}, + 11: {id: 11, foo: 2, bar: 2, baz: 2}, + 12: {id: 12, foo: 2, bar: 2, baz: 2}, + }, + async (collRef, db) => { + let docRef = await collRef.doc('2').get(); + let query1 = collRef + .orderBy('foo') + .orderBy('bar') + .orderBy('baz') + .startAfter(docRef); + let snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 3, foo: 1, bar: 1, baz: 2}, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 5, foo: 1, bar: 2, baz: 2}, + {id: 6, foo: 1, bar: 2, baz: 2}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 8, foo: 2, bar: 1, baz: 2}, + {id: 9, foo: 2, bar: 1, baz: 2}, + {id: 10, foo: 2, bar: 2, baz: 1}, + {id: 11, foo: 2, bar: 2, baz: 2}, + {id: 12, foo: 2, bar: 2, baz: 2}, + ); + + docRef = await collRef.doc('3').get(); + query1 = collRef + .orderBy('foo') + .orderBy('bar') + .orderBy('baz') + .startAfter(docRef); + snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 5, foo: 1, bar: 2, baz: 2}, + {id: 6, foo: 1, bar: 2, baz: 2}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 8, foo: 2, bar: 1, baz: 2}, + {id: 9, foo: 2, bar: 1, baz: 2}, + {id: 10, foo: 2, bar: 2, baz: 1}, + {id: 11, foo: 2, bar: 2, baz: 2}, + {id: 12, foo: 2, bar: 2, baz: 2}, + ); + }, + ); + }); + + it('supports startAt (with DocumentSnapshot)', () => { + return testCollectionWithDocs( + { + 1: {id: 1, foo: 1, bar: 1, baz: 1}, + 2: {id: 2, foo: 1, bar: 1, baz: 2}, + 3: {id: 3, foo: 1, bar: 1, baz: 2}, + 4: {id: 4, foo: 1, bar: 2, baz: 1}, + 5: {id: 5, foo: 1, bar: 2, baz: 2}, + 6: {id: 6, foo: 1, bar: 2, baz: 2}, + 7: {id: 7, foo: 2, bar: 1, baz: 1}, + 8: {id: 8, foo: 2, bar: 1, baz: 2}, + 9: {id: 9, foo: 2, bar: 1, baz: 2}, + 10: {id: 10, foo: 2, bar: 2, baz: 1}, + 11: {id: 11, foo: 2, bar: 2, baz: 2}, + 12: {id: 12, foo: 2, bar: 2, baz: 2}, + }, + async (collRef, db) => { + let docRef = await collRef.doc('2').get(); + let query1 = collRef + .orderBy('foo') + .orderBy('bar') + .orderBy('baz') + .startAt(docRef); + let snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 2, foo: 1, bar: 1, baz: 2}, + {id: 3, foo: 1, bar: 1, baz: 2}, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 5, foo: 1, bar: 2, baz: 2}, + {id: 6, foo: 1, bar: 2, baz: 2}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 8, foo: 2, bar: 1, baz: 2}, + {id: 9, foo: 2, bar: 1, baz: 2}, + {id: 10, foo: 2, bar: 2, baz: 1}, + {id: 11, foo: 2, bar: 2, baz: 2}, + {id: 12, foo: 2, bar: 2, baz: 2}, + ); + + docRef = await collRef.doc('3').get(); + query1 = collRef + .orderBy('foo') + .orderBy('bar') + .orderBy('baz') + .startAt(docRef); + snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 3, foo: 1, bar: 1, baz: 2}, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 5, foo: 1, bar: 2, baz: 2}, + {id: 6, foo: 1, bar: 2, baz: 2}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 8, foo: 2, bar: 1, baz: 2}, + {id: 9, foo: 2, bar: 1, baz: 2}, + {id: 10, foo: 2, bar: 2, baz: 1}, + {id: 11, foo: 2, bar: 2, baz: 2}, + {id: 12, foo: 2, bar: 2, baz: 2}, + ); + }, + ); + }); + + it('supports startAfter', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').startAfter(1); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}); + }, + ); + }); + + it('supports endAt', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').endAt(1); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}); + }, + ); + }); + + it('supports endBefore', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').endBefore(2); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}); + }, + ); + }); + + it('supports pagination', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + let query1 = collRef.orderBy('foo').limit(1); + const pipeline1 = db.pipeline().createFrom(query1); + let snapshot = await execute(pipeline1); + verifyResults(snapshot, {foo: 1}); + + // Pass the document snapshot from the previous snapshot + query1 = query1.startAfter(snapshot.results[0].get('foo')); + snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}); + }, + ); + }); + + it('supports pagination on DocumentIds', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + let query1 = collRef + .orderBy('foo') + .orderBy(FieldPath.documentId(), 'asc') + .limit(1); + const pipeline1 = db.pipeline().createFrom(query1); + let snapshot = await execute(pipeline1); + verifyResults(snapshot, {foo: 1}); + + // Pass the document snapshot from the previous snapshot + query1 = query1.startAfter( + snapshot.results[0].get('foo'), + snapshot.results[0].ref?.id, + ); + snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}); + }, + ); + }); + + it('supports collection groups', () => { + return testCollectionWithDocs({}, async (collRef, db) => { + const collectionGroupId = `${collRef.id}group`; + + const fooDoc = collRef.firestore.doc( + `${collRef.id}/foo/${collectionGroupId}/doc1`, + ); + const barDoc = collRef.firestore.doc( + `${collRef.id}/bar/baz/boo/${collectionGroupId}/doc2`, + ); + await fooDoc.set({foo: 1}); + await barDoc.set({bar: 1}); + + const query1 = collRef.firestore.collectionGroup(collectionGroupId); + const snapshot = await execute(db.pipeline().createFrom(query1)); + + verifyResults(snapshot, {bar: 1}, {foo: 1}); + }); + }); + + it('supports query over collection path with special characters', () => { + return testCollectionWithDocs({}, async (collRef, db) => { + const docWithSpecials = collRef.doc('so!@#$%^&*()_+special'); + + const collectionWithSpecials = docWithSpecials.collection( + 'so!@#$%^&*()_+special', + ); + await collectionWithSpecials.add({foo: 1}); + await collectionWithSpecials.add({foo: 2}); + + const snapshot = await execute( + db.pipeline().createFrom(collectionWithSpecials.orderBy('foo', 'asc')), + ); + + verifyResults(snapshot, {foo: 1}, {foo: 2}); + }); + }); + + it('supports multiple inequality on same field', () => { + return testCollectionWithDocs( + { + '01': {id: 1, foo: 1, bar: 1, baz: 1}, + '02': {id: 2, foo: 1, bar: 1, baz: 2}, + '03': {id: 3, foo: 1, bar: 1, baz: 2}, + '04': {id: 4, foo: 1, bar: 2, baz: 1}, + '05': {id: 5, foo: 1, bar: 2, baz: 2}, + '06': {id: 6, foo: 1, bar: 2, baz: 2}, + '07': {id: 7, foo: 2, bar: 1, baz: 1}, + '08': {id: 8, foo: 2, bar: 1, baz: 2}, + '09': {id: 9, foo: 2, bar: 1, baz: 2}, + '10': {id: 10, foo: 2, bar: 2, baz: 1}, + '11': {id: 11, foo: 2, bar: 2, baz: 2}, + '12': {id: 12, foo: 2, bar: 2, baz: 2}, + }, + async (collRef, db) => { + const query1 = collRef.where( + Filter.and(Filter.where('id', '>', 2), Filter.where('id', '<=', 10)), + ); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 3, foo: 1, bar: 1, baz: 2}, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 5, foo: 1, bar: 2, baz: 2}, + {id: 6, foo: 1, bar: 2, baz: 2}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 8, foo: 2, bar: 1, baz: 2}, + {id: 9, foo: 2, bar: 1, baz: 2}, + {id: 10, foo: 2, bar: 2, baz: 1}, + ); + }, + ); + }); + + it('supports multiple inequality on different fields', () => { + return testCollectionWithDocs( + { + '01': {id: 1, foo: 1, bar: 1, baz: 1}, + '02': {id: 2, foo: 1, bar: 1, baz: 2}, + '03': {id: 3, foo: 1, bar: 1, baz: 2}, + '04': {id: 4, foo: 1, bar: 2, baz: 1}, + '05': {id: 5, foo: 1, bar: 2, baz: 2}, + '06': {id: 6, foo: 1, bar: 2, baz: 2}, + '07': {id: 7, foo: 2, bar: 1, baz: 1}, + '08': {id: 8, foo: 2, bar: 1, baz: 2}, + '09': {id: 9, foo: 2, bar: 1, baz: 2}, + '10': {id: 10, foo: 2, bar: 2, baz: 1}, + '11': {id: 11, foo: 2, bar: 2, baz: 2}, + '12': {id: 12, foo: 2, bar: 2, baz: 2}, + }, + async (collRef, db) => { + const query1 = collRef.where( + Filter.and(Filter.where('id', '>=', 2), Filter.where('baz', '<', 2)), + ); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 10, foo: 2, bar: 2, baz: 1}, + ); + }, + ); + }); + + it('supports collectionGroup query', () => { + return testCollectionWithDocs({1: {foo: 1}}, async (collRef, db) => { + const snapshot = await execute( + db.pipeline().createFrom(db.collectionGroup(collRef.id)), + ); + verifyResults(snapshot, {foo: 1}); + }); + }); + + it('supports equal nan', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: NaN}, + 2: {foo: 2, bar: 1}, + 3: {foo: 3, bar: 'bar'}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', '==', NaN); + const classicSnapshot = await query1.get(); + const classicData = classicSnapshot.docs.map(d => d.data()); + + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, ...classicData); + }, + ); + }); + + it('supports notEqual nan', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: NaN}, + 2: {foo: 2, bar: 1}, + 3: {foo: 3, bar: 'bar'}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', '!=', NaN); + + const classicSnapshot = await query1.get(); + const classicData = classicSnapshot.docs.map(d => d.data()); + + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, ...classicData); + }, + ); + }); + + it('supports equal null', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: null}, + 2: {foo: 2, bar: 1}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', '==', null); + const classicSnapshot = await query1.get(); + const classicData = classicSnapshot.docs.map(d => d.data()); + + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, ...classicData); + }, + ); + }); + + it('supports notEqual null', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: null}, + 2: {foo: 2, bar: 1}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', '!=', null); + const classicSnapshot = await query1.get(); + const classicData = classicSnapshot.docs.map(d => d.data()); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, ...classicData); + }, + ); + }); + + it('supports notEqual', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 0}, + 2: {foo: 2, bar: 1}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', '!=', 0); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2, bar: 1}); + }, + ); + }); + + it('supports array contains', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: [0, 2, 4, 6]}, + 2: {foo: 2, bar: [1, 3, 5, 7]}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', 'array-contains', 4); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1, bar: [0, 2, 4, 6]}); + }, + ); + }); + + it('supports array contains any', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: [0, 2, 4, 6]}, + 2: {foo: 2, bar: [1, 3, 5, 7]}, + 3: {foo: 3, bar: [10, 20, 30, 40]}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', 'array-contains-any', [4, 5]); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {foo: 1, bar: [0, 2, 4, 6]}, + {foo: 2, bar: [1, 3, 5, 7]}, + ); + }, + ); + }); + + it('supports in', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 2}, + 2: {foo: 2}, + 3: {foo: 3, bar: 10}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', 'in', [0, 10, 20]); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 3, bar: 10}); + }, + ); + }); + + it('supports in with 1', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 2}, + 2: {foo: 2}, + 3: {foo: 3, bar: 10}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', 'in', [2]); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1, bar: 2}); + }, + ); + }); + + it('supports not in', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 2}, + 2: {foo: 2, bar: 1}, + 3: {foo: 3, bar: 10}, + }, + async (collRef, db) => { + const query1 = collRef + .where('bar', 'not-in', [0, 10, 20]) + .orderBy('foo'); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1, bar: 2}, {foo: 2, bar: 1}); + }, + ); + }); + + it('supports not in with 1', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 2}, + 2: {foo: 2}, + 3: {foo: 3, bar: 10}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', 'not-in', [2]); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}, {foo: 3, bar: 10}); + }, + ); + }); + + it('supports or operator', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 2}, + 2: {foo: 2, bar: 0}, + 3: {foo: 3, bar: 10}, + }, + async (collRef, db) => { + const query1 = collRef + .where( + Filter.or( + Filter.where('bar', '==', 2), + Filter.where('foo', '==', 3), + ), + ) + .orderBy('foo'); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1, bar: 2}, {foo: 3, bar: 10}); + }, + ); + }); +}); diff --git a/handwritten/firestore/dev/system-test/query.ts b/handwritten/firestore/dev/system-test/query.ts new file mode 100644 index 00000000000..14acbe69bce --- /dev/null +++ b/handwritten/firestore/dev/system-test/query.ts @@ -0,0 +1,2295 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { + DocumentData, + QuerySnapshot, + VectorValue, +} from '@google-cloud/firestore'; + +import {expect} from 'chai'; +import {afterEach, beforeEach, describe, it} from 'mocha'; +import '../test/util/mocha_extensions'; +import { + CollectionReference, + DocumentReference, + DocumentSnapshot, + FieldPath, + FieldValue, + Filter, + Firestore, + Query, + QueryDocumentSnapshot, + VectorQuery, + VectorQuerySnapshot, + setLogFunction, +} from '../src'; +import {verifyInstance} from '../test/util/helpers'; +import {DeferredPromise, getTestRoot} from './firestore'; +import {IndexTestHelper} from './index_test_helper'; + +describe.skipClassic('Query and Pipeline Compare - Enterprise DB', () => { + interface PaginatedResults { + pages: number; + docs: QueryDocumentSnapshot[]; + } + + let firestore: Firestore; + let randomCol: CollectionReference; + + const paginateResults = ( + query: Query, + startAfter?: unknown, + ): Promise => { + return (startAfter ? query.startAfter(startAfter) : query) + .get() + .then(snapshot => { + if (snapshot.empty) { + return {pages: 0, docs: []}; + } else { + const docs = snapshot.docs; + return paginateResults(query, docs[docs.length - 1]).then( + nextPage => { + return { + pages: nextPage.pages + 1, + docs: docs.concat(nextPage.docs), + }; + }, + ); + } + }); + }; + + async function addDocs( + ...docs: DocumentData[] + ): Promise { + let id = 0; // Guarantees consistent ordering for the first documents + const refs: DocumentReference[] = []; + for (const doc of docs) { + const ref = randomCol.doc('doc' + id++); + await ref.set(doc); + refs.push(ref); + } + return refs; + } + + async function testCollectionWithDocs(docs: { + [id: string]: DocumentData; + }): Promise> { + for (const id in docs) { + const ref = randomCol.doc(id); + await ref.set(docs[id]); + } + return randomCol; + } + + function expectDocs(result: QuerySnapshot, ...docs: string[]): void; + function expectDocs(result: QuerySnapshot, ...data: DocumentData[]): void; + + function expectDocs( + result: QuerySnapshot, + ...data: DocumentData[] | string[] + ): void { + expect(result.size).to.equal(data.length); + + if (data.length > 0) { + if (typeof data[0] === 'string') { + const actualIds = result.docs.map(docSnapshot => docSnapshot.id); + expect(actualIds).to.deep.equal(data); + } else { + result.forEach(doc => { + expect(doc.data()).to.deep.equal(data.shift()); + }); + } + } + } + + async function compareQueryAndPipeline(query: Query): Promise { + const queryResults = await query.get(); + const pipeline = query.firestore.pipeline().createFrom(query); + const pipelineResults = await pipeline.execute(); + + expect(pipelineResults.results.map(r => r._fieldsProto)).to.deep.equal( + queryResults.docs.map(s => s._fieldsProto), + ); + return queryResults; + } + + async function compareVectorQueryAndPipeline( + query: VectorQuery, + ): Promise { + const queryResults = await query.get(); + const pipeline = query.query.firestore.pipeline().createFrom(query); + const pipelineResults = await pipeline.execute(); + + expect(pipelineResults.results.map(r => r._fieldsProto)).to.deep.equal( + queryResults.docs.map(s => s._fieldsProto), + ); + return queryResults; + } + + beforeEach(() => { + randomCol = getTestRoot(); + firestore = randomCol.firestore; + }); + + afterEach(() => verifyInstance(firestore)); + + it('has firestore property', () => { + const ref = randomCol.limit(0); + expect(ref.firestore).to.be.an.instanceOf(Firestore); + }); + + it('has select() method', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar', bar: 'foo'}) + .then(() => { + return randomCol.select('foo').get(); + }) + .then(res => { + expect(res.docs[0].data()).to.deep.equal({foo: 'bar'}); + }); + }); + + it('select() supports empty fields', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar', bar: 'foo'}) + .then(() => { + return randomCol.select().get(); + }) + .then(res => { + expect(res.docs[0].ref.id).to.deep.equal('doc'); + expect(res.docs[0].data()).to.deep.equal({}); + }); + }); + + it('has where() method', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar'}) + .then(() => { + return compareQueryAndPipeline(randomCol.where('foo', '==', 'bar')); + }) + .then(res => { + expect(res.docs[0].data()).to.deep.equal({foo: 'bar'}); + }); + }); + + it('supports NaN and Null', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: NaN, bar: null}) + .then(() => { + return compareQueryAndPipeline( + randomCol.where('foo', '==', NaN).where('bar', '==', null), + ); + }) + .then(res => { + expect( + typeof res.docs[0].get('foo') === 'number' && + isNaN(res.docs[0].get('foo')), + ); + expect(res.docs[0].get('bar')).to.equal(null); + }); + }); + + it('supports array-contains', () => { + return Promise.all([ + randomCol.add({foo: ['bar']}), + randomCol.add({foo: []}), + ]) + .then(() => + compareQueryAndPipeline( + randomCol.where('foo', 'array-contains', 'bar'), + ), + ) + .then(res => { + expect(res.size).to.equal(1); + expect(res.docs[0].get('foo')).to.deep.equal(['bar']); + }); + }); + + it('supports findNearest by EUCLIDEAN distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(3); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([10, 0]))).to + .be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1]))).to + .be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0]))).to + .be.true; + }); + + it('supports findNearest by COSINE distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + '4': {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + '5': {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + '6': {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'COSINE', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + + expect(res.size).to.equal(3); + + if (res.docs[0].get('embedding').isEqual(FieldValue.vector([1, 1]))) { + expect( + res.docs[1].get('embedding').isEqual(FieldValue.vector([100, 100])), + ).to.be.true; + } else { + expect( + res.docs[0].get('embedding').isEqual(FieldValue.vector([100, 100])), + ).to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1]))).to + .be.true; + } + + expect( + res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0])) || + res.docs[2].get('embedding').isEqual(FieldValue.vector([10, 0])), + ).to.be.true; + }); + + it('supports findNearest by DOT_PRODUCT distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'DOT_PRODUCT', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(3); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([100, 100]))) + .to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([20, 0]))).to + .be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([10, 0]))).to + .be.true; + }); + + it('findNearest works with converters', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + class FooDistance { + constructor( + readonly foo: string, + readonly embedding: Array, + ) {} + } + + const fooConverter = { + toFirestore(d: FooDistance): DocumentData { + return {title: d.foo, embedding: FieldValue.vector(d.embedding)}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): FooDistance { + const data = snapshot.data(); + return new FooDistance(data.foo, data.embedding.toArray()); + }, + }; + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar', embedding: FieldValue.vector([5, 5])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .withConverter(fooConverter) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + + expect(res.size).to.equal(1); + expect(res.docs[0].data().foo).to.equal('bar'); + expect(res.docs[0].data().embedding).to.deep.equal([5, 5]); + }); + + it('supports findNearest skipping fields of wrong types', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + + // These documents are skipped because it is not really a vector value + {foo: 'bar', embedding: [10, 10]}, + {foo: 'bar', embedding: 'not actually a vector'}, + {foo: 'bar', embedding: null}, + + // Actual vector values + {foo: 'bar', embedding: FieldValue.vector([9, 9])}, + {foo: 'bar', embedding: FieldValue.vector([50, 50])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 100, // Intentionally large to get all matches. + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(3); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([9, 9]))).to + .be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([50, 50]))).to + .be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([100, 100]))) + .to.be.true; + }); + + it('findNearest ignores mismatching dimensions', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + + // Vectors with dimension mismatch + {foo: 'bar', embedding: FieldValue.vector([10])}, + + // Vectors with dimension match + {foo: 'bar', embedding: FieldValue.vector([9, 9])}, + {foo: 'bar', embedding: FieldValue.vector([50, 50])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(2); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([9, 9]))).to + .be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([50, 50]))).to + .be.true; + }); + + it('supports findNearest on non-existent field', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'bar', otherField: [10, 10]}, + {foo: 'bar', otherField: 'not actually a vector'}, + {foo: 'bar', otherField: null}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + + expect(res.size).to.equal(0); + }); + + it('supports findNearest on vector nested in a map', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {nested: {foo: 'bar'}}, + {nested: {foo: 'xxx', embedding: FieldValue.vector([10, 10])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([1, 1])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([10, 0])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([20, 0])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([100, 100])}}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest('nested.embedding', [10, 10], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(3); + expect( + res.docs[0].get('nested.embedding').isEqual(FieldValue.vector([10, 10])), + ).to.be.true; + expect( + res.docs[1].get('nested.embedding').isEqual(FieldValue.vector([10, 0])), + ).to.be.true; + expect( + res.docs[2].get('nested.embedding').isEqual(FieldValue.vector([1, 1])), + ).to.be.true; + }); + + it('supports findNearest with select to exclude vector data in response', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 1}, + {foo: 2, embedding: FieldValue.vector([10, 10])}, + {foo: 3, embedding: FieldValue.vector([1, 1])}, + {foo: 4, embedding: FieldValue.vector([10, 0])}, + {foo: 5, embedding: FieldValue.vector([20, 0])}, + {foo: 6, embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', 'in', [1, 2, 3, 4, 5, 6]) + .select('foo') + .findNearest('embedding', [10, 10], { + limit: 10, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(5); + expect(res.docs[0].get('foo')).to.equal(2); + expect(res.docs[1].get('foo')).to.equal(4); + expect(res.docs[2].get('foo')).to.equal(3); + expect(res.docs[3].get('foo')).to.equal(5); + expect(res.docs[4].get('foo')).to.equal(6); + + res.docs.forEach(ds => expect(ds.get('embedding')).to.be.undefined); + }); + + it('supports findNearest limits', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const embeddingVector = []; + const queryVector = []; + for (let i = 0; i < 2048; i++) { + embeddingVector.push(i + 1); + queryVector.push(i - 1); + } + + const collectionReference = await indexTestHelper.createTestDocs([ + {embedding: FieldValue.vector(embeddingVector)}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest('embedding', queryVector, { + limit: 1000, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(1); + expect( + (res.docs[0].get('embedding') as VectorValue).toArray(), + ).to.deep.equal(embeddingVector); + }); + + // TODO waiting on implicit sort order decision + it.skipEnterprise('supports !=', async () => { + await addDocs( + {zip: NaN}, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + {zip: null}, + ); + + let res = await compareQueryAndPipeline( + randomCol.where('zip', '!=', 98101), + ); + expectDocs( + res, + {zip: NaN}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + + res = await compareQueryAndPipeline(randomCol.where('zip', '!=', NaN)); + expectDocs( + res, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + + res = await compareQueryAndPipeline(randomCol.where('zip', '!=', null)); + expectDocs( + res, + {zip: NaN}, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + }); + + // TODO waiting on implicit sort order decision + it.skipEnterprise('supports != with document ID', async () => { + const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); + const res = await compareQueryAndPipeline( + randomCol.where(FieldPath.documentId(), '!=', refs[0].id), + ); + expectDocs(res, {count: 2}, {count: 3}); + }); + + it('supports not-in', async () => { + await addDocs( + {zip: 98101}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + let res = await compareQueryAndPipeline( + randomCol + .where('zip', 'not-in', [98101, 98103]) + .orderBy(FieldPath.documentId()), + ); + expectDocs( + res, + {zip: 91102}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + + res = await compareQueryAndPipeline( + randomCol + .where('zip', 'not-in', [NaN]) + .orderBy('zip') + .orderBy(FieldPath.documentId()), + ); + expectDocs( + res, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + + res = await compareQueryAndPipeline( + randomCol.where('zip', 'not-in', [null]).orderBy(FieldPath.documentId()), + ); + expectDocs( + res, + {zip: 98101}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + }); + + it('supports not-in with document ID array', async () => { + const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); + const res = await compareQueryAndPipeline( + randomCol.where(FieldPath.documentId(), 'not-in', [refs[0].id, refs[1]]), + ); + expectDocs(res, {count: 3}); + }); + + // TODO waiting on implicit sort order decision + it.skipEnterprise('supports "in"', async () => { + await addDocs( + {zip: 98101}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + const res = await compareQueryAndPipeline( + randomCol.where('zip', 'in', [98101, 98103]), + ); + expectDocs(res, {zip: 98101}, {zip: 98103}); + }); + + it('supports "in" with document ID array', async () => { + const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); + const res = await compareQueryAndPipeline( + randomCol.where(FieldPath.documentId(), 'in', [refs[0].id, refs[1]]), + ); + expectDocs(res, {count: 1}, {count: 2}); + }); + + // TODO waiting fix for `The function array_contains(...) requires `Array` but got `LONG`. + it.skipEnterprise('supports array-contains-any', async () => { + await addDocs( + {array: [42]}, + {array: ['a', 42, 'c']}, + {array: [41.999, '42', {a: [42]}]}, + {array: [42], array2: ['sigh']}, + {array: [43]}, + {array: [{a: 42}]}, + {array: 42}, + ); + + const res = await compareQueryAndPipeline( + randomCol.where('array', 'array-contains-any', [42, 43]), + ); + + expectDocs( + res, + {array: [42]}, + {array: ['a', 42, 'c']}, + { + array: [42], + array2: ['sigh'], + }, + {array: [43]}, + ); + }); + + it('can query by FieldPath.documentId()', () => { + const ref = randomCol.doc('foo'); + + return ref + .set({}) + .then(() => { + return compareQueryAndPipeline( + randomCol.where(FieldPath.documentId(), '>=', 'bar'), + ); + }) + .then(res => { + expect(res.docs.length).to.equal(1); + }); + }); + + it('has orderBy() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + + let res = await compareQueryAndPipeline(randomCol.orderBy('foo')); + expectDocs(res, {foo: 'a'}, {foo: 'b'}); + + res = await compareQueryAndPipeline(randomCol.orderBy('foo', 'desc')); + expectDocs(res, {foo: 'b'}, {foo: 'a'}); + }); + + it('can order by FieldPath.documentId()', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + return Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'b'})]) + .then(() => { + return compareQueryAndPipeline( + randomCol.orderBy(FieldPath.documentId()), + ); + }) + .then(res => { + expect(res.docs[0].data()).to.deep.equal({foo: 'a'}); + expect(res.docs[1].data()).to.deep.equal({foo: 'b'}); + }); + }); + + it('can run get() on empty collection', async () => { + return compareQueryAndPipeline(randomCol).then(res => { + return expect(res.empty); + }); + }); + + it('can run stream() on empty collection', async () => { + let received = 0; + const stream = randomCol.stream(); + + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(0); + }); + + it('has limit() method on get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await compareQueryAndPipeline( + randomCol.orderBy('foo').limit(1), + ); + expectDocs(res, {foo: 'a'}); + }); + + it('has limit() method on stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + + const stream = randomCol.orderBy('foo').limit(1).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(1); + }); + + it('can run limit(num), where num is larger than the collection size on get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await compareQueryAndPipeline( + randomCol.orderBy('foo').limit(3), + ); + expectDocs(res, {foo: 'a'}, {foo: 'b'}); + }); + + it('can run limit(num), where num is larger than the collection size on stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + + const stream = randomCol.orderBy('foo').limit(3).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(2); + }); + + it('has limitToLast() method', async () => { + await addDocs({doc: 1}, {doc: 2}, {doc: 3}); + // const res = await compareQueryAndPipeline(randomCol.orderBy('doc').limitToLast(2)); + const res = await randomCol.orderBy('doc').limitToLast(2).get(); + expectDocs(res, {doc: 2}, {doc: 3}); + }); + + it('limitToLast() supports Query cursors', async () => { + await addDocs({doc: 1}, {doc: 2}, {doc: 3}, {doc: 4}, {doc: 5}); + const res = await randomCol + .orderBy('doc') + .startAt(2) + .endAt(4) + .limitToLast(5) + .get(); + expectDocs(res, {doc: 2}, {doc: 3}, {doc: 4}); + }); + + it('can use offset() method with get()', async () => { + setLogFunction(console.log); + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await compareQueryAndPipeline( + randomCol.orderBy('foo').offset(1), + ); + expectDocs(res, {foo: 'b'}); + }); + + it('can use offset() method with stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + + const stream = randomCol.orderBy('foo').offset(1).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(1); + }); + + it('can run offset(num), where num is larger than the collection size on get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await compareQueryAndPipeline( + randomCol.orderBy('foo').offset(3), + ); + expect(res.empty); + }); + + it('can run offset(num), where num is larger than the collection size on stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + const stream = randomCol.orderBy('foo').offset(3).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + expect(received).to.equal(0); + }); + + it('supports Unicode in document names', async () => { + const collRef = randomCol.doc('доброеутро').collection('coll'); + await collRef.add({}); + const snapshot = await compareQueryAndPipeline(collRef); + expect(snapshot.size).to.equal(1); + }); + + it('supports pagination', () => { + const batch = firestore.batch(); + + for (let i = 0; i < 10; ++i) { + batch.set(randomCol.doc('doc' + i), {val: i}); + } + + const query = randomCol.orderBy('val').limit(3); + + return batch + .commit() + .then(() => paginateResults(query)) + .then(results => { + expect(results.pages).to.equal(4); + expect(results.docs).to.have.length(10); + }); + }); + + // TODO (enterprise) waiting for implicit sort order support + it('supports pagination with where() clauses', () => { + const batch = firestore.batch(); + + for (let i = 0; i < 10; ++i) { + batch.set(randomCol.doc('doc' + i), {val: i}); + } + + const query = randomCol + .where('val', '>=', 1) + .limit(3) + .orderBy('val') + .orderBy(FieldPath.documentId()); + + return batch + .commit() + .then(() => paginateResults(query)) + .then(results => { + expect(results.pages).to.equal(3); + expect(results.docs).to.have.length(9); + }); + }); + + it('supports pagination with array-contains filter', () => { + const batch = firestore.batch(); + + for (let i = 0; i < 10; ++i) { + batch.set(randomCol.doc('doc' + i), {array: ['foo']}); + } + + const query = randomCol.where('array', 'array-contains', 'foo').limit(3); + + return batch + .commit() + .then(() => paginateResults(query)) + .then(results => { + expect(results.pages).to.equal(4); + expect(results.docs).to.have.length(10); + }); + }); + + it('has startAt() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').startAt('b').get(); + expectDocs(res, {foo: 'b'}); + }); + + it('startAt() adds implicit order by for DocumentSnapshot', async () => { + const references = await addDocs({foo: 'a'}, {foo: 'b'}); + const docSnap = await references[1].get(); + const res = await randomCol.startAt(docSnap).get(); + expectDocs(res, {foo: 'b'}); + }); + + it('has startAfter() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').startAfter('a').get(); + expectDocs(res, {foo: 'b'}); + }); + + it('has endAt() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').endAt('b').get(); + expectDocs(res, {foo: 'a'}, {foo: 'b'}); + }); + + it('has endBefore() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').endBefore('b').get(); + expectDocs(res, {foo: 'a'}); + }); + + it('has stream() method', done => { + let received = 0; + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + void Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'b'})]).then(() => { + return randomCol + .stream() + .on('data', d => { + expect(d).to.be.an.instanceOf(DocumentSnapshot); + ++received; + }) + .on('end', () => { + expect(received).to.equal(2); + done(); + }); + }); + }); + + it('stream() supports readable[Symbol.asyncIterator]()', async () => { + let received = 0; + await randomCol.doc().set({foo: 'bar'}); + await randomCol.doc().set({foo: 'bar'}); + + const stream = randomCol.stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(2); + }); + + // TODO (enterprise) waiting on implicit sor order decision + it.skipEnterprise('can query collection groups', async () => { + // Use `randomCol` to get a random collection group name to use but ensure + // it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; + + const docPaths = [ + `abc/123/${collectionGroup}/cg-doc1`, + `abc/123/${collectionGroup}/cg-doc2`, + `${collectionGroup}/cg-doc3`, + `${collectionGroup}/cg-doc4`, + `def/456/${collectionGroup}/cg-doc5`, + `${collectionGroup}/virtual-doc/nested-coll/not-cg-doc`, + `x${collectionGroup}/not-cg-doc`, + `${collectionGroup}x/not-cg-doc`, + `abc/123/${collectionGroup}x/not-cg-doc`, + `abc/123/x${collectionGroup}/not-cg-doc`, + `abc/${collectionGroup}`, + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); + + const querySnapshot = await compareQueryAndPipeline( + firestore.collectionGroup(collectionGroup), + ); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc1', + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + 'cg-doc5', + ]); + }); + + // TODO (enterprise) wait for implicit sort order support + it.skipEnterprise( + 'can query collection groups with startAt / endAt by arbitrary documentId', + async () => { + // Use `randomCol` to get a random collection group name to use but + // ensure it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; + + const docPaths = [ + `a/a/${collectionGroup}/cg-doc1`, + `a/b/a/b/${collectionGroup}/cg-doc2`, + `a/b/${collectionGroup}/cg-doc3`, + `a/b/c/d/${collectionGroup}/cg-doc4`, + `a/c/${collectionGroup}/cg-doc5`, + `${collectionGroup}/cg-doc6`, + 'a/b/nope/nope', + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); + + let querySnapshot = await firestore + .collectionGroup(collectionGroup) + .orderBy(FieldPath.documentId()) + .startAt('a/b') + .endAt('a/b0') + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + ]); + + querySnapshot = await firestore + .collectionGroup(collectionGroup) + .orderBy(FieldPath.documentId()) + .startAfter('a/b') + .endBefore(`a/b/${collectionGroup}/cg-doc3`) + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); + }, + ); + + // TODO (enterprise) wait for implicit sort order support + it.skipEnterprise( + 'can query collection groups with where filters on arbitrary documentId', + async () => { + // Use `randomCol` to get a random collection group name to use but + // ensure it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; + + const docPaths = [ + `a/a/${collectionGroup}/cg-doc1`, + `a/b/a/b/${collectionGroup}/cg-doc2`, + `a/b/${collectionGroup}/cg-doc3`, + `a/b/c/d/${collectionGroup}/cg-doc4`, + `a/c/${collectionGroup}/cg-doc5`, + `${collectionGroup}/cg-doc6`, + 'a/b/nope/nope', + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); + + let querySnapshot = await compareQueryAndPipeline( + firestore + .collectionGroup(collectionGroup) + .where(FieldPath.documentId(), '>=', 'a/b') + .where(FieldPath.documentId(), '<=', 'a/b0'), + ); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + ]); + + querySnapshot = await compareQueryAndPipeline( + firestore + .collectionGroup(collectionGroup) + .where(FieldPath.documentId(), '>', 'a/b') + .where(FieldPath.documentId(), '<', `a/b/${collectionGroup}/cg-doc3`), + ); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); + }, + ); + + it('can query large collections', async () => { + // @grpc/grpc-js v0.4.1 failed to deliver the full set of query results for + // larger collections (https://github.com/grpc/grpc-node/issues/895); + const batch = firestore.batch(); + for (let i = 0; i < 100; ++i) { + batch.create(randomCol.doc(), {}); + } + await batch.commit(); + + const snapshot = await compareQueryAndPipeline(randomCol); + expect(snapshot.size).to.equal(100); + }); + + // TODO (enterprise) wait for implicit sort order support + it.skipEnterprise('supports OR queries', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {a: 2, b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1, b: 1}, + }); + + // Two equalities: a==1 || b==1. + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), + ), + ), + 'doc1', + 'doc2', + 'doc4', + 'doc5', + ); + + // (a==1 && b==0) || (a==3 && b==2) + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or( + Filter.and(Filter.where('a', '==', 1), Filter.where('b', '==', 0)), + Filter.and(Filter.where('a', '==', 3), Filter.where('b', '==', 2)), + ), + ), + ), + 'doc1', + 'doc3', + ); + + // a==1 && (b==0 || b==3). + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.and( + Filter.where('a', '==', 1), + Filter.or(Filter.where('b', '==', 0), Filter.where('b', '==', 3)), + ), + ), + ), + 'doc1', + 'doc4', + ); + + // (a==2 || b==2) && (a==3 || b==3) + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.and( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 2)), + Filter.or(Filter.where('a', '==', 3), Filter.where('b', '==', 3)), + ), + ), + ), + 'doc3', + ); + + // Test with limits without orderBy (the __name__ ordering is the tie breaker). + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), + ) + .limit(1), + ), + 'doc2', + ); + }); + + // Skip this test if running against production because it results in a 'missing index' error. + // The Firestore Emulator, however, does serve these queries. + // TODO (enterprise) wait for implicit sort order support + it.skipEnterprise('supports OR queries with composite indexes', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {a: 2, b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1, b: 1}, + }); + + // with one inequality: a>2 || b==1. + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), + ), + ), + 'doc5', + 'doc2', + 'doc3', + ); + + // Test with limits (implicit order by ASC): (a==1) || (b > 0) LIMIT 2 + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)), + ) + .limit(2), + ), + 'doc1', + 'doc2', + ); + + // Test with limits (explicit order by): (a==1) || (b > 0) LIMIT_TO_LAST 2 + // Note: The public query API does not allow implicit ordering when limitToLast is used. + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)), + ) + .limitToLast(2) + .orderBy('b'), + ), + 'doc3', + 'doc4', + ); + + // Test with limits (explicit order by ASC): (a==2) || (b == 1) ORDER BY a LIMIT 1 + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), + ) + .limit(1) + .orderBy('a'), + ), + 'doc5', + ); + + // Test with limits (explicit order by DESC): (a==2) || (b == 1) ORDER BY a LIMIT 1 + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), + ) + .limit(1) + .orderBy('a', 'desc'), + ), + 'doc2', + ); + }); + + it('supports OR queries on documents with missing fields', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==1 || b==1 + // There's no explicit nor implicit orderBy. Documents with missing 'a' or missing 'b' should be + // allowed if the document matches at least one disjunction term. + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), + ) + .orderBy(FieldPath.documentId()), + ), + 'doc1', + 'doc2', + 'doc4', + 'doc5', + ); + }); + + // Skip this test if running against production because it results in a 'missing index' error. + // TODO (enterprise) wait for implicit sort order support + it.skip('supports OR queries on documents with missing fields', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==1 || b==1 order by a. + // doc2 should not be included because it's missing the field 'a', and we have "orderBy a". + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), + ) + .orderBy('a'), + ), + 'doc1', + 'doc4', + 'doc5', + ); + + // Query: a==1 || b==1 order by b. + // doc5 should not be included because it's missing the field 'b', and we have "orderBy b". + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), + ) + .orderBy('b'), + ), + 'doc1', + 'doc2', + 'doc4', + ); + + // Query: a>2 || b==1. + // This query has an implicit 'order by a'. + // doc2 should not be included because it's missing the field 'a'. + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), + ), + ), + 'doc3', + ); + + // Query: a>1 || b==1 order by a order by b. + // doc6 should not be included because it's missing the field 'b'. + // doc2 should not be included because it's missing the field 'a'. + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '>', 1), Filter.where('b', '==', 1)), + ) + .orderBy('a') + .orderBy('b'), + ), + 'doc3', + ); + }); + + it('supports OR queries with in', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==2 || b in [2, 3] + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'in', [2, 3]), + ), + ) + .orderBy(FieldPath.documentId()), + ), + 'doc3', + 'doc4', + 'doc6', + ); + }); + + // Skip this test if running against production because it results in a 'missing index' error. + it('supports OR queries with not-in', async () => { + setLogFunction(console.log); + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // a==2 || (b != 2 && b != 3) + // Has implicit "orderBy b" + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'not-in', [2, 3]), + ), + ) + .orderBy(FieldPath.documentId()), + ), + 'doc1', + 'doc2', + 'doc5', + 'doc6', + ); + }); + + // TODO (enterprise) wait for implicit sort order support + it.skipEnterprise('supports OR queries with array membership', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: [0]}, + doc2: {b: [1]}, + doc3: {a: 3, b: [2, 7]}, + doc4: {a: 1, b: [3, 7]}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==2 || b array-contains 7 + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'array-contains', 7), + ), + ), + ), + 'doc3', + 'doc4', + 'doc6', + ); + + // a==2 || b array-contains-any [0, 3] + // Has implicit "orderBy b" + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'array-contains-any', [0, 3]), + ), + ), + ), + 'doc1', + 'doc4', + 'doc6', + ); + }); + + describe('watch', () => { + interface ExpectedChange { + type: string; + doc: DocumentSnapshot; + } + + const currentDeferred = new DeferredPromise(); + + const snapshot = (id: string, data: DocumentData) => { + const ref = randomCol.doc(id); + const fields = ref.firestore._serializer!.encodeFields(data); + return randomCol.firestore.snapshot_( + { + name: + 'projects/ignored/databases/(default)/documents/' + + ref._path.relativeName, + fields, + createTime: {seconds: 0, nanos: 0}, + updateTime: {seconds: 0, nanos: 0}, + }, + {seconds: 0, nanos: 0}, + ); + }; + + const docChange = ( + type: string, + id: string, + data: DocumentData, + ): ExpectedChange => { + return { + type, + doc: snapshot(id, data), + }; + }; + + const added = (id: string, data: DocumentData) => + docChange('added', id, data); + const modified = (id: string, data: DocumentData) => + docChange('modified', id, data); + const removed = (id: string, data: DocumentData) => + docChange('removed', id, data); + + function resetPromise() { + currentDeferred.promise = new Promise((resolve, reject) => { + currentDeferred.resolve = resolve; + currentDeferred.reject = reject; + }); + } + + function waitForSnapshot(): Promise { + return currentDeferred.promise!.then(snapshot => { + resetPromise(); + return snapshot; + }); + } + + function snapshotsEqual( + actual: QuerySnapshot, + expected: {docs: DocumentSnapshot[]; docChanges: ExpectedChange[]}, + ) { + let i; + expect(actual.size).to.equal(expected.docs.length); + for (i = 0; i < expected.docs.length && i < actual.size; i++) { + expect(actual.docs[i].ref.id).to.equal(expected.docs[i].ref.id); + expect(actual.docs[i].data()).to.deep.equal(expected.docs[i].data()); + } + const actualDocChanges = actual.docChanges(); + expect(actualDocChanges.length).to.equal(expected.docChanges.length); + for (i = 0; i < expected.docChanges.length; i++) { + expect(actualDocChanges[i].type).to.equal(expected.docChanges[i].type); + expect(actualDocChanges[i].doc.ref.id).to.equal( + expected.docChanges[i].doc.ref.id, + ); + expect(actualDocChanges[i].doc.data()).to.deep.equal( + expected.docChanges[i].doc.data(), + ); + expect(actualDocChanges[i].doc.readTime).to.exist; + expect(actualDocChanges[i].doc.createTime).to.exist; + expect(actualDocChanges[i].doc.updateTime).to.exist; + } + expect(actual.readTime).to.exist; + } + + beforeEach(() => resetPromise()); + + it('handles changing a doc', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + const unsubscribe = randomCol.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject!(err); + }, + ); + + return waitForSnapshot() + .then(results => { + snapshotsEqual(results, {docs: [], docChanges: []}); + // Add a result. + return ref1.set({foo: 'a'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {foo: 'a'})], + docChanges: [added('doc1', {foo: 'a'})], + }); + // Add another result. + return ref2.set({foo: 'b'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {foo: 'a'}), snapshot('doc2', {foo: 'b'})], + docChanges: [added('doc2', {foo: 'b'})], + }); + // Change a result. + return ref2.set({bar: 'c'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {foo: 'a'}), snapshot('doc2', {bar: 'c'})], + docChanges: [modified('doc2', {bar: 'c'})], + }); + unsubscribe(); + }); + }); + + it("handles changing a doc so it doesn't match", () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + const query = randomCol.where('included', '==', 'yes'); + const unsubscribe = query.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject(err); + }, + ); + + return waitForSnapshot() + .then(results => { + snapshotsEqual(results, {docs: [], docChanges: []}); + // Add a result. + return ref1.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [added('doc1', {included: 'yes'})], + }); + // Add another result. + return ref2.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [ + snapshot('doc1', {included: 'yes'}), + snapshot('doc2', {included: 'yes'}), + ], + docChanges: [added('doc2', {included: 'yes'})], + }); + // Change a result. + return ref2.set({included: 'no'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [removed('doc2', {included: 'yes'})], + }); + unsubscribe(); + }); + }); + + it('handles deleting a doc', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + const unsubscribe = randomCol.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject(err); + }, + ); + + return waitForSnapshot() + .then(results => { + snapshotsEqual(results, {docs: [], docChanges: []}); + // Add a result. + return ref1.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [added('doc1', {included: 'yes'})], + }); + // Add another result. + return ref2.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [ + snapshot('doc1', {included: 'yes'}), + snapshot('doc2', {included: 'yes'}), + ], + docChanges: [added('doc2', {included: 'yes'})], + }); + // Delete a result. + return ref2.delete(); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [removed('doc2', {included: 'yes'})], + }); + unsubscribe(); + }); + }); + + it('orders limitToLast() correctly', async () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + const ref3 = randomCol.doc('doc3'); + + await ref1.set({doc: 1}); + await ref2.set({doc: 2}); + await ref3.set({doc: 3}); + + const unsubscribe = randomCol + .orderBy('doc') + .limitToLast(2) + .onSnapshot(snapshot => currentDeferred.resolve(snapshot)); + + const results = await waitForSnapshot(); + snapshotsEqual(results, { + docs: [snapshot('doc2', {doc: 2}), snapshot('doc3', {doc: 3})], + docChanges: [added('doc2', {doc: 2}), added('doc3', {doc: 3})], + }); + + unsubscribe(); + }); + + it('SDK orders vector field same way as backend', async () => { + // We validate that the SDK orders the vector field the same way as the backend + // by comparing the sort order of vector fields from a Query.get() and + // Query.onSnapshot(). Query.onSnapshot() will return sort order of the SDK, + // and Query.get() will return sort order of the backend. + + // Test data in the order that we expect the backend to sort it. + const docsInOrder = [ + {embedding: [1, 2, 3, 4, 5, 6]}, + {embedding: [100]}, + {embedding: FieldValue.vector([Number.NEGATIVE_INFINITY])}, + {embedding: FieldValue.vector([-100])}, + {embedding: FieldValue.vector([100])}, + {embedding: FieldValue.vector([Number.POSITIVE_INFINITY])}, + {embedding: FieldValue.vector([1, 2])}, + {embedding: FieldValue.vector([2, 2])}, + {embedding: FieldValue.vector([1, 2, 3])}, + {embedding: FieldValue.vector([1, 2, 3, 4])}, + {embedding: FieldValue.vector([1, 2, 3, 4, 5])}, + {embedding: FieldValue.vector([1, 2, 100, 4, 4])}, + {embedding: FieldValue.vector([100, 2, 3, 4, 5])}, + {embedding: {HELLO: 'WORLD'}}, + {embedding: {hello: 'world'}}, + ]; + + const expectedSnapshots = []; + const expectedChanges = []; + + for (let i = 0; i < docsInOrder.length; i++) { + const dr = await randomCol.add(docsInOrder[i]); + expectedSnapshots.push(snapshot(dr.id, docsInOrder[i])); + expectedChanges.push(added(dr.id, docsInOrder[i])); + } + + const orderedQuery = randomCol.orderBy('embedding'); + + const unsubscribe = orderedQuery.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject!(err); + }, + ); + + const watchSnapshot = await waitForSnapshot(); + unsubscribe(); + + const getSnapshot = await orderedQuery.get(); + + // Compare the snapshot (including sort order) of a snapshot + // from Query.onSnapshot() to an actual snapshot from Query.get() + snapshotsEqual(watchSnapshot, { + docs: getSnapshot.docs, + docChanges: getSnapshot.docChanges(), + }); + + // Compare the snapshot (including sort order) of a snapshot + // from Query.onSnapshot() to the expected sort order from + // the backend. + snapshotsEqual(watchSnapshot, { + docs: expectedSnapshots, + docChanges: expectedChanges, + }); + }); + }); + + (process.env.FIRESTORE_EMULATOR_HOST === undefined + ? describe.skip + : describe)('multiple inequality', () => { + it('supports multiple inequality queries', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 0}, + doc2: {key: 'b', sort: 3, v: 1}, + doc3: {key: 'c', sort: 1, v: 3}, + doc4: {key: 'd', sort: 2, v: 2}, + }); + + // Multiple inequality fields + let results = await compareQueryAndPipeline( + collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .where('v', '>', 2), + ); + expectDocs(results, 'doc3'); + + // Duplicate inequality fields + results = await compareQueryAndPipeline( + collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .where('sort', '>', 1), + ); + expectDocs(results, 'doc4'); + + // With multiple IN + results = await compareQueryAndPipeline( + collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .where('v', 'in', [2, 3, 4]) + .where('sort', 'in', [2, 3]), + ); + expectDocs(results, 'doc4'); + + // With NOT-IN + results = await compareQueryAndPipeline( + collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .where('v', 'not-in', [2, 4, 5]), + ); + expectDocs(results, 'doc1', 'doc3'); + + // With orderby + results = await compareQueryAndPipeline( + collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .orderBy('v', 'desc'), + ); + expectDocs(results, 'doc3', 'doc4', 'doc1'); + + // With limit + results = await compareQueryAndPipeline( + collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .orderBy('v', 'desc') + .limit(2), + ); + expectDocs(results, 'doc3', 'doc4'); + + // With limitToLast + results = await compareQueryAndPipeline( + collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .orderBy('v', 'desc') + .limitToLast(2), + ); + expectDocs(results, 'doc4', 'doc1'); + }); + + it('can use on special values', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 0}, + doc2: {key: 'b', sort: NaN, v: 1}, + doc3: {key: 'c', sort: null, v: 3}, + doc4: {key: 'd', v: 0}, + doc5: {key: 'e', sort: 1}, + doc6: {key: 'f', sort: 1, v: 1}, + }); + + let results = await compareQueryAndPipeline( + collection.where('key', '!=', 'a').where('sort', '<=', 2), + ); + expectDocs(results, 'doc5', 'doc6'); + + results = await compareQueryAndPipeline( + collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .where('v', '<=', 1), + ); + expectDocs(results, 'doc6'); + }); + + it('can use with array membership', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: [0]}, + doc2: {key: 'b', sort: 1, v: [0, 1, 3]}, + doc3: {key: 'c', sort: 1, v: []}, + doc4: {key: 'd', sort: 2, v: [1]}, + doc5: {key: 'e', sort: 3, v: [2, 4]}, + doc6: {key: 'f', sort: 4, v: [NaN]}, + doc7: {key: 'g', sort: 4, v: [null]}, + }); + + let results = await compareQueryAndPipeline( + collection + .where('key', '!=', 'a') + .where('sort', '>=', 1) + .where('v', 'array-contains', 0), + ); + expectDocs(results, 'doc2'); + + results = await compareQueryAndPipeline( + collection + .where('key', '!=', 'a') + .where('sort', '>=', 1) + .where('v', 'array-contains-any', [0, 1]), + ); + expectDocs(results, 'doc2', 'doc4'); + }); + + // Use cursor in following test cases to add implicit order by fields in the sdk and compare the + // result with the query fields normalized in the server. + it('can use with nested field', async () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const testData = (n?: number): any => { + n = n || 1; + return { + name: 'room ' + n, + metadata: { + createdAt: n, + }, + field: 'field ' + n, + 'field.dot': n, + 'field\\slash': n, + }; + }; + + const collection = await testCollectionWithDocs({ + doc1: testData(400), + doc2: testData(200), + doc3: testData(100), + doc4: testData(300), + }); + + // ordered by: name asc, metadata.createdAt asc, __name__ asc + let query = collection + .where('metadata.createdAt', '<=', 500) + .where('metadata.createdAt', '>', 100) + .where('name', '!=', 'room 200') + .orderBy('name'); + let docSnap = await collection.doc('doc4').get(); + let queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc4', 'doc1'); + expectDocs(await queryWithCursor.get(), 'doc4', 'doc1'); + + // ordered by: name desc, field desc, field.dot desc, field\\slash desc, __name__ desc + query = collection + .where('field', '>=', 'field 100') + .where(new FieldPath('field.dot'), '!=', 300) + .where('field\\slash', '<', 400) + .orderBy('name', 'desc'); + docSnap = await collection.doc('doc2').get(); + queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc2', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc3'); + }); + + it('can use with nested composite filters', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 5}, + doc2: {key: 'aa', sort: 4, v: 4}, + doc3: {key: 'c', sort: 3, v: 3}, + doc4: {key: 'b', sort: 2, v: 2}, + doc5: {key: 'b', sort: 2, v: 1}, + doc6: {key: 'b', sort: 0, v: 0}, + }); + + // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc + let query = collection.where( + Filter.or( + Filter.and( + Filter.where('key', '==', 'b'), + Filter.where('sort', '<=', 2), + ), + Filter.and(Filter.where('key', '!=', 'b'), Filter.where('v', '>', 4)), + ), + ); + let docSnap = await collection.doc('doc1').get(); + let queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc1', + 'doc6', + 'doc5', + 'doc4', + ); + expectDocs(await queryWithCursor.get(), 'doc1', 'doc6', 'doc5', 'doc4'); + + // Ordered by: 'sort' desc, 'key' asc, 'v' asc, __name__ asc + query = collection + .where( + Filter.or( + Filter.and( + Filter.where('key', '==', 'b'), + Filter.where('sort', '<=', 2), + ), + Filter.and( + Filter.where('key', '!=', 'b'), + Filter.where('v', '>', 4), + ), + ), + ) + .orderBy('sort', 'desc') + .orderBy('key'); + docSnap = await collection.doc('doc5').get(); + queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc5', + 'doc4', + 'doc1', + 'doc6', + ); + expectDocs(await queryWithCursor.get(), 'doc5', 'doc4', 'doc1', 'doc6'); + + // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc + query = collection.where( + Filter.and( + Filter.or( + Filter.and( + Filter.where('key', '==', 'b'), + Filter.where('sort', '<=', 4), + ), + Filter.and( + Filter.where('key', '!=', 'b'), + Filter.where('v', '>=', 4), + ), + ), + Filter.or( + Filter.and( + Filter.where('key', '>', 'b'), + Filter.where('sort', '>=', 1), + ), + Filter.and( + Filter.where('key', '<', 'b'), + Filter.where('v', '>', 0), + ), + ), + ), + ); + docSnap = await collection.doc('doc1').get(); + queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc1', 'doc2'); + expectDocs(await queryWithCursor.get(), 'doc1', 'doc2'); + }); + + it('inequality fields will be implicitly ordered lexicographically by the server', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 5}, + doc2: {key: 'aa', sort: 4, v: 4}, + doc3: {key: 'b', sort: 3, v: 3}, + doc4: {key: 'b', sort: 2, v: 2}, + doc5: {key: 'b', sort: 2, v: 1}, + doc6: {key: 'b', sort: 0, v: 0}, + }); + + const docSnap = await collection.doc('doc2').get(); + + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + let query = collection + .where('key', '!=', 'a') + .where('sort', '>', 1) + .where('v', 'in', [1, 2, 3, 4]); + let queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc2', + 'doc4', + 'doc5', + 'doc3', + ); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc5', 'doc3'); + + // Changing filters order will not effect implicit order. + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + query = collection + .where('sort', '>', 1) + .where('key', '!=', 'a') + .where('v', 'in', [1, 2, 3, 4]); + queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc2', + 'doc4', + 'doc5', + 'doc3', + ); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc5', 'doc3'); + }); + + it('can use multiple explicit order by field', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 5, v: 0}, + doc2: {key: 'aa', sort: 4, v: 0}, + doc3: {key: 'b', sort: 3, v: 1}, + doc4: {key: 'b', sort: 2, v: 1}, + doc5: {key: 'bb', sort: 1, v: 1}, + doc6: {key: 'c', sort: 0, v: 2}, + }); + + let docSnap = await collection.doc('doc2').get(); + + // Ordered by: 'v' asc, 'key' asc, 'sort' asc, __name__ asc + let query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v'); + let queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc2', + 'doc4', + 'doc3', + 'doc5', + ); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3', 'doc5'); + + // Ordered by: 'v asc, 'sort' asc, 'key' asc, __name__ asc + query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v') + .orderBy('sort'); + queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc2', + 'doc5', + 'doc4', + 'doc3', + ); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc5', 'doc4', 'doc3'); + + docSnap = await collection.doc('doc5').get(); + + // Implicit order by matches the direction of last explicit order by. + // Ordered by: 'v' desc, 'key' desc, 'sort' desc, __name__ desc + query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v', 'desc'); + queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc5', + 'doc3', + 'doc4', + 'doc2', + ); + expectDocs(await queryWithCursor.get(), 'doc5', 'doc3', 'doc4', 'doc2'); + + // Ordered by: 'v desc, 'sort' asc, 'key' asc, __name__ asc + query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v', 'desc') + .orderBy('sort'); + queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc5', + 'doc4', + 'doc3', + 'doc2', + ); + expectDocs(await queryWithCursor.get(), 'doc5', 'doc4', 'doc3', 'doc2'); + }); + + it('can use in aggregate query', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 5, v: 0}, + doc2: {key: 'aa', sort: 4, v: 0}, + doc3: {key: 'b', sort: 3, v: 1}, + doc4: {key: 'b', sort: 2, v: 1}, + doc5: {key: 'bb', sort: 1, v: 1}, + }); + + const results = await collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v') + .count() + .get(); + expect(results.data().count).to.be.equal(4); + //TODO(MIEQ): Add sum and average when they are public. + }); + + it('can use document ID im multiple inequality query', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 5}, + doc2: {key: 'aa', sort: 4}, + doc3: {key: 'b', sort: 3}, + doc4: {key: 'b', sort: 2}, + doc5: {key: 'bb', sort: 1}, + }); + + const docSnap = await collection.doc('doc2').get(); + + // Document Key in inequality field will implicitly ordered to the last. + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + let query = collection + .where('sort', '>=', 1) + .where('key', '!=', 'a') + .where(FieldPath.documentId(), '<', 'doc5'); + let queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc2', 'doc4', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3'); + + // Changing filters order will not effect implicit order. + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + query = collection + .where(FieldPath.documentId(), '<', 'doc5') + .where('sort', '>=', 1) + .where('key', '!=', 'a'); + queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc2', 'doc4', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3'); + + // Ordered by: 'sort' desc,'key' desc, __name__ desc + query = collection + .where(FieldPath.documentId(), '<', 'doc5') + .where('sort', '>=', 1) + .where('key', '!=', 'a') + .orderBy('sort', 'desc'); + queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc2', 'doc3', 'doc4'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc3', 'doc4'); + }); + }); +}); diff --git a/handwritten/firestore/dev/system-test/tracing.ts b/handwritten/firestore/dev/system-test/tracing.ts new file mode 100644 index 00000000000..5af3a29f887 --- /dev/null +++ b/handwritten/firestore/dev/system-test/tracing.ts @@ -0,0 +1,1071 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import * as chaiAsPromised from 'chai-as-promised'; +import {expect, use} from 'chai'; +import {describe, it, beforeEach, afterEach, Test} from 'mocha'; +import { + Attributes, + context, + diag, + DiagConsoleLogger, + DiagLogLevel, + ROOT_CONTEXT, + SpanContext, + trace, + TraceFlags, + Tracer, + TracerProvider, + Context as OpenTelemetryContext, +} from '@opentelemetry/api'; +import {TraceExporter} from '@google-cloud/opentelemetry-cloud-trace-exporter'; +import {FirestoreOpenTelemetryOptions, Settings} from '@google-cloud/firestore'; +import { + AlwaysOnSampler, + BatchSpanProcessor, + ConsoleSpanExporter, + InMemorySpanExporter, + NodeTracerProvider, + ReadableSpan, + SpanProcessor, + TimedEvent, +} from '@opentelemetry/sdk-trace-node'; +import {setLogFunction, Firestore} from '../src'; +import {verifyInstance} from '../test/util/helpers'; +import { + ATTRIBUTE_GCP_RESOURCE_NAME, + ATTRIBUTE_KEY_DOC_COUNT, + ATTRIBUTE_SETTINGS_PREFIX, + SPAN_NAME_AGGREGATION_QUERY_GET, + SPAN_NAME_BATCH_COMMIT, + SPAN_NAME_BATCH_GET_DOCUMENTS, + SPAN_NAME_BULK_WRITER_COMMIT, + SPAN_NAME_COL_REF_ADD, + SPAN_NAME_COL_REF_LIST_DOCUMENTS, + SPAN_NAME_DOC_REF_CREATE, + SPAN_NAME_DOC_REF_DELETE, + SPAN_NAME_DOC_REF_GET, + SPAN_NAME_DOC_REF_LIST_COLLECTIONS, + SPAN_NAME_DOC_REF_SET, + SPAN_NAME_DOC_REF_UPDATE, + SPAN_NAME_PARTITION_QUERY, + SPAN_NAME_QUERY_GET, + SPAN_NAME_TRANSACTION_COMMIT, + SPAN_NAME_TRANSACTION_GET_AGGREGATION_QUERY, + SPAN_NAME_TRANSACTION_GET_DOCUMENT, + SPAN_NAME_TRANSACTION_GET_DOCUMENTS, + SPAN_NAME_TRANSACTION_GET_QUERY, + SPAN_NAME_TRANSACTION_RUN, +} from '../src/telemetry/trace-util'; +import {AsyncLocalStorageContextManager} from '@opentelemetry/context-async-hooks'; +import {cloudtrace_v1, auth as gAuth} from '@googleapis/cloudtrace'; +import Schema$Trace = cloudtrace_v1.Schema$Trace; +import Schema$TraceSpan = cloudtrace_v1.Schema$TraceSpan; +import {logger} from '../src/logger'; + +use(chaiAsPromised); + +const NUM_TRACE_ID_BYTES = 32; +const NUM_SPAN_ID_BYTES = 16; +const SPAN_NAME_TEST_ROOT = 'TestRootSpan'; +const GET_TRACE_INITIAL_WAIT_MILLIS = 2000; +const GET_TRACE_RETRY_BACKOFF_MILLIS = 2000; +const GET_TRACE_MAX_RETRY_COUNT = 10; + +const E2E_TEST_SUITE_TITLE = 'E2E'; +const IN_MEMORY_TEST_SUITE_TITLE = 'IN-MEMORY'; +const GLOBAL_OTEL_TEST_SUITE_TITLE = 'GLOBAL-OTEL'; +const NON_GLOBAL_OTEL_TEST_SUITE_TITLE = 'NON-GLOBAL-OTEL'; +const GRPC_TEST_SUITE_TITLE = 'GRPC'; +const REST_TEST_SUITE_TITLE = 'REST'; + +// Enable OpenTelemetry debug message for local debugging. +diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG); + +// Enable Firestore debug messages for local debugging. +if (process.env.NODE_ENV === 'DEBUG') { + setLogFunction((msg: string) => { + console.log(`LOG: ${msg}`); + }); +} + +interface TestConfig { + // In-Memory tests check trace correctness by inspecting traces in memory by + // utilizing InMemorySpanExporter. These tests have `e2e` set to `false`. + // End-to-End tests check trace correctness by querying the Google Cloud Trace + // backend and making sure it has recorded all the expected spans. These + // tests have `e2e` set to `true`. + e2e: boolean; + + // OpenTelemetry allows registering a specific OpenTelemetry instance as the + // "global" instance. We should make sure that the tracing works in two + // circumstances: (1) the user provides us with a specific OpenTelemetry + // instance. (2) the user does not provide an instance and we find the + // global instance to use. + useGlobalOpenTelemetry: boolean; + + // Whether the Firestore instance should use gRPC or REST. + preferRest: boolean; +} + +// Unfortunately the in-memory spans and Cloud Trace spans do not share the +// same data-structures. This interface is useful to abstract that away for +// testing. +// Also note that Cloud Trace currently does NOT return span attributes nor +// span events. So we'll have to leave those as empty and not check them for +// end-to-end tests. +class SpanData { + constructor( + public id: string | null | undefined, + public parentId: string | null | undefined, + public traceId: string, + public name: string | null | undefined, + public attributes: Attributes, + public events: TimedEvent[], + ) {} + static fromInMemorySpan(span: ReadableSpan): SpanData { + return new SpanData( + span.spanContext().spanId, + span.parentSpanContext?.spanId, + span.spanContext().traceId, + span.name, + span.attributes, + span.events, + ); + } + + static fromCloudTraceSpan(span: Schema$TraceSpan, traceId: string): SpanData { + return new SpanData( + span.spanId, + span.parentSpanId, + traceId, + span.name, + {}, + [], + ); + } +} + +describe.skipEnterprise('Tracing Tests', () => { + let firestore: Firestore; + let tracerProvider: NodeTracerProvider; + let inMemorySpanExporter: InMemorySpanExporter; + let consoleSpanExporter: ConsoleSpanExporter; + let gcpTraceExporter: TraceExporter; + let tracer: Tracer; + let cloudTraceInfo: Schema$Trace; + let testConfig: TestConfig; + + // Custom SpanContext for each test, required for trace ID injection. + let customSpanContext: SpanContext; + + // Custom Context for each test, required for trace ID injection. + let customContext: OpenTelemetryContext; + + const spanIdToChildrenSpanIds = new Map(); + const spanIdToSpanData = new Map(); + let rootSpanIds: string[] = []; + + function afterEachTest(): Promise { + spanIdToChildrenSpanIds.clear(); + spanIdToSpanData.clear(); + rootSpanIds = []; + + return verifyInstance(firestore); + } + + function getOpenTelemetryOptions( + tracerProvider: TracerProvider, + ): FirestoreOpenTelemetryOptions { + const options: FirestoreOpenTelemetryOptions = { + tracerProvider: undefined, + }; + + // If we are *not* using a global OpenTelemetry instance, a TracerProvider + // must be passed to the Firestore SDK. + if (!testConfig.useGlobalOpenTelemetry) { + options.tracerProvider = tracerProvider; + } + + return options; + } + + function generateRandomHexString(length: number): string { + if (length <= 0) { + throw new Error('Length must be a positive integer'); + } + + const hexCharacters = '0123456789abcdef'; + let hexString = ''; + for (let i = 0; i < length; i++) { + const randomIndex = Math.floor(Math.random() * hexCharacters.length); + hexString += hexCharacters[randomIndex]; + } + + return hexString; + } + + function getNewSpanContext(): SpanContext { + const spanContext: SpanContext = { + traceId: generateRandomHexString(NUM_TRACE_ID_BYTES), + spanId: generateRandomHexString(NUM_SPAN_ID_BYTES), + traceFlags: TraceFlags.SAMPLED, + }; + logger('getNewSpanContext', null, `custom span context:${spanContext}`); + return spanContext; + } + + function beforeEachTest(test: Test) { + testConfig = { + preferRest: test.parent?.title === REST_TEST_SUITE_TITLE, + useGlobalOpenTelemetry: + test.parent?.parent?.title === GLOBAL_OTEL_TEST_SUITE_TITLE, + e2e: test.parent?.parent?.parent?.title === E2E_TEST_SUITE_TITLE, + }; + + logger('beforeEach', null, 'Starting test with config:', testConfig); + + // Remove the global tracer provider in case anything was registered + // in order to avoid duplicate global tracers. + trace.disable(); + context.disable(); + + // Set up a context manager. + const contextManager = new AsyncLocalStorageContextManager(); + contextManager.enable(); + context.setGlobalContextManager(contextManager); + + inMemorySpanExporter = new InMemorySpanExporter(); + consoleSpanExporter = new ConsoleSpanExporter(); + gcpTraceExporter = new TraceExporter(); + + const spanProcessors: SpanProcessor[] = [ + // Always add the console exporter for local debugging. + new BatchSpanProcessor(consoleSpanExporter), + ]; + + if (testConfig.e2e) { + spanProcessors.push(new BatchSpanProcessor(gcpTraceExporter)); + } else { + spanProcessors.push(new BatchSpanProcessor(inMemorySpanExporter)); + } + + // Create a new tracer and span processor for each test to make sure there + // are no overlaps when reading the results. + tracerProvider = new NodeTracerProvider({ + sampler: new AlwaysOnSampler(), + spanProcessors, + }); + + if (testConfig.useGlobalOpenTelemetry) { + trace.setGlobalTracerProvider(tracerProvider); + } + + // Using a unique tracer name for each test. + tracer = tracerProvider.getTracer(`${test.title}${Date.now()}`); + + customSpanContext = getNewSpanContext(); + customContext = trace.setSpanContext(ROOT_CONTEXT, customSpanContext); + + const settings: Settings = { + preferRest: testConfig.preferRest, + openTelemetry: getOpenTelemetryOptions(tracerProvider), + }; + + // Named-database tests use an environment variable to specify the database ID. Add it to the settings. + if (process.env.FIRESTORE_NAMED_DATABASE) { + settings.databaseId = process.env.FIRESTORE_NAMED_DATABASE; + } + // If a database ID has not been specified in the settings, check whether + // it's been specified using an environment variable. + if (!settings.databaseId && process.env.DATABASE_ID) { + settings.databaseId = process.env.DATABASE_ID; + } + // If a Project ID has not been specified in the settings, check whether + // it's been specified using an environment variable. + if (!settings.projectId && process.env.PROJECT_ID) { + settings.projectId = process.env.PROJECT_ID; + } + + firestore = new Firestore(settings); + } + + function getSettingsAttributes(): Attributes { + const settingsAttributes: Attributes = {}; + settingsAttributes['otel.scope.name'] = require('../../package.json').name; + settingsAttributes['otel.scope.version'] = + require('../../package.json').version; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.database_id`] = + firestore.databaseId; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.host`] = + 'firestore.googleapis.com:443'; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.prefer_REST`] = + testConfig.preferRest; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.max_idle_channels`] = 1; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.initial_retry_delay`] = + '0.1s'; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.initial_rpc_timeout`] = + '60s'; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.total_timeout`] = '600s'; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.max_retry_delay`] = '60s'; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.max_rpc_timeout`] = '60s'; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.retry_delay_multiplier`] = + '1.3'; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.rpc_timeout_multiplier`] = + '1'; + + // Project ID is not set on the Firestore object until _after_ the first + // operation is done. Therefore, the spans that are created _before_ the + // first operation do not contain a project ID. + try { + const projectId = firestore.projectId; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.project_id`] = projectId; + } catch (e) { + // Project ID has not been set yet. + } + + return settingsAttributes; + } + + // Take a function and runs it inside a new root span. This makes it possible to + // encapsulate all the SDK-generated spans inside a test root span. It also makes + // it easy to query a trace storage backend for a known trace ID and span Id. + function runFirestoreOperationInRootSpan void>( + fn: F, + ): Promise { + return tracer.startActiveSpan( + SPAN_NAME_TEST_ROOT, + {}, + customContext, + async span => { + await fn(); + span.end(); + }, + ); + } + + // Returns true on success, and false otherwise. + async function waitForCompletedInMemorySpans(): Promise { + await tracerProvider.forceFlush(); + await inMemorySpanExporter.forceFlush(); + await new Promise(resolve => setTimeout(resolve, 1000)); + return true; + } + + // Returns true on success, and false otherwise. + async function waitForCompletedCloudTraceSpans( + numExpectedSpans: number, + ): Promise { + const auth = new gAuth.GoogleAuth({ + projectId: firestore.projectId, + scopes: ['https://www.googleapis.com/auth/cloud-platform'], + }); + const client = new cloudtrace_v1.Cloudtrace({auth}); + const projectTraces = new cloudtrace_v1.Resource$Projects$Traces( + client.context, + ); + + // Querying the trace from Cloud Trace immediately is almost always going + // to fail. So we have an initial delay before making our first attempt. + await new Promise(resolve => + setTimeout(resolve, GET_TRACE_INITIAL_WAIT_MILLIS), + ); + + let remainingAttempts = GET_TRACE_MAX_RETRY_COUNT; + let receivedFullTrace = false; + do { + try { + const getTraceResponse = await projectTraces.get({ + projectId: firestore.projectId, + traceId: customSpanContext.traceId, + }); + + cloudTraceInfo = getTraceResponse.data; + + receivedFullTrace = cloudTraceInfo.spans?.length === numExpectedSpans; + logger( + 'waitForCompletedCloudTraceSpans', + null, + `fetched a trace with ${cloudTraceInfo.spans?.length} spans`, + ); + } catch (error) { + logger( + 'waitForCompletedCloudTraceSpans', + null, + 'failed with error:', + error, + ); + } + + // Using a constant backoff for each attempt. + if (!receivedFullTrace) { + logger( + 'waitForCompletedCloudTraceSpans', + null, + `Could not fetch a full trace from the server. Retrying in ${GET_TRACE_RETRY_BACKOFF_MILLIS}ms.`, + ); + await new Promise(resolve => + setTimeout(resolve, GET_TRACE_RETRY_BACKOFF_MILLIS), + ); + } + } while (!receivedFullTrace && --remainingAttempts > 0); + return receivedFullTrace; + } + + async function waitForCompletedSpans( + numExpectedSpans: number, + ): Promise { + let success = false; + if (testConfig.e2e) { + success = await waitForCompletedCloudTraceSpans(numExpectedSpans); + } else { + success = await waitForCompletedInMemorySpans(); + } + + if (success) { + buildSpanMaps(); + } + + // Tests are able to perform some Firestore operations inside + // `runFirestoreOperationInRootSpan`, and some Firestore operations outside + // of it. Therefore, if a given test intends to capture some (but not all) spans, + // the in-memory trace will have more spans than `numExpectedSpans`. + expect(spanIdToSpanData.size).to.greaterThanOrEqual( + numExpectedSpans, + `Could not find expected number of spans (${numExpectedSpans})`, + ); + } + + function buildSpanMapsFromInMemorySpanExporter(): void { + const spans = inMemorySpanExporter.getFinishedSpans(); + spans.forEach(span => { + const id = span?.spanContext().spanId; + const parentId = span?.parentSpanContext?.spanId; + if (!parentId || span.name === SPAN_NAME_TEST_ROOT) { + rootSpanIds.push(id); + } else { + let children = spanIdToChildrenSpanIds.get(parentId); + // Initialize to empty array if it hasn't been seen before. + if (!children) { + children = []; + } + // Add the new child. + children.push(id); + spanIdToChildrenSpanIds.set(parentId, children); + } + spanIdToSpanData.set(id, SpanData.fromInMemorySpan(span)); + }); + } + + function buildSpanMapsFromCloudTraceInfo(): void { + const spans = cloudTraceInfo.spans; + spans?.forEach(span => { + const id = span.spanId; + const parentId = span.parentSpanId; + if (!parentId || span.name === SPAN_NAME_TEST_ROOT) { + rootSpanIds.push(id!); + } else { + let children = spanIdToChildrenSpanIds.get(parentId); + if (!children) { + children = []; + } + children.push(id!); + spanIdToChildrenSpanIds.set(parentId, children); + } + spanIdToSpanData.set( + id!, + SpanData.fromCloudTraceSpan(span, customSpanContext.traceId), + ); + }); + } + + function buildSpanMaps(): void { + if (testConfig.e2e) { + buildSpanMapsFromCloudTraceInfo(); + } else { + buildSpanMapsFromInMemorySpanExporter(); + } + logger( + 'buildSpanMaps', + null, + 'Built the following spans:', + rootSpanIds, + spanIdToSpanData, + spanIdToChildrenSpanIds, + ); + } + + function getChildSpans(spanId: string): string[] | undefined { + return spanIdToChildrenSpanIds.get(spanId); + } + + // Returns the first span it can find with the given name, or null if it cannot find a span with the given name. + // If there are multiple spans with the same name, it'll return the first one. + function getSpanByName(spanName: string): SpanData | null { + for (const spanData of spanIdToSpanData.values()) { + if (spanData.name === spanName) { + return spanData; + } + } + return null; + } + + // Returns the array of spans that match the given span hierarchy names starting + // at the given root. Returns an empty list if it cannot find such hierarchy under + // the given root. + function dfsSpanHierarchy( + rootSpanId: string, + spanNamesHierarchy: string[], + ): SpanData[] { + // This function returns an empty list if it cannot find a full match. + const notAMatch: SpanData[] = []; + const rootSpan = spanIdToSpanData.get(rootSpanId); + + if (spanNamesHierarchy.length === 0 || !rootSpan) { + return notAMatch; + } + + if (spanIdToSpanData.get(rootSpanId)?.name !== spanNamesHierarchy[0]) { + // The root names didn't match. + return notAMatch; + } else { + // The root names matched. The new hierarchy to match can be obtained by + // popping the first element of `spanNamesHierarchy`. + const newSpanNamesHierarchy = spanNamesHierarchy.slice(1); + + const children = getChildSpans(rootSpanId); + if (!children || children.length === 0) { + if (newSpanNamesHierarchy.length === 0) { + // The root span doesn't have any more children, and there are no + // more span names to match. This is a successful match, and it is + // a base case for the recursion. + return [rootSpan]; + } else { + // The root span doesn't have any more children, but there are still + // more span names to match. + return notAMatch; + } + } else { + // See which (if any) of the child trees matches `newSpanNamesHierarchy`. + for (let childIndex = 0; childIndex < children.length; ++childIndex) { + const newRootSpanId = children[childIndex]; + const subtreeMatch = dfsSpanHierarchy( + newRootSpanId, + newSpanNamesHierarchy, + ); + if (subtreeMatch.length > 0) { + // We found a full match in the child tree. + return [rootSpan].concat(subtreeMatch); + } + } + + // If none of the child trees matched `newSpanNamesHierarchy`, we were + // not able to find a full match anywhere in our child trees. + return notAMatch; + } + } + } + + // Asserts that the span hierarchy exists for the given span names. + // The hierarchy starts with the root span, followed by the child span, + // grandchild span, and so on. It also asserts that all the given spans belong + // to the same trace, and that Firestore-generated spans contain the expected + // Firestore attributes. + function expectSpanHierarchy(...spanNamesHierarchy: string[]): void { + expect(spanNamesHierarchy.length).to.be.greaterThan( + 0, + 'The expected spans hierarchy was empty', + ); + + let matchingSpanHierarchy: SpanData[] = []; + + // The Firestore operations that have been executed generate a number of + // spans. The span names, however, are not unique. For example, we could have: + // "DocRef.Get" (id:1) -> "grpc.GET" (id:2) -> "POST" (id:3) + // "DocRef.Set" (id:4) -> "grpc.SET" (id:5) -> "POST" (id:6) + // Note that span names are not unique (e.g. span 3 and span 6). + // Let's say we want to check if the following span hierarchy exists: + // [DocRef.Set -> grpc.SET -> POST] + // We start at each root span (span 1 and span 4 in this case), and check if + // the span hierarchy matches the given `spanNamesHierarchy`. + for (let i = 0; i < rootSpanIds.length; ++i) { + matchingSpanHierarchy = dfsSpanHierarchy( + rootSpanIds[i], + spanNamesHierarchy, + ); + if (matchingSpanHierarchy.length > 0) break; + } + + expect(matchingSpanHierarchy.length).to.be.greaterThan( + 0, + `Was not able to find the following span hierarchy: ${spanNamesHierarchy}`, + ); + logger( + 'expectSpanHierarchy', + null, + 'Found the following span hierarchy:', + matchingSpanHierarchy, + ); + + for (let i = 0; i + 1 < matchingSpanHierarchy.length; ++i) { + const parentSpan = matchingSpanHierarchy[i]; + const childSpan = matchingSpanHierarchy[i + 1]; + expect(childSpan.traceId).to.equal( + parentSpan.traceId, + `'${childSpan.name}' and '${parentSpan.name}' spans do not belong to the same trace`, + ); + + // The Cloud Trace API does not return span attributes and events. + if (!testConfig.e2e) { + const settingsAttributes = getSettingsAttributes(); + for (const attributesKey in settingsAttributes) { + if ( + attributesKey.endsWith('.project_id') && + i + 1 !== matchingSpanHierarchy.length + ) { + // Project ID is not set on the Firestore object until _after_ the first + // operation is done. Therefore, the spans that are created _before_ the + // first operation do not contain a project ID. So, we'll just compare + // this attribute on the leaf spans. + } else { + expect(childSpan.attributes[attributesKey]).to.be.equal( + settingsAttributes[attributesKey], + ); + } + } + } + } + } + + // Ensures that the given span exists and has exactly all the given attributes. + function expectSpanHasAttributes( + spanName: string, + attributes: Attributes, + ): void { + // The Cloud Trace API does not return span attributes and events. + if (testConfig.e2e) { + return; + } + + // Expect that the span exists first. + const span = getSpanByName(spanName); + expect(span, `Could not find the span named ${spanName}`).to.not.be.null; + + // Assert that the expected attributes are present in the span attributes. + // Note that the span attributes may be a superset of the attributes passed + // to this function. + for (const attributesKey in attributes) { + expect(span!.attributes[attributesKey]).to.be.equal( + attributes[attributesKey], + ); + } + } + + // Ensures that the given span exists and has the given attributes. + function expectSpanHasEvents(spanName: string, eventNames: string[]): void { + // The Cloud Trace API does not return span attributes and events. + if (testConfig.e2e) { + return; + } + + // Expect that the span exists first. + const span = getSpanByName(spanName); + expect(span, `Could not find the span named ${spanName}`).to.not.be.null; + + // Assert that the expected attributes are present in the span attributes. + // Note that the span attributes may be a superset of the attributes passed + // to this function. + if (span?.events) { + const numEvents = eventNames.length; + expect(numEvents).to.equal(span.events.length); + for (let i = 0; i < numEvents; ++i) { + expect(span.events[i].name).to.equal(eventNames[i]); + } + } + } + + describe(IN_MEMORY_TEST_SUITE_TITLE, () => { + describe(NON_GLOBAL_OTEL_TEST_SUITE_TITLE, () => { + describe(GRPC_TEST_SUITE_TITLE, () => { + beforeEach(function () { + beforeEachTest(this.currentTest!); + }); + runTestCases(); + afterEach(async () => afterEachTest()); + }); + describe(REST_TEST_SUITE_TITLE, () => { + beforeEach(function () { + beforeEachTest(this.currentTest!); + }); + runTestCases(); + afterEach(async () => afterEachTest()); + }); + }); + describe(GLOBAL_OTEL_TEST_SUITE_TITLE, () => { + describe(GRPC_TEST_SUITE_TITLE, () => { + beforeEach(function () { + beforeEachTest(this.currentTest!); + }); + runTestCases(); + afterEach(async () => afterEachTest()); + }); + describe(REST_TEST_SUITE_TITLE, () => { + beforeEach(function () { + beforeEachTest(this.currentTest!); + }); + runTestCases(); + afterEach(async () => afterEachTest()); + }); + }); + }); + + describe(E2E_TEST_SUITE_TITLE, () => { + describe(NON_GLOBAL_OTEL_TEST_SUITE_TITLE, () => { + describe(GRPC_TEST_SUITE_TITLE, () => { + beforeEach(function () { + beforeEachTest(this.currentTest!); + }); + runTestCases(); + afterEach(async () => afterEachTest()); + }); + describe(REST_TEST_SUITE_TITLE, () => { + beforeEach(function () { + beforeEachTest(this.currentTest!); + }); + runTestCases(); + afterEach(async () => afterEachTest()); + }); + }); + describe(GLOBAL_OTEL_TEST_SUITE_TITLE, () => { + describe(GRPC_TEST_SUITE_TITLE, () => { + beforeEach(function () { + beforeEachTest(this.currentTest!); + }); + runTestCases(); + afterEach(async () => afterEachTest()); + }); + describe(REST_TEST_SUITE_TITLE, () => { + beforeEach(function () { + beforeEachTest(this.currentTest!); + }); + runTestCases(); + afterEach(async () => afterEachTest()); + }); + }); + }); + + function runTestCases() { + it('document reference get()', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').doc('bar').get(), + ); + await waitForCompletedSpans(3); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_DOC_REF_GET, + SPAN_NAME_BATCH_GET_DOCUMENTS, + ); + expectSpanHasEvents(SPAN_NAME_BATCH_GET_DOCUMENTS, [ + 'Firestore.batchGetDocuments: Start', + 'Firestore.batchGetDocuments: First response received', + 'Firestore.batchGetDocuments: Completed', + ]); + + expectSpanHasAttributes(SPAN_NAME_BATCH_GET_DOCUMENTS, { + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + }); + + it('document reference create()', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').doc().create({}), + ); + await waitForCompletedSpans(3); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_DOC_REF_CREATE, + SPAN_NAME_BATCH_COMMIT, + ); + + expectSpanHasAttributes(SPAN_NAME_BATCH_COMMIT, { + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + }); + + it('document reference delete()', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').doc('bar').delete(), + ); + await waitForCompletedSpans(3); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_DOC_REF_DELETE, + SPAN_NAME_BATCH_COMMIT, + ); + + expectSpanHasAttributes(SPAN_NAME_BATCH_COMMIT, { + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + }); + + it('document reference set()', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').doc('bar').set({foo: 'bar'}), + ); + await waitForCompletedSpans(3); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_DOC_REF_SET, + SPAN_NAME_BATCH_COMMIT, + ); + + expectSpanHasAttributes(SPAN_NAME_BATCH_COMMIT, { + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + }); + + it('document reference update()', async () => { + // Make sure the document exists before updating it. + // Perform the `set` operation outside of the root span. + await firestore.collection('foo').doc('bar').set({foo: 'bar'}); + + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').doc('bar').update('foo', 'bar2'), + ); + await waitForCompletedSpans(3); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_DOC_REF_UPDATE, + SPAN_NAME_BATCH_COMMIT, + ); + + expectSpanHasAttributes(SPAN_NAME_BATCH_COMMIT, { + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + }); + + it('document reference list collections', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').doc('bar').listCollections(), + ); + await waitForCompletedSpans(2); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_DOC_REF_LIST_COLLECTIONS, + ); + + expectSpanHasAttributes(SPAN_NAME_DOC_REF_LIST_COLLECTIONS, { + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + }); + + it('aggregate query get()', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').count().get(), + ); + await waitForCompletedSpans(2); + expectSpanHierarchy(SPAN_NAME_TEST_ROOT, SPAN_NAME_AGGREGATION_QUERY_GET); + expectSpanHasEvents(SPAN_NAME_AGGREGATION_QUERY_GET, [ + 'Firestore.runAggregationQuery: Start', + 'Firestore.runAggregationQuery: First response received', + 'Firestore.runAggregationQuery: Completed', + ]); + }); + + it('collection reference add()', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').add({foo: 'bar'}), + ); + await waitForCompletedSpans(4); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_COL_REF_ADD, + SPAN_NAME_DOC_REF_CREATE, + SPAN_NAME_BATCH_COMMIT, + ); + + expectSpanHasAttributes(SPAN_NAME_BATCH_COMMIT, { + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + }); + + // Enterprise: field mask is not supported + it.skipEnterprise('collection reference list documents', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').listDocuments(), + ); + await waitForCompletedSpans(2); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_COL_REF_LIST_DOCUMENTS, + ); + + expectSpanHasAttributes(SPAN_NAME_COL_REF_LIST_DOCUMENTS, { + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + }); + + it('query get()', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').where('foo', '==', 'bar').limit(1).get(), + ); + await waitForCompletedSpans(2); + expectSpanHierarchy(SPAN_NAME_TEST_ROOT, SPAN_NAME_QUERY_GET); + expectSpanHasEvents(SPAN_NAME_QUERY_GET, [ + 'RunQuery', + 'Firestore.runQuery: Start', + 'Firestore.runQuery: First response received', + 'Firestore.runQuery: Completed', + ]); + + expectSpanHasAttributes(SPAN_NAME_QUERY_GET, { + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + }); + + it('firestore getAll()', async () => { + const docRef1 = firestore.collection('foo').doc('1'); + const docRef2 = firestore.collection('foo').doc('2'); + await runFirestoreOperationInRootSpan(() => + firestore.getAll(docRef1, docRef2), + ); + await waitForCompletedSpans(2); + expectSpanHierarchy(SPAN_NAME_TEST_ROOT, SPAN_NAME_BATCH_GET_DOCUMENTS); + expectSpanHasEvents(SPAN_NAME_BATCH_GET_DOCUMENTS, [ + 'Firestore.batchGetDocuments: Start', + 'Firestore.batchGetDocuments: First response received', + 'Firestore.batchGetDocuments: Completed', + ]); + + expectSpanHasAttributes(SPAN_NAME_BATCH_GET_DOCUMENTS, { + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + }); + + it('transaction', async () => { + const docRef1 = firestore.collection('foo').doc('bar'); + const docRef2 = firestore.collection('foo').doc('bar'); + + await runFirestoreOperationInRootSpan(async () => { + return firestore.runTransaction(async transaction => { + await transaction.get(docRef1); + await transaction.getAll(docRef1, docRef2); + await transaction.get(firestore.collection('foo').limit(1)); + await transaction.get(firestore.collection('nonexistent').count()); + transaction.set(firestore.collection('foo').doc(), {foo: 'bar'}); + }); + }); + + await waitForCompletedSpans(7); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_TRANSACTION_RUN, + SPAN_NAME_TRANSACTION_GET_DOCUMENT, + ); + + expectSpanHasAttributes(SPAN_NAME_TRANSACTION_GET_DOCUMENT, { + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_TRANSACTION_RUN, + SPAN_NAME_TRANSACTION_GET_DOCUMENTS, + ); + + expectSpanHasAttributes(SPAN_NAME_TRANSACTION_GET_DOCUMENTS, { + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_TRANSACTION_RUN, + SPAN_NAME_TRANSACTION_GET_QUERY, + ); + + expectSpanHasAttributes(SPAN_NAME_TRANSACTION_GET_QUERY, { + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_TRANSACTION_RUN, + SPAN_NAME_TRANSACTION_GET_AGGREGATION_QUERY, + ); + + expectSpanHasAttributes(SPAN_NAME_TRANSACTION_GET_AGGREGATION_QUERY, { + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_TRANSACTION_RUN, + SPAN_NAME_TRANSACTION_COMMIT, + ); + + expectSpanHasAttributes(SPAN_NAME_TRANSACTION_COMMIT, { + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + }); + + it('batch', async () => { + const writeBatch = firestore.batch(); + const documentRef = firestore.doc('col/doc'); + writeBatch.set(documentRef, {foo: 'bar'}); + + await runFirestoreOperationInRootSpan(() => writeBatch.commit()); + await waitForCompletedSpans(2); + expectSpanHierarchy(SPAN_NAME_TEST_ROOT, SPAN_NAME_BATCH_COMMIT); + }); + + // Service not implemented for Enterprise DB: PartitionQuery + it.skipEnterprise('partition query', async () => { + await runFirestoreOperationInRootSpan(async () => { + const query = firestore.collectionGroup('foo'); + let numPartitions = 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + for await (const partition of query.getPartitions(3)) { + numPartitions++; + } + return numPartitions; + }); + + await waitForCompletedSpans(2); + expectSpanHierarchy(SPAN_NAME_TEST_ROOT, SPAN_NAME_PARTITION_QUERY); + expectSpanHasAttributes(SPAN_NAME_PARTITION_QUERY, { + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + }); + + it('bulk writer', async () => { + await runFirestoreOperationInRootSpan(async () => { + const bulkWriter = firestore.bulkWriter(); + // No need to await the set operations as 'close()' will commit all writes before closing. + void bulkWriter.set(firestore.collection('foo').doc(), {foo: 1}); + void bulkWriter.set(firestore.collection('foo').doc(), {foo: 2}); + void bulkWriter.set(firestore.collection('foo').doc(), {foo: 3}); + void bulkWriter.set(firestore.collection('foo').doc(), {foo: 4}); + void bulkWriter.set(firestore.collection('foo').doc(), {foo: 5}); + await bulkWriter.close(); + }); + + await waitForCompletedSpans(2); + expectSpanHierarchy(SPAN_NAME_TEST_ROOT, SPAN_NAME_BULK_WRITER_COMMIT); + expectSpanHasAttributes(SPAN_NAME_BULK_WRITER_COMMIT, { + [ATTRIBUTE_KEY_DOC_COUNT]: 5, + [ATTRIBUTE_GCP_RESOURCE_NAME]: `//firestore.googleapis.com/projects/${firestore.projectId}/databases/${firestore.databaseId}`, + }); + }); + } +}); diff --git a/handwritten/firestore/dev/test/aggregate.ts b/handwritten/firestore/dev/test/aggregate.ts new file mode 100644 index 00000000000..4875af91a73 --- /dev/null +++ b/handwritten/firestore/dev/test/aggregate.ts @@ -0,0 +1,47 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {expect, use} from 'chai'; +import * as chaiAsPromised from 'chai-as-promised'; +import {AggregateField} from '../src/aggregate'; + +use(chaiAsPromised); + +describe('aggregate field equality checks', () => { + it('equates two equal aggregate fields', () => { + expect(AggregateField.count().isEqual(AggregateField.count())).to.be.true; + expect(AggregateField.sum('foo').isEqual(AggregateField.sum('foo'))).to.be + .true; + expect(AggregateField.average('bar').isEqual(AggregateField.average('bar'))) + .to.be.true; + expect(AggregateField.sum('foo.bar').isEqual(AggregateField.sum('foo.bar'))) + .to.be.true; + expect( + AggregateField.average('bar.baz').isEqual( + AggregateField.average('bar.baz'), + ), + ).to.be.true; + }); + + it('differentiates two different aggregate fields', () => { + expect(AggregateField.sum('foo').isEqual(AggregateField.sum('bar'))).to.be + .false; + expect(AggregateField.average('foo').isEqual(AggregateField.average('bar'))) + .to.be.false; + expect(AggregateField.average('foo').isEqual(AggregateField.sum('foo'))).to + .be.false; + expect(AggregateField.sum('foo').isEqual(AggregateField.average('foo'))).to + .be.false; + }); +}); diff --git a/handwritten/firestore/dev/test/aggregateQuery.ts b/handwritten/firestore/dev/test/aggregateQuery.ts new file mode 100644 index 00000000000..72b75cbe8b1 --- /dev/null +++ b/handwritten/firestore/dev/test/aggregateQuery.ts @@ -0,0 +1,166 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {afterEach, beforeEach, it} from 'mocha'; +import { + ApiOverride, + createInstance, + stream, + verifyInstance, +} from './util/helpers'; +import {Firestore, Query, Timestamp} from '../src'; +import {expect, use} from 'chai'; +import {google} from '../protos/firestore_v1_proto_api'; +import api = google.firestore.v1; +import * as chaiAsPromised from 'chai-as-promised'; +import {setTimeoutHandler} from '../src/backoff'; +use(chaiAsPromised); + +describe('aggregate query interface', () => { + let firestore: Firestore; + + beforeEach(() => { + setTimeoutHandler(setImmediate); + return createInstance().then(firestoreInstance => { + firestore = firestoreInstance; + }); + }); + + afterEach(async () => { + await verifyInstance(firestore); + setTimeoutHandler(setTimeout); + }); + + it('has isEqual() method', () => { + const queryA = firestore.collection('collectionId'); + const queryB = firestore.collection('collectionId'); + + const queryEquals = (equals: Query[], notEquals: Query[]) => { + for (const equal1 of equals) { + const equal1count = equal1.count(); + for (const equal2 of equals) { + const equal2count = equal2.count(); + expect(equal1count.isEqual(equal2count)).to.be.true; + expect(equal2count.isEqual(equal1count)).to.be.true; + } + + for (const notEqual of notEquals) { + const notEqual2count = notEqual.count(); + expect(equal1count.isEqual(notEqual2count)).to.be.false; + expect(notEqual2count.isEqual(equal1count)).to.be.false; + } + } + }; + + queryEquals( + [ + queryA.orderBy('foo').endBefore('a'), + queryB.orderBy('foo').endBefore('a'), + ], + [ + queryA.orderBy('foo').endBefore('b'), + queryB.orderBy('bar').endBefore('a'), + ], + ); + }); + + it('returns results', async () => { + // Here we are mocking the response from the server. The client uses + // `aggregate_$i` aliases in requests and will receive these in responses. + const result: api.IRunAggregationQueryResponse = { + result: { + aggregateFields: { + aggregate_0: {integerValue: '99'}, + }, + }, + readTime: {seconds: 5, nanos: 6}, + }; + const overrides: ApiOverride = { + runAggregationQuery: () => stream(result), + }; + + firestore = await createInstance(overrides); + + const query = firestore.collection('collectionId').count(); + return query.get().then(results => { + expect(results.data().count).to.be.equal(99); + expect(results.readTime.isEqual(new Timestamp(5, 6))).to.be.true; + expect(results.query).to.be.equal(query); + }); + }); + + it('handles stream exception at initialization', async () => { + let attempts = 0; + const query = firestore.collection('collectionId').count(); + + query._stream = () => { + ++attempts; + throw new Error('Expected error'); + }; + + await query + .get() + .then(() => { + throw new Error('Unexpected success in Promise'); + }) + .catch(err => { + expect(err.message).to.equal('Expected error'); + expect(attempts).to.equal(1); + }); + }); + + it('handles stream exception during initialization', async () => { + let attempts = 0; + const overrides: ApiOverride = { + runAggregationQuery: () => { + ++attempts; + return stream(new Error('Expected error')); + }, + }; + firestore = await createInstance(overrides); + + const query = firestore.collection('collectionId').count(); + await query + .get() + .then(() => { + throw new Error('Unexpected success in Promise'); + }) + .catch(err => { + expect(err.message).to.equal('Expected error'); + expect(attempts).to.equal(5); + }); + }); + + it('handles message without result during initialization', async () => { + let attempts = 0; + const overrides: ApiOverride = { + runAggregationQuery: () => { + ++attempts; + return stream({readTime: {seconds: 5, nanos: 6}}); + }, + }; + firestore = await createInstance(overrides); + + const query = firestore.collection('collectionId').count(); + await query + .get() + .then(() => { + throw new Error('Unexpected success in Promise'); + }) + .catch(err => { + expect(err.message).to.equal('No AggregateQuery results'); + expect(attempts).to.equal(1); + }); + }); +}); diff --git a/handwritten/firestore/dev/test/backoff.ts b/handwritten/firestore/dev/test/backoff.ts new file mode 100644 index 00000000000..c8a4950906a --- /dev/null +++ b/handwritten/firestore/dev/test/backoff.ts @@ -0,0 +1,174 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {describe, it, beforeEach, before, after} from 'mocha'; +import {expect, use} from 'chai'; +import * as chaiAsPromised from 'chai-as-promised'; + +import {ExponentialBackoff, setTimeoutHandler} from '../src/backoff'; + +use(chaiAsPromised); + +const nop = () => {}; + +describe('ExponentialBackoff', () => { + let observedDelays: number[] = []; + + before(() => { + setTimeoutHandler((callback, timeout) => { + observedDelays.push(timeout); + callback(); + }); + }); + + beforeEach(() => { + observedDelays = []; + }); + + after(() => setTimeoutHandler(setTimeout)); + + function assertDelayEquals(expected: number) { + expect(observedDelays.shift()).to.equal(expected); + } + + function assertDelayBetween(low: number, high: number) { + const actual = observedDelays.shift()!; + expect(actual).to.be.at.least(low); + expect(actual).to.be.at.most(high); + } + + it("doesn't delay first attempt", async () => { + const backoff = new ExponentialBackoff(); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(0); + }); + + it('respects the initial retry delay', async () => { + const backoff = new ExponentialBackoff({ + initialDelayMs: 10, + jitterFactor: 0, + }); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(0); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(10); + }); + + it('exponentially increases the delay', async () => { + const backoff = new ExponentialBackoff({ + initialDelayMs: 10, + backoffFactor: 2, + jitterFactor: 0, + }); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(0); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(10); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(20); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(40); + }); + + it('increases until maximum', async () => { + const backoff = new ExponentialBackoff({ + initialDelayMs: 10, + backoffFactor: 2, + maxDelayMs: 35, + jitterFactor: 0, + }); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(0); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(10); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(20); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(35); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(35); + }); + + it('can reset delay', async () => { + const backoff = new ExponentialBackoff({ + initialDelayMs: 10, + backoffFactor: 2, + maxDelayMs: 35, + jitterFactor: 0, + }); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(0); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(10); + backoff.reset(); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(0); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(10); + }); + + it('can reset delay to maximum', async () => { + const backoff = new ExponentialBackoff({ + initialDelayMs: 10, + maxDelayMs: 35, + jitterFactor: 0, + }); + backoff.resetToMax(); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(35); + }); + + it('applies jitter', async () => { + const backoff = new ExponentialBackoff({ + initialDelayMs: 10, + backoffFactor: 2, + jitterFactor: 0.1, + }); + await backoff.backoffAndWait().then(nop); + assertDelayEquals(0); + await backoff.backoffAndWait().then(nop); + assertDelayBetween(9, 11); + await backoff.backoffAndWait().then(nop); + assertDelayBetween(18, 22); + await backoff.backoffAndWait().then(nop); + assertDelayBetween(36, 44); + }); + + it('tracks the number of retry attempts', async () => { + const backoff = new ExponentialBackoff({ + initialDelayMs: 10, + backoffFactor: 2, + jitterFactor: 0.1, + }); + expect(backoff.retryCount).to.equal(0); + await backoff.backoffAndWait().then(nop); + expect(backoff.retryCount).to.equal(1); + await backoff.backoffAndWait().then(nop); + expect(backoff.retryCount).to.equal(2); + backoff.reset(); + expect(backoff.retryCount).to.equal(0); + }); + + it('cannot queue two backoffAndWait() operations simultaneously', async () => { + const backoff = new ExponentialBackoff(); + + // The timeout handler for this test simply idles forever. + setTimeoutHandler(() => {}); + + void backoff.backoffAndWait().then(nop); + await expect(backoff.backoffAndWait()).to.eventually.be.rejectedWith( + 'A backoff operation is already in progress.', + ); + }); +}); diff --git a/handwritten/firestore/dev/test/bulk-writer.ts b/handwritten/firestore/dev/test/bulk-writer.ts new file mode 100644 index 00000000000..041b673d957 --- /dev/null +++ b/handwritten/firestore/dev/test/bulk-writer.ts @@ -0,0 +1,1409 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {BulkWriterOptions, DocumentData} from '@google-cloud/firestore'; + +import {afterEach, beforeEach, describe, it} from 'mocha'; +import {expect} from 'chai'; +import {GoogleError, Status} from 'google-gax'; + +import * as proto from '../protos/firestore_v1_proto_api'; +import { + BulkWriter, + Firestore, + setLogFunction, + Timestamp, + WriteResult, +} from '../src'; +import { + DEFAULT_BACKOFF_FACTOR, + DEFAULT_BACKOFF_INITIAL_DELAY_MS, + DEFAULT_BACKOFF_MAX_DELAY_MS, + MAX_RETRY_ATTEMPTS, + setTimeoutHandler, +} from '../src/backoff'; +import { + BulkWriterError, + DEFAULT_INITIAL_OPS_PER_SECOND_LIMIT, + DEFAULT_JITTER_FACTOR, + DEFAULT_MAXIMUM_OPS_PER_SECOND_LIMIT, + RETRY_MAX_BATCH_SIZE, +} from '../src/bulk-writer'; +import {Deferred} from '../src/util'; +import { + ApiOverride, + create, + createInstance, + document, + InvalidApiUsage, + remove, + response, + set, + update, + updateMask, + verifyInstance, +} from './util/helpers'; +import api = proto.google.firestore.v1; + +// Change the argument to 'console.log' to enable debug output. +setLogFunction(null); + +const PROJECT_ID = 'test-project'; + +interface RequestResponse { + request: api.IBatchWriteRequest; + response: api.IBatchWriteResponse; +} + +export function createRequest(requests: api.IWrite[]): api.IBatchWriteRequest { + return { + writes: requests, + }; +} + +export function successResponse( + updateTimeSeconds: number, +): api.IBatchWriteResponse { + return { + writeResults: [ + { + updateTime: { + nanos: 0, + seconds: updateTimeSeconds, + }, + }, + ], + status: [{code: Status.OK}], + }; +} + +export function failedResponse( + code = Status.DEADLINE_EXCEEDED, +): api.IBatchWriteResponse { + return { + writeResults: [ + { + updateTime: null, + }, + ], + status: [{code}], + }; +} + +export function mergeResponses( + responses: api.IBatchWriteResponse[], +): api.IBatchWriteResponse { + return { + writeResults: responses.map(v => v.writeResults![0]), + status: responses.map(v => v.status![0]), + }; +} + +export function setOp(doc: string, value: string): api.IWrite { + return set({ + document: document(doc, 'foo', value), + }).writes![0]; +} + +export function updateOp(doc: string, value: string): api.IWrite { + return update({ + document: document(doc, 'foo', value), + mask: updateMask('foo'), + }).writes![0]; +} + +export function createOp(doc: string, value: string): api.IWrite { + return create({ + document: document(doc, 'foo', value), + }).writes![0]; +} + +export function deleteOp(doc: string): api.IWrite { + return remove(doc).writes![0]; +} + +describe.skip('BulkWriter', () => { + let firestore: Firestore; + let requestCounter: number; + let opCount: number; + let timeoutHandlerCounter = 0; + + beforeEach(() => { + requestCounter = 0; + opCount = 0; + timeoutHandlerCounter = 0; + setTimeoutHandler((fn, timeout) => { + // Since a call to the backoff is made before each batchWrite, only + // increment the counter if the timeout is non-zero, which indicates a + // retry from an error. + if (timeout > 0) { + timeoutHandlerCounter++; + } + fn(); + }); + }); + + function incrementOpCount(): void { + opCount++; + } + + function verifyOpCount(expected: number): void { + expect(opCount).to.equal(expected); + } + + /** + * Creates an instance with the mocked objects. + */ + function instantiateInstance(mock: RequestResponse[]): Promise { + const overrides: ApiOverride = { + batchWrite: async (request, options) => { + expect(options!.retry!.retryCodes).contains(Status.ABORTED); + + expect(request).to.deep.eq({ + database: `projects/${PROJECT_ID}/databases/(default)`, + writes: mock[requestCounter].request.writes, + }); + const responsePromise = response({ + writeResults: mock[requestCounter].response.writeResults, + status: mock[requestCounter].response.status, + }); + requestCounter++; + return responsePromise; + }, + }; + return createInstance(overrides).then(firestoreClient => { + firestore = firestoreClient; + return firestore.bulkWriter(); + }); + } + + afterEach(async () => { + await verifyInstance(firestore); + setTimeoutHandler(setTimeout); + }); + + describe('options', () => { + it('requires object', async () => { + const firestore = await createInstance(); + expect(() => firestore.bulkWriter(42 as InvalidApiUsage)).to.throw( + 'Value for argument "options" is not a valid bulkWriter() options argument. Input is not an object.', + ); + }); + + it('initialOpsPerSecond requires positive integer', async () => { + const firestore = await createInstance(); + expect(() => + firestore.bulkWriter({throttling: {initialOpsPerSecond: -1}}), + ).to.throw( + 'Value for argument "initialOpsPerSecond" must be within [1, Infinity] inclusive, but was: -1', + ); + + expect(() => + firestore.bulkWriter({throttling: {initialOpsPerSecond: 500.5}}), + ).to.throw( + 'Value for argument "initialOpsPerSecond" is not a valid integer.', + ); + }); + + it('maxOpsPerSecond requires positive integer', async () => { + const firestore = await createInstance(); + expect(() => + firestore.bulkWriter({throttling: {maxOpsPerSecond: -1}}), + ).to.throw( + 'Value for argument "maxOpsPerSecond" must be within [1, Infinity] inclusive, but was: -1', + ); + + expect(() => + firestore.bulkWriter({throttling: {maxOpsPerSecond: 500.5}}), + ).to.throw( + 'Value for argument "maxOpsPerSecond" is not a valid integer.', + ); + }); + + it('maxOpsPerSecond must be greater than initial ops per second', async () => { + const firestore = await createInstance(); + + expect(() => + firestore.bulkWriter({ + throttling: {initialOpsPerSecond: 550, maxOpsPerSecond: 500}, + }), + ).to.throw( + 'Value for argument "options" is not a valid bulkWriter() options argument. "maxOpsPerSecond" cannot be less than "initialOpsPerSecond".', + ); + }); + + it('initial and max rates are properly set', async () => { + const firestore = await createInstance(); + + let bulkWriter = firestore.bulkWriter({ + throttling: {initialOpsPerSecond: 500, maxOpsPerSecond: 550}, + }); + expect(bulkWriter._rateLimiter.availableTokens).to.equal(500); + expect(bulkWriter._rateLimiter.maximumCapacity).to.equal(550); + + bulkWriter = firestore.bulkWriter({ + throttling: {maxOpsPerSecond: 1000}, + }); + expect(bulkWriter._rateLimiter.availableTokens).to.equal(500); + expect(bulkWriter._rateLimiter.maximumCapacity).to.equal(1000); + + bulkWriter = firestore.bulkWriter({ + throttling: {initialOpsPerSecond: 100}, + }); + expect(bulkWriter._rateLimiter.availableTokens).to.equal(100); + expect(bulkWriter._rateLimiter.maximumCapacity).to.equal( + DEFAULT_MAXIMUM_OPS_PER_SECOND_LIMIT, + ); + + bulkWriter = firestore.bulkWriter({ + throttling: {maxOpsPerSecond: 100}, + }); + expect(bulkWriter._rateLimiter.availableTokens).to.equal(100); + expect(bulkWriter._rateLimiter.maximumCapacity).to.equal(100); + + bulkWriter = firestore.bulkWriter(); + expect(bulkWriter._rateLimiter.availableTokens).to.equal( + DEFAULT_INITIAL_OPS_PER_SECOND_LIMIT, + ); + expect(bulkWriter._rateLimiter.maximumCapacity).to.equal( + DEFAULT_MAXIMUM_OPS_PER_SECOND_LIMIT, + ); + + bulkWriter = firestore.bulkWriter({throttling: true}); + expect(bulkWriter._rateLimiter.availableTokens).to.equal( + DEFAULT_INITIAL_OPS_PER_SECOND_LIMIT, + ); + expect(bulkWriter._rateLimiter.maximumCapacity).to.equal( + DEFAULT_MAXIMUM_OPS_PER_SECOND_LIMIT, + ); + + bulkWriter = firestore.bulkWriter({throttling: false}); + expect(bulkWriter._rateLimiter.availableTokens).to.equal( + Number.POSITIVE_INFINITY, + ); + expect(bulkWriter._rateLimiter.maximumCapacity).to.equal( + Number.POSITIVE_INFINITY, + ); + }); + }); + + it('has a set() method', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([setOp('doc', 'bar')]), + response: successResponse(2), + }, + ]); + const doc = firestore.doc('collectionId/doc'); + const writeResult = await bulkWriter.set(doc, {foo: 'bar'}); + incrementOpCount(); + await bulkWriter.close(); + verifyOpCount(1); + expect(writeResult.writeTime.isEqual(new Timestamp(2, 0))).to.be.true; + }); + + it('has an update() method', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([updateOp('doc', 'bar')]), + response: successResponse(2), + }, + ]); + const doc = firestore.doc('collectionId/doc'); + const writeResult = await bulkWriter.update(doc, {foo: 'bar'}); + incrementOpCount(); + await bulkWriter.close(); + verifyOpCount(1); + expect(writeResult.writeTime.isEqual(new Timestamp(2, 0))).to.be.true; + }); + + it('has a delete() method', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([deleteOp('doc')]), + response: successResponse(2), + }, + ]); + const doc = firestore.doc('collectionId/doc'); + const writeResult = await bulkWriter.delete(doc); + incrementOpCount(); + await bulkWriter.close(); + verifyOpCount(1); + expect(writeResult.writeTime.isEqual(new Timestamp(2, 0))).to.be.true; + }); + + it('has a create() method', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([createOp('doc', 'bar')]), + response: successResponse(2), + }, + ]); + const doc = firestore.doc('collectionId/doc'); + const writeResult = await bulkWriter.create(doc, {foo: 'bar'}); + incrementOpCount(); + await bulkWriter.close(); + verifyOpCount(1); + expect(writeResult.writeTime.isEqual(new Timestamp(2, 0))).to.be.true; + }); + + it('surfaces errors', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([setOp('doc', 'bar')]), + response: failedResponse(), + }, + ]); + + const doc = firestore.doc('collectionId/doc'); + void bulkWriter.set(doc, {foo: 'bar'}).catch(err => { + incrementOpCount(); + expect(err instanceof BulkWriterError).to.be.true; + expect(err.code).to.equal(Status.DEADLINE_EXCEEDED); + }); + + await bulkWriter.close(); + verifyOpCount(1); + }); + + it('throws UnhandledPromiseRejections if no error handler is passed in', async () => { + let errorThrown = false; + const unhandledDeferred = new Deferred(); + process.on('unhandledRejection', () => { + errorThrown = true; + unhandledDeferred.resolve(); + }); + + const bulkWriter = await instantiateInstance([ + { + request: createRequest([setOp('doc', 'bar')]), + response: failedResponse(), + }, + ]); + + const doc = firestore.doc('collectionId/doc'); + void bulkWriter.set(doc, {foo: 'bar'}); + + await bulkWriter.close(); + await unhandledDeferred.promise; + expect(errorThrown).to.be.true; + }); + + it('swallows UnhandledPromiseRejections if an error handler is passed in', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([setOp('doc', 'bar')]), + response: failedResponse(), + }, + ]); + + const doc = firestore.doc('collectionId/doc'); + void bulkWriter.set(doc, {foo: 'bar'}); + // Set the error handler after calling set() to ensure that the check is + // performed when the promise resolves. + bulkWriter.onWriteError(() => false); + return bulkWriter.close(); + }); + + it('flush() resolves immediately if there are no writes', async () => { + const bulkWriter = await instantiateInstance([]); + return bulkWriter.flush().then(() => verifyOpCount(0)); + }); + + it('adds writes to a new batch after calling flush()', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([createOp('doc', 'bar')]), + response: successResponse(2), + }, + { + request: createRequest([setOp('doc2', 'bar1')]), + response: successResponse(2), + }, + ]); + void bulkWriter + .create(firestore.doc('collectionId/doc'), {foo: 'bar'}) + .then(incrementOpCount); + await bulkWriter.flush(); + void bulkWriter + .set(firestore.doc('collectionId/doc2'), {foo: 'bar1'}) + .then(incrementOpCount); + await bulkWriter.close(); + verifyOpCount(2); + }); + + it('close() sends all writes', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([createOp('doc', 'bar')]), + response: successResponse(2), + }, + ]); + const doc = firestore.doc('collectionId/doc'); + void bulkWriter.create(doc, {foo: 'bar'}).then(incrementOpCount); + await bulkWriter.close(); + verifyOpCount(1); + }); + + it('close() resolves immediately if there are no writes', async () => { + const bulkWriter = await instantiateInstance([]); + return bulkWriter.close().then(() => verifyOpCount(0)); + }); + + it('cannot call methods after close() is called', async () => { + const bulkWriter = await instantiateInstance([]); + + const expected = 'BulkWriter has already been closed.'; + const doc = firestore.doc('collectionId/doc'); + await bulkWriter.close(); + expect(() => bulkWriter.set(doc, {})).to.throw(expected); + expect(() => bulkWriter.create(doc, {})).to.throw(expected); + expect(() => bulkWriter.update(doc, {})).to.throw(expected); + expect(() => bulkWriter.flush()).to.throw(expected); + + // Calling close() multiple times is allowed. + await bulkWriter.close(); + }); + + it('send writes to the same documents in the different batches', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([setOp('doc1', 'bar')]), + response: successResponse(1), + }, + { + request: createRequest([updateOp('doc1', 'bar2')]), + response: successResponse(2), + }, + ]); + + const doc1 = firestore.doc('collectionId/doc1'); + void bulkWriter.set(doc1, {foo: 'bar'}).then(incrementOpCount); + void bulkWriter.update(doc1, {foo: 'bar2'}).then(incrementOpCount); + + await bulkWriter.close(); + verifyOpCount(2); + }); + + it('sends writes to different documents in the same batch', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([setOp('doc1', 'bar'), updateOp('doc2', 'bar')]), + response: mergeResponses([successResponse(1), successResponse(2)]), + }, + ]); + + const doc1 = firestore.doc('collectionId/doc1'); + const doc2 = firestore.doc('collectionId/doc2'); + void bulkWriter.set(doc1, {foo: 'bar'}).then(incrementOpCount); + void bulkWriter.update(doc2, {foo: 'bar'}).then(incrementOpCount); + + await bulkWriter.close(); + verifyOpCount(2); + }); + + it('buffers subsequent operations after reaching maximum pending op count', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([ + setOp('doc1', 'bar'), + setOp('doc2', 'bar'), + setOp('doc3', 'bar'), + ]), + response: mergeResponses([ + successResponse(1), + successResponse(2), + successResponse(3), + ]), + }, + { + request: createRequest([setOp('doc4', 'bar'), setOp('doc5', 'bar')]), + response: mergeResponses([successResponse(4), successResponse(5)]), + }, + ]); + bulkWriter._setMaxPendingOpCount(3); + void bulkWriter + .set(firestore.doc('collectionId/doc1'), {foo: 'bar'}) + .then(incrementOpCount); + void bulkWriter + .set(firestore.doc('collectionId/doc2'), {foo: 'bar'}) + .then(incrementOpCount); + void bulkWriter + .set(firestore.doc('collectionId/doc3'), {foo: 'bar'}) + .then(incrementOpCount); + void bulkWriter + .set(firestore.doc('collectionId/doc4'), {foo: 'bar'}) + .then(incrementOpCount); + expect(bulkWriter._getBufferedOperationsCount()).to.equal(1); + void bulkWriter + .set(firestore.doc('collectionId/doc5'), {foo: 'bar'}) + .then(incrementOpCount); + expect(bulkWriter._getBufferedOperationsCount()).to.equal(2); + await bulkWriter.close(); + verifyOpCount(5); + }); + + it('buffered operations are flushed after being enqueued', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([ + setOp('doc1', 'bar'), + setOp('doc2', 'bar'), + setOp('doc3', 'bar'), + ]), + response: mergeResponses([ + successResponse(1), + successResponse(2), + successResponse(3), + ]), + }, + { + request: createRequest([ + setOp('doc4', 'bar'), + setOp('doc5', 'bar'), + setOp('doc6', 'bar'), + ]), + response: mergeResponses([ + successResponse(4), + successResponse(5), + successResponse(6), + ]), + }, + { + request: createRequest([setOp('doc7', 'bar')]), + response: successResponse(7), + }, + ]); + bulkWriter._setMaxPendingOpCount(6); + bulkWriter._setMaxBatchSize(3); + void bulkWriter + .set(firestore.doc('collectionId/doc1'), {foo: 'bar'}) + .then(incrementOpCount); + void bulkWriter + .set(firestore.doc('collectionId/doc2'), {foo: 'bar'}) + .then(incrementOpCount); + void bulkWriter + .set(firestore.doc('collectionId/doc3'), {foo: 'bar'}) + .then(incrementOpCount); + void bulkWriter + .set(firestore.doc('collectionId/doc4'), {foo: 'bar'}) + .then(incrementOpCount); + void bulkWriter + .set(firestore.doc('collectionId/doc5'), {foo: 'bar'}) + .then(incrementOpCount); + void bulkWriter + .set(firestore.doc('collectionId/doc6'), {foo: 'bar'}) + .then(incrementOpCount); + + // The 7th operation is buffered. We want to check that the operation is + // still sent even though it is not enqueued when close() is called. + void bulkWriter + .set(firestore.doc('collectionId/doc7'), {foo: 'bar'}) + .then(incrementOpCount); + await bulkWriter.close(); + verifyOpCount(7); + }); + + it('runs the success handler', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([ + createOp('doc1', 'bar'), + setOp('doc2', 'bar'), + updateOp('doc3', 'bar'), + deleteOp('doc4'), + ]), + response: mergeResponses([ + successResponse(1), + successResponse(2), + successResponse(3), + successResponse(4), + ]), + }, + ]); + const writeResults: number[] = []; + bulkWriter.onWriteResult((documentRef, result) => { + writeResults.push(result.writeTime.seconds); + }); + void bulkWriter.create(firestore.doc('collectionId/doc1'), {foo: 'bar'}); + void bulkWriter.set(firestore.doc('collectionId/doc2'), {foo: 'bar'}); + void bulkWriter.update(firestore.doc('collectionId/doc3'), {foo: 'bar'}); + void bulkWriter.delete(firestore.doc('collectionId/doc4')); + return bulkWriter.close().then(() => { + expect(writeResults).to.deep.equal([1, 2, 3, 4]); + }); + }); + + it('can retry failed operations with global error callback', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([ + createOp('doc', 'bar'), + setOp('doc1', 'bar'), + updateOp('doc2', 'bar'), + deleteOp('doc3'), + ]), + response: mergeResponses([ + successResponse(1), + failedResponse(Status.CANCELLED), + failedResponse(Status.CANCELLED), + failedResponse(Status.CANCELLED), + ]), + }, + { + request: createRequest([ + setOp('doc1', 'bar'), + updateOp('doc2', 'bar'), + deleteOp('doc3'), + ]), + response: mergeResponses([ + successResponse(2), + successResponse(3), + successResponse(4), + ]), + }, + ]); + const ops: string[] = []; + const writeResults: number[] = []; + bulkWriter.onWriteError(error => { + ops.push(error.operationType); + return true; + }); + bulkWriter.onWriteResult((documentRef, result) => { + ops.push('success'); + writeResults.push(result.writeTime.seconds); + }); + void bulkWriter.create(firestore.doc('collectionId/doc'), {foo: 'bar'}); + void bulkWriter.set(firestore.doc('collectionId/doc1'), {foo: 'bar'}); + void bulkWriter.update(firestore.doc('collectionId/doc2'), {foo: 'bar'}); + void bulkWriter.delete(firestore.doc('collectionId/doc3')); + return bulkWriter.close().then(() => { + expect(ops).to.deep.equal([ + 'success', + 'set', + 'update', + 'delete', + 'success', + 'success', + 'success', + ]); + expect(writeResults).to.deep.equal([1, 2, 3, 4]); + expect(timeoutHandlerCounter).to.equal(1); + }); + }); + + it('errors are still surfaced even if a retry function is specified', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([setOp('doc', 'bar')]), + response: failedResponse(Status.INTERNAL), + }, + ]); + let onWriteErrorCalled = false; + let catchCalled = false; + bulkWriter.onWriteError(() => { + onWriteErrorCalled = true; + return false; + }); + bulkWriter + .set(firestore.doc('collectionId/doc'), {foo: 'bar'}) + .catch(err => { + expect(err.code).to.equal(Status.INTERNAL); + catchCalled = true; + }); + await bulkWriter.flush(); + expect(catchCalled).to.be.true; + expect(onWriteErrorCalled).to.be.true; + }); + + it('retries INTERNAL errors for deletes', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([setOp('doc1', 'bar'), deleteOp('doc2')]), + response: mergeResponses([ + failedResponse(Status.INTERNAL), + failedResponse(Status.INTERNAL), + ]), + }, + { + request: createRequest([deleteOp('doc2')]), + response: successResponse(2), + }, + ]); + + let errorCaught = false; + bulkWriter + .set(firestore.doc('collectionId/doc1'), { + foo: 'bar', + }) + .catch(() => { + errorCaught = true; + }); + const del = bulkWriter.delete(firestore.doc('collectionId/doc2')); + await bulkWriter.close(); + expect((await del).writeTime).to.deep.equal(new Timestamp(2, 0)); + expect(errorCaught).to.be.true; + }); + + it('surfaces errors thrown by user-provided error callback', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([setOp('doc', 'bar')]), + response: failedResponse(Status.INTERNAL), + }, + ]); + let errorCaught = false; + bulkWriter.onWriteError(() => { + throw new Error('User provided error callback failed'); + }); + void bulkWriter + .set(firestore.doc('collectionId/doc'), {foo: 'bar'}) + .catch(err => { + expect(err.message).to.equal('User provided error callback failed'); + errorCaught = true; + }); + await bulkWriter.flush(); + expect(errorCaught).to.be.true; + }); + + it('write fails if user-provided success callback fails', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([setOp('doc', 'bar')]), + response: successResponse(1), + }, + ]); + let errorCaught = false; + bulkWriter.onWriteResult(() => { + throw new Error('User provided success callback failed'); + }); + void bulkWriter + .set(firestore.doc('collectionId/doc'), {foo: 'bar'}) + .catch(err => { + expect(err.message).to.equal('User provided success callback failed'); + errorCaught = true; + }); + await bulkWriter.flush(); + expect(errorCaught).to.be.true; + }); + + it('retries multiple times', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([setOp('doc', 'bar')]), + response: failedResponse(Status.INTERNAL), + }, + { + request: createRequest([setOp('doc', 'bar')]), + response: failedResponse(Status.INTERNAL), + }, + { + request: createRequest([setOp('doc', 'bar')]), + response: failedResponse(Status.INTERNAL), + }, + { + request: createRequest([setOp('doc', 'bar')]), + response: successResponse(1), + }, + ]); + let writeResult = 0; + bulkWriter.onWriteError(() => { + return true; + }); + void bulkWriter + .set(firestore.doc('collectionId/doc'), {foo: 'bar'}) + .then(res => { + writeResult = res.writeTime.seconds; + }); + await bulkWriter.close(); + expect(writeResult).to.equal(1); + expect(timeoutHandlerCounter).to.equal(3); + }); + + it('retries with smaller batch size', async () => { + const nLengthArray = (n: number): number[] => Array.from(Array(n).keys()); + + const bulkWriter = await instantiateInstance([ + { + request: createRequest( + nLengthArray(15).map((_, i) => setOp('doc' + i, 'bar')), + ), + response: mergeResponses( + nLengthArray(15).map(() => failedResponse(Status.ABORTED)), + ), + }, + { + request: createRequest( + nLengthArray(RETRY_MAX_BATCH_SIZE).map((_, i) => + setOp('doc' + i, 'bar'), + ), + ), + response: mergeResponses( + nLengthArray(RETRY_MAX_BATCH_SIZE).map(() => successResponse(1)), + ), + }, + { + request: createRequest( + nLengthArray(15 - RETRY_MAX_BATCH_SIZE).map((_, i) => + setOp('doc' + (i + RETRY_MAX_BATCH_SIZE), 'bar'), + ), + ), + response: mergeResponses( + nLengthArray(15 - RETRY_MAX_BATCH_SIZE).map(() => successResponse(1)), + ), + }, + ]); + for (let i = 0; i < 15; i++) { + void bulkWriter + .set(firestore.doc('collectionId/doc' + i), {foo: 'bar'}) + .then(incrementOpCount); + } + + await bulkWriter.close(); + expect(opCount).to.equal(15); + }); + + it('retries maintain correct write resolution ordering', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([setOp('doc', 'bar')]), + response: failedResponse(Status.INTERNAL), + }, + { + request: createRequest([setOp('doc', 'bar')]), + response: successResponse(1), + }, + { + request: createRequest([setOp('doc2', 'bar')]), + response: successResponse(2), + }, + ]); + const ops: string[] = []; + bulkWriter.onWriteError(() => { + return true; + }); + void bulkWriter + .set(firestore.doc('collectionId/doc'), {foo: 'bar'}) + .then(() => { + ops.push('before_flush'); + }); + await bulkWriter.flush().then(() => { + ops.push('flush'); + }); + void bulkWriter + .set(firestore.doc('collectionId/doc2'), {foo: 'bar'}) + .then(() => { + ops.push('after_flush'); + }); + + expect(ops).to.deep.equal(['before_flush', 'flush']); + await bulkWriter.close(); + expect(ops).to.deep.equal(['before_flush', 'flush', 'after_flush']); + }); + + it('returns the error if no retry is specified', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([setOp('doc', 'bar')]), + response: failedResponse(Status.INTERNAL), + }, + { + request: createRequest([setOp('doc', 'bar')]), + response: failedResponse(Status.INTERNAL), + }, + { + request: createRequest([setOp('doc', 'bar')]), + response: failedResponse(Status.INTERNAL), + }, + { + request: createRequest([setOp('doc', 'bar')]), + response: failedResponse(Status.INTERNAL), + }, + ]); + let code: Status = -1 as Status; + bulkWriter.onWriteError(error => { + return error.failedAttempts < 3; + }); + void bulkWriter + .set(firestore.doc('collectionId/doc'), {foo: 'bar'}) + .catch(err => { + code = err.code; + }); + await bulkWriter.close(); + expect(code).to.equal(Status.INTERNAL); + }); + + it('splits into multiple batches after exceeding maximum batch size', async () => { + const arrayRange = Array.from(new Array(6), (_, i) => i); + const requests = arrayRange.map(i => setOp('doc' + i, 'bar')); + const responses = arrayRange.map(i => successResponse(i)); + const bulkWriter = await instantiateInstance([ + { + request: createRequest([requests[0], requests[1]]), + response: mergeResponses([responses[0], responses[1]]), + }, + { + request: createRequest([requests[2], requests[3]]), + response: mergeResponses([responses[2], responses[3]]), + }, + { + request: createRequest([requests[4], requests[5]]), + response: mergeResponses([responses[4], responses[5]]), + }, + ]); + + bulkWriter._setMaxBatchSize(2); + for (let i = 0; i < 6; i++) { + void bulkWriter + .set(firestore.doc('collectionId/doc' + i), {foo: 'bar'}) + .then(incrementOpCount); + } + + await bulkWriter.close(); + verifyOpCount(6); + }); + + it('sends batches automatically when the batch size limit is reached', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([ + setOp('doc1', 'bar'), + updateOp('doc2', 'bar'), + createOp('doc3', 'bar'), + ]), + response: mergeResponses([ + successResponse(1), + successResponse(2), + successResponse(3), + ]), + }, + { + request: createRequest([deleteOp('doc4')]), + response: successResponse(3), + }, + ]); + + bulkWriter._setMaxBatchSize(3); + const promise1 = bulkWriter + .set(firestore.doc('collectionId/doc1'), {foo: 'bar'}) + .then(incrementOpCount); + const promise2 = bulkWriter + .update(firestore.doc('collectionId/doc2'), {foo: 'bar'}) + .then(incrementOpCount); + const promise3 = bulkWriter + .create(firestore.doc('collectionId/doc3'), {foo: 'bar'}) + .then(incrementOpCount); + + // The 4th write should not sent because it should be in a new batch. + void bulkWriter + .delete(firestore.doc('collectionId/doc4')) + .then(incrementOpCount); + + await Promise.all([promise1, promise2, promise3]); + verifyOpCount(3); + + await bulkWriter.close(); + verifyOpCount(4); + }); + + it('supports different type converters', async () => { + const bulkWriter = await instantiateInstance([ + { + request: createRequest([setOp('doc1', 'boo'), setOp('doc2', 'moo')]), + response: mergeResponses([successResponse(1), successResponse(2)]), + }, + ]); + + class Boo {} + const booConverter = { + toFirestore(): DocumentData { + return {foo: 'boo'}; + }, + fromFirestore(): Boo { + return new Boo(); + }, + }; + + class Moo {} + const mooConverter = { + toFirestore(): DocumentData { + return {foo: 'moo'}; + }, + fromFirestore(): Moo { + return new Moo(); + }, + }; + + const doc1 = firestore.doc('collectionId/doc1').withConverter(booConverter); + const doc2 = firestore.doc('collectionId/doc2').withConverter(mooConverter); + void bulkWriter.set(doc1, new Boo()).then(incrementOpCount); + void bulkWriter.set(doc2, new Moo()).then(incrementOpCount); + await bulkWriter.close(); + verifyOpCount(2); + }); + + it('retries individual writes that fail with ABORTED and UNAVAILABLE errors', async () => { + setTimeoutHandler(setImmediate); + // Create mock responses that simulate one successful write followed by + // failed responses. + const bulkWriter = await instantiateInstance([ + { + request: createRequest([ + setOp('doc1', 'bar'), + setOp('doc2', 'bar2'), + setOp('doc3', 'bar'), + ]), + response: mergeResponses([ + failedResponse(), + failedResponse(Status.UNAVAILABLE), + failedResponse(Status.ABORTED), + ]), + }, + { + request: createRequest([setOp('doc2', 'bar2'), setOp('doc3', 'bar')]), + response: mergeResponses([ + successResponse(2), + failedResponse(Status.ABORTED), + ]), + }, + { + request: createRequest([setOp('doc3', 'bar')]), + response: mergeResponses([successResponse(3)]), + }, + ]); + + // Test writes to the same document in order to verify that retry logic + // is unaffected by the document key. + void bulkWriter + .set(firestore.doc('collectionId/doc1'), { + foo: 'bar', + }) + .catch(incrementOpCount); + const set2 = bulkWriter.set(firestore.doc('collectionId/doc2'), { + foo: 'bar2', + }); + const set3 = bulkWriter.set(firestore.doc('collectionId/doc3'), { + foo: 'bar', + }); + await bulkWriter.close(); + expect((await set2).writeTime).to.deep.equal(new Timestamp(2, 0)); + expect((await set3).writeTime).to.deep.equal(new Timestamp(3, 0)); + + // Check that set1 was not retried + verifyOpCount(1); + }); + + describe('Timeout handler tests', () => { + // Return success responses for all requests. + function instantiateInstance( + options?: BulkWriterOptions, + ): Promise { + const overrides: ApiOverride = { + batchWrite: request => { + const requestLength = request.writes?.length || 0; + const responses = mergeResponses( + Array.from(new Array(requestLength), (_, i) => successResponse(i)), + ); + return response({ + writeResults: responses.writeResults, + status: responses.status, + }); + }, + }; + return createInstance(overrides).then(firestoreClient => { + firestore = firestoreClient; + return firestore.bulkWriter(options); + }); + } + + it('does not send batches if doing so exceeds the rate limit', done => { + void instantiateInstance({throttling: {maxOpsPerSecond: 5}}).then( + bulkWriter => { + let timeoutCalled = false; + setTimeoutHandler((_, timeout) => { + if (!timeoutCalled && timeout > 0) { + timeoutCalled = true; + done(); + } + }); + for (let i = 0; i < 500; i++) { + void bulkWriter.set(firestore.doc('collectionId/doc' + i), { + foo: 'bar', + }); + } + // The close() promise will never resolve. Since we do not call the + // callback function in the overridden handler, subsequent requests + // after the timeout will not be made. The close() call is used to + // ensure that the final batch is sent. + void bulkWriter.close(); + }, + ); + }); + }); + + it('retries batchWrite when the RPC fails with retryable error', async () => { + setTimeoutHandler(setImmediate); + let retryAttempts = 0; + function instantiateInstance(): Promise { + const overrides: ApiOverride = { + batchWrite: () => { + retryAttempts++; + if (retryAttempts < 5) { + const error = new GoogleError('Mock batchWrite failed in test'); + error.code = Status.ABORTED; + throw error; + } else { + const mockResponse = successResponse(1); + return response({ + writeResults: mockResponse.writeResults, + status: mockResponse.status, + }); + } + }, + }; + return createInstance(overrides).then(firestoreClient => { + firestore = firestoreClient; + return firestore.bulkWriter(); + }); + } + const bulkWriter = await instantiateInstance(); + let writeResult: WriteResult; + void bulkWriter + .create(firestore.doc('collectionId/doc'), { + foo: 'bar', + }) + .then(result => { + incrementOpCount(); + writeResult = result; + }); + return bulkWriter.close().then(async () => { + expect(writeResult.writeTime.isEqual(new Timestamp(1, 0))).to.be.true; + }); + }); + + it('fails writes after all retry attempts failed', async () => { + setTimeoutHandler((fn, timeout) => { + const expected = + DEFAULT_BACKOFF_INITIAL_DELAY_MS * Math.pow(1.5, timeoutHandlerCounter); + expect(timeout).to.be.within( + (1 - DEFAULT_JITTER_FACTOR) * expected, + (1 + DEFAULT_JITTER_FACTOR) * expected, + ); + timeoutHandlerCounter++; + fn(); + }); + function instantiateInstance(): Promise { + const overrides: ApiOverride = { + batchWrite: () => { + const error = new GoogleError('Mock batchWrite failed in test'); + error.code = Status.ABORTED; + throw error; + }, + }; + return createInstance(overrides).then(firestoreClient => { + firestore = firestoreClient; + return firestore.bulkWriter(); + }); + } + const bulkWriter = await instantiateInstance(); + bulkWriter + .create(firestore.doc('collectionId/doc'), { + foo: 'bar', + }) + .catch(err => { + expect(err instanceof BulkWriterError).to.be.true; + expect(err.code).to.equal(Status.ABORTED); + incrementOpCount(); + }); + return bulkWriter.close().then(() => { + verifyOpCount(1); + expect(timeoutHandlerCounter).to.equal(MAX_RETRY_ATTEMPTS - 1); + }); + }); + + it('applies maximum backoff on retries for RESOURCE_EXHAUSTED', async () => { + setTimeoutHandler((fn, timeout) => { + timeoutHandlerCounter++; + expect(timeout).to.be.within( + (1 - DEFAULT_JITTER_FACTOR) * DEFAULT_BACKOFF_MAX_DELAY_MS, + (1 + DEFAULT_JITTER_FACTOR) * DEFAULT_BACKOFF_MAX_DELAY_MS, + ); + fn(); + }); + function instantiateInstance(): Promise { + const overrides: ApiOverride = { + batchWrite: () => { + const error = new GoogleError('Mock batchWrite failed in test'); + error.code = Status.RESOURCE_EXHAUSTED; + throw error; + }, + }; + return createInstance(overrides).then(firestoreClient => { + firestore = firestoreClient; + return firestore.bulkWriter(); + }); + } + const bulkWriter = await instantiateInstance(); + bulkWriter.onWriteError(err => err.failedAttempts < 5); + bulkWriter + .create(firestore.doc('collectionId/doc'), { + foo: 'bar', + }) + .catch(err => { + expect(err instanceof BulkWriterError).to.be.true; + expect(err.code).to.equal(Status.RESOURCE_EXHAUSTED); + incrementOpCount(); + }); + return bulkWriter.close().then(() => { + verifyOpCount(1); + expect(timeoutHandlerCounter).to.equal(4); + }); + }); + + it('uses the highest backoff found in the batch', async () => { + const expected = [ + DEFAULT_BACKOFF_MAX_DELAY_MS, + DEFAULT_BACKOFF_INITIAL_DELAY_MS * DEFAULT_BACKOFF_FACTOR, + ]; + setTimeoutHandler((fn, timeout) => { + // 1st batch should have max backoff. 2nd batch should have 1 round + // of backoff applied. + expect(timeout).to.be.within( + (1 - DEFAULT_JITTER_FACTOR) * expected[timeoutHandlerCounter], + (1 + DEFAULT_JITTER_FACTOR) * expected[timeoutHandlerCounter], + ); + timeoutHandlerCounter++; + fn(); + }); + const bulkWriter = await instantiateInstance([ + { + request: createRequest([createOp('doc1', 'bar'), setOp('doc2', 'bar')]), + response: mergeResponses([ + failedResponse(Status.RESOURCE_EXHAUSTED), + failedResponse(Status.UNAVAILABLE), + ]), + }, + { + request: createRequest([createOp('doc1', 'bar'), setOp('doc2', 'bar')]), + response: mergeResponses([ + successResponse(1), + failedResponse(Status.UNAVAILABLE), + ]), + }, + { + request: createRequest([setOp('doc2', 'bar')]), + response: successResponse(2), + }, + ]); + + bulkWriter.onWriteError(err => err.failedAttempts < 5); + void bulkWriter.create(firestore.doc('collectionId/doc1'), { + foo: 'bar', + }); + void bulkWriter.set(firestore.doc('collectionId/doc2'), { + foo: 'bar', + }); + return bulkWriter.close().then(() => { + expect(timeoutHandlerCounter).to.equal(2); + }); + }); + + it('sends backoff batch after other enqueued batches', async () => { + setTimeoutHandler(setImmediate); + const bulkWriter = await instantiateInstance([ + { + request: createRequest([createOp('doc1', 'bar')]), + response: failedResponse(Status.RESOURCE_EXHAUSTED), + }, + { + request: createRequest([setOp('doc2', 'bar')]), + response: successResponse(1), + }, + { + request: createRequest([createOp('doc1', 'bar')]), + response: successResponse(2), + }, + ]); + + bulkWriter.onWriteError(err => err.failedAttempts < 5); + void bulkWriter.create(firestore.doc('collectionId/doc1'), { + foo: 'bar', + }); + await bulkWriter.flush(); + void bulkWriter.set(firestore.doc('collectionId/doc2'), { + foo: 'bar', + }); + await bulkWriter.close(); + }); + + describe('if bulkCommit() fails', async () => { + function instantiateInstance(): Promise { + const overrides: ApiOverride = { + batchWrite: () => { + throw new Error('Mock batchWrite failed in test'); + }, + }; + return createInstance(overrides).then(firestoreClient => { + firestore = firestoreClient; + return firestore.bulkWriter(); + }); + } + it('flush() should not fail', async () => { + const bulkWriter = await instantiateInstance(); + void bulkWriter + .create(firestore.doc('collectionId/doc'), {foo: 'bar'}) + .catch(incrementOpCount); + void bulkWriter + .set(firestore.doc('collectionId/doc2'), {foo: 'bar'}) + .catch(incrementOpCount); + await bulkWriter.flush(); + verifyOpCount(2); + + await bulkWriter.close(); + }); + + it('close() should not fail', async () => { + const bulkWriter = await instantiateInstance(); + void bulkWriter + .create(firestore.doc('collectionId/doc'), {foo: 'bar'}) + .catch(incrementOpCount); + void bulkWriter + .set(firestore.doc('collectionId/doc2'), {foo: 'bar'}) + .catch(incrementOpCount); + + await bulkWriter.close(); + verifyOpCount(2); + }); + + it('all individual writes are rejected', async () => { + const bulkWriter = await instantiateInstance(); + void bulkWriter + .create(firestore.doc('collectionId/doc'), {foo: 'bar'}) + .catch(err => { + expect(err.message).to.equal('Mock batchWrite failed in test'); + incrementOpCount(); + }); + + void bulkWriter + .set(firestore.doc('collectionId/doc2'), {foo: 'bar'}) + .catch(err => { + expect(err.message).to.equal('Mock batchWrite failed in test'); + incrementOpCount(); + }); + + await bulkWriter.close(); + verifyOpCount(2); + }); + }); +}); diff --git a/handwritten/firestore/dev/test/bundle.ts b/handwritten/firestore/dev/test/bundle.ts new file mode 100644 index 00000000000..99a4a661704 --- /dev/null +++ b/handwritten/firestore/dev/test/bundle.ts @@ -0,0 +1,405 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {expect} from 'chai'; +import * as extend from 'extend'; +import {afterEach, beforeEach, describe, it} from 'mocha'; +import {firestore, google} from '../protos/firestore_v1_proto_api'; +import {Firestore, QuerySnapshot, Timestamp} from '../src'; +import { + bundleToElementArray, + createInstance, + DATABASE_ROOT, + verifyInstance, +} from './util/helpers'; + +import IBundleElement = firestore.IBundleElement; +import IBundleMetadata = firestore.IBundleMetadata; +import ITimestamp = google.protobuf.ITimestamp; + +export const TEST_BUNDLE_ID = 'test-bundle'; +const TEST_BUNDLE_VERSION = 1; + +export function verifyMetadata( + meta: IBundleMetadata, + createTime: ITimestamp, + totalDocuments: number, + expectEmptyContent = false, +): void { + if (!expectEmptyContent) { + expect(parseInt(meta.totalBytes!.toString())).greaterThan(0); + } else { + expect(parseInt(meta.totalBytes!.toString())).to.equal(0); + } + expect(meta.id).to.equal(TEST_BUNDLE_ID); + expect(meta.version).to.equal(TEST_BUNDLE_VERSION); + expect(meta.totalDocuments).to.equal(totalDocuments); + expect(meta.createTime).to.deep.equal(createTime); +} + +describe('Bundle Builder', () => { + let firestore: Firestore; + + beforeEach(() => { + return createInstance().then(firestoreInstance => { + firestore = firestoreInstance; + }); + }); + + afterEach(() => verifyInstance(firestore)); + + // Tests the testing helper function bundleToElementArray works as expected. + it('succeeds to read length prefixed json with testing function', async () => { + const bundleString = + '20{"a":"string value"}9{"b":123}26{"c":{"d":"nested value"}}'; + const elements = await bundleToElementArray(Buffer.from(bundleString)); + expect(elements).to.deep.equal([ + {a: 'string value'}, + {b: 123}, + {c: {d: 'nested value'}}, + ]); + }); + + it('succeeds with document snapshots', async () => { + const bundle = firestore.bundle(TEST_BUNDLE_ID); + const snap1 = firestore.snapshot_( + { + name: `${DATABASE_ROOT}/documents/collectionId/doc1`, + fields: {foo: {stringValue: 'value'}, bar: {integerValue: '42'}}, + createTime: '1970-01-01T00:00:01.002Z', + updateTime: '1970-01-01T00:00:03.000004Z', + }, + // This should be the bundle read time. + '2020-01-01T00:00:05.000000006Z', + 'json', + ); + // Same document but older read time. + const snap2 = firestore.snapshot_( + { + name: `${DATABASE_ROOT}/documents/collectionId/doc1`, + fields: {foo: {stringValue: 'value'}, bar: {integerValue: '-42'}}, + createTime: '1970-01-01T00:00:01.002Z', + updateTime: '1970-01-01T00:00:03.000004Z', + }, + '1970-01-01T00:00:05.000000006Z', + 'json', + ); + + bundle.add(snap1); + bundle.add(snap2); + // Bundle is expected to be [bundleMeta, snap2Meta, snap2] because `snap1` is newer. + const elements = await bundleToElementArray(bundle.build()); + expect(elements.length).to.equal(3); + + const meta = (elements[0] as IBundleElement).metadata; + verifyMetadata( + meta!, + // `snap1.readTime` is the bundle createTime, because it is larger than `snap2.readTime`. + snap1.readTime.toProto().timestampValue!, + 1, + ); + + // Verify doc1Meta and doc1Snap + const docMeta = (elements[1] as IBundleElement).documentMetadata; + const docSnap = (elements[2] as IBundleElement).document; + expect(docMeta).to.deep.equal({ + name: snap1.toDocumentProto().name, + readTime: snap1.readTime.toProto().timestampValue, + exists: true, + }); + expect(docSnap).to.deep.equal(snap1.toDocumentProto()); + }); + + it('succeeds with query snapshots', async () => { + const bundle = firestore.bundle(TEST_BUNDLE_ID); + const snap = firestore.snapshot_( + { + name: `${DATABASE_ROOT}/documents/collectionId/doc1`, + fields: {foo: {stringValue: 'value'}}, + createTime: '1970-01-01T00:00:01.002Z', + updateTime: '1970-01-01T00:00:03.000004Z', + }, + // This should be the bundle read time. + '2020-01-01T00:00:05.000000006Z', + 'json', + ); + const query = firestore + .collection('collectionId') + .where('value', '==', 'string'); + const querySnapshot = new QuerySnapshot( + query, + snap.readTime, + 1, + () => [snap], + () => [], + ); + + const newQuery = firestore.collection('collectionId'); + const newQuerySnapshot = new QuerySnapshot( + newQuery, + snap.readTime, + 1, + () => [snap], + () => [], + ); + + bundle.add('test-query', querySnapshot); + bundle.add('test-query-new', newQuerySnapshot); + // Bundle is expected to be [bundleMeta, namedQuery, newNamedQuery, snapMeta, snap] + const elements = await bundleToElementArray(bundle.build()); + expect(elements.length).to.equal(5); + + const meta = (elements[0] as IBundleElement).metadata; + verifyMetadata( + meta!, + // `snap.readTime` is the bundle createTime, because it is larger than `snap2.readTime`. + snap.readTime.toProto().timestampValue!, + 1, + ); + + // Verify named query + const namedQuery = elements.find( + e => e.namedQuery?.name === 'test-query', + )!.namedQuery; + const newNamedQuery = elements.find( + e => e.namedQuery?.name === 'test-query-new', + )!.namedQuery; + expect(namedQuery).to.deep.equal({ + name: 'test-query', + readTime: snap.readTime.toProto().timestampValue, + bundledQuery: extend( + true, + {}, + { + parent: query.toProto().parent, + structuredQuery: query.toProto().structuredQuery, + }, + ), + }); + expect(newNamedQuery).to.deep.equal({ + name: 'test-query-new', + readTime: snap.readTime.toProto().timestampValue, + bundledQuery: extend( + true, + {}, + { + parent: newQuery.toProto().parent, + structuredQuery: newQuery.toProto().structuredQuery, + }, + ), + }); + + // Verify docMeta and docSnap + const docMeta = (elements[3] as IBundleElement).documentMetadata; + const docSnap = (elements[4] as IBundleElement).document; + docMeta?.queries?.sort(); + expect(docMeta).to.deep.equal({ + name: snap.toDocumentProto().name, + readTime: snap.readTime.toProto().timestampValue, + exists: true, + queries: ['test-query', 'test-query-new'], + }); + expect(docSnap).to.deep.equal(snap.toDocumentProto()); + }); + + it('succeeds with multiple calls to build()', async () => { + const bundle = firestore.bundle(TEST_BUNDLE_ID); + const snap1 = firestore.snapshot_( + { + name: `${DATABASE_ROOT}/documents/collectionId/doc1`, + fields: {foo: {stringValue: 'value'}, bar: {integerValue: '42'}}, + createTime: '1970-01-01T00:00:01.002Z', + updateTime: '1970-01-01T00:00:03.000004Z', + }, + // This should be the bundle read time. + '2020-01-01T00:00:05.000000006Z', + 'json', + ); + bundle.add(snap1); + // Bundle is expected to be [bundleMeta, doc1Meta, doc1Snap]. + const elements = await bundleToElementArray(bundle.build()); + + expect(elements.length).to.equal(3); + + const meta = (elements[0] as IBundleElement).metadata; + verifyMetadata( + meta!, + // `snap1.readTime` is the bundle createTime, because it is larger than `snap2.readTime`. + snap1.readTime.toProto().timestampValue!, + 1, + ); + + // Verify doc1Meta and doc1Snap + const doc1Meta = (elements[1] as IBundleElement).documentMetadata; + const doc1Snap = (elements[2] as IBundleElement).document; + expect(doc1Meta).to.deep.equal({ + name: snap1.toDocumentProto().name, + readTime: snap1.readTime.toProto().timestampValue, + exists: true, + }); + expect(doc1Snap).to.deep.equal(snap1.toDocumentProto()); + + // Add another document + const snap2 = firestore.snapshot_( + { + name: `${DATABASE_ROOT}/documents/collectionId/doc2`, + fields: {foo: {stringValue: 'value'}, bar: {integerValue: '-42'}}, + createTime: '1970-01-01T00:00:01.002Z', + updateTime: '1970-01-01T00:00:03.000004Z', + }, + '1970-01-01T00:00:05.000000006Z', + 'json', + ); + bundle.add(snap2); + + // Bundle is expected to be [bundleMeta, doc1Meta, doc1Snap, doc2Meta, doc2Snap]. + const newElements = await bundleToElementArray(bundle.build()); + + expect(newElements.length).to.equal(5); + const newMeta = (newElements[0] as IBundleElement).metadata; + verifyMetadata( + newMeta!, + // `snap1.readTime` is the bundle createTime, because it is larger than `snap2.readTime`. + snap1.readTime.toProto().timestampValue!, + 2, + ); + expect(newElements.slice(1, 3)).to.deep.equal(elements.slice(1)); + + // Verify doc2Meta and doc2Snap + const doc2Meta = (newElements[3] as IBundleElement).documentMetadata; + const doc2Snap = (newElements[4] as IBundleElement).document; + expect(doc2Meta).to.deep.equal({ + name: snap2.toDocumentProto().name, + readTime: snap2.readTime.toProto().timestampValue, + exists: true, + }); + expect(doc2Snap).to.deep.equal(snap2.toDocumentProto()); + }); + + it('succeeds when nothing is added', async () => { + const bundle = firestore.bundle(TEST_BUNDLE_ID); + + // `elements` is expected to be [bundleMeta]. + const elements = await bundleToElementArray(bundle.build()); + expect(elements.length).to.equal(1); + + const meta = (elements[0] as IBundleElement).metadata; + verifyMetadata( + meta!, + new Timestamp(0, 0).toProto().timestampValue!, + 0, + true, + ); + }); + + it('handles identical document id from different collections', async () => { + const bundle = firestore.bundle(TEST_BUNDLE_ID); + const snap1 = firestore.snapshot_( + { + name: `${DATABASE_ROOT}/documents/collectionId_A/doc1`, + fields: {foo: {stringValue: 'value'}, bar: {integerValue: '42'}}, + createTime: '1970-01-01T00:00:01.002Z', + updateTime: '1970-01-01T00:00:03.000004Z', + }, + // This should be the bundle read time. + '2020-01-01T00:00:05.000000006Z', + 'json', + ); + // Same document id but different collection + const snap2 = firestore.snapshot_( + { + name: `${DATABASE_ROOT}/documents/collectionId_B/doc1`, + fields: {foo: {stringValue: 'value'}, bar: {integerValue: '-42'}}, + createTime: '1970-01-01T00:00:01.002Z', + updateTime: '1970-01-01T00:00:03.000004Z', + }, + '1970-01-01T00:00:05.000000006Z', + 'json', + ); + + bundle.add(snap1); + bundle.add(snap2); + // Bundle is expected to be [bundleMeta, snap1Meta, snap1, snap2Meta, snap2] because `snap1` is newer. + const elements = await bundleToElementArray(bundle.build()); + expect(elements.length).to.equal(5); + + const meta = (elements[0] as IBundleElement).metadata; + verifyMetadata( + meta!, + // `snap1.readTime` is the bundle createTime, because it is larger than `snap2.readTime`. + snap1.readTime.toProto().timestampValue!, + 2, + ); + + // Verify doc1Meta and doc1Snap + let docMeta = (elements[1] as IBundleElement).documentMetadata; + let docSnap = (elements[2] as IBundleElement).document; + expect(docMeta).to.deep.equal({ + name: snap1.toDocumentProto().name, + readTime: snap1.readTime.toProto().timestampValue, + exists: true, + }); + expect(docSnap).to.deep.equal(snap1.toDocumentProto()); + + // Verify doc2Meta and doc2Snap + docMeta = (elements[3] as IBundleElement).documentMetadata; + docSnap = (elements[4] as IBundleElement).document; + expect(docMeta).to.deep.equal({ + name: snap2.toDocumentProto().name, + readTime: snap2.readTime.toProto().timestampValue, + exists: true, + }); + expect(docSnap).to.deep.equal(snap2.toDocumentProto()); + }); +}); + +describe('Bundle Builder using BigInt', () => { + let firestore: Firestore; + + beforeEach(() => { + return createInstance(undefined, {useBigInt: true}).then( + firestoreInstance => { + firestore = firestoreInstance; + }, + ); + }); + + it('succeeds with document snapshots with BigInt field', async () => { + const bundle = firestore.bundle(TEST_BUNDLE_ID); + const bigIntValue = + BigInt(Number.MAX_SAFE_INTEGER) + BigInt(Number.MAX_SAFE_INTEGER); + const snap = firestore.snapshot_( + { + name: `${DATABASE_ROOT}/documents/collectionId/doc1`, + fields: {foo: {integerValue: bigIntValue.toString()}}, + createTime: '1970-01-01T00:00:01.002Z', + updateTime: '1970-01-01T00:00:03.000004Z', + }, + // This should be the bundle read time. + '2020-01-01T00:00:05.000000006Z', + 'json', + ); + bundle.add(snap); + + // Bundle is expected to be [bundleMeta, snapMeta, snap] + const elements = await bundleToElementArray(bundle.build()); + // The point is to make sure BigInt gets encoded correctly into a string without losing + // precision. + expect(elements[2].document?.fields).to.deep.equal({ + foo: {integerValue: bigIntValue.toString()}, + }); + }); + + afterEach(() => verifyInstance(firestore)); +}); diff --git a/handwritten/firestore/dev/test/collection.ts b/handwritten/firestore/dev/test/collection.ts new file mode 100644 index 00000000000..9c469f429fb --- /dev/null +++ b/handwritten/firestore/dev/test/collection.ts @@ -0,0 +1,301 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {describe, it, beforeEach, afterEach} from 'mocha'; +import {expect} from 'chai'; +import * as through2 from 'through2'; + +import {DocumentReference, Firestore, setLogFunction} from '../src'; +import { + ApiOverride, + createInstance, + DATABASE_ROOT, + document, + InvalidApiUsage, + Post, + postConverter, + requestEquals, + response, + set, + verifyInstance, + writeResult, +} from './util/helpers'; + +// Change the argument to 'console.log' to enable debug output. +setLogFunction(null); + +describe('Collection interface', () => { + let firestore: Firestore; + + beforeEach(() => { + return createInstance().then(firestoreInstance => { + firestore = firestoreInstance; + }); + }); + + afterEach(() => verifyInstance(firestore)); + + it('has doc() method', () => { + const collectionRef = firestore.collection('colId'); + expect(collectionRef.doc); + + let documentRef = collectionRef.doc('docId'); + expect(documentRef).to.be.an.instanceOf(DocumentReference); + expect(collectionRef.id).to.equal('colId'); + expect(documentRef.id).to.equal('docId'); + + expect(() => collectionRef.doc(false as InvalidApiUsage)).to.throw( + 'Value for argument "documentPath" is not a valid resource path. Path must be a non-empty string.', + ); + expect(() => collectionRef.doc(null as InvalidApiUsage)).to.throw( + 'Value for argument "documentPath" is not a valid resource path. Path must be a non-empty string.', + ); + expect(() => collectionRef.doc('')).to.throw( + 'Value for argument "documentPath" is not a valid resource path. Path must be a non-empty string.', + ); + expect(() => (collectionRef as InvalidApiUsage).doc(undefined)).to.throw( + 'Value for argument "documentPath" is not a valid resource path. Path must be a non-empty string.', + ); + expect(() => collectionRef.doc('doc/coll')).to.throw( + 'Value for argument "documentPath" must point to a document, but was "doc/coll". Your path does not contain an even number of components.', + ); + + documentRef = collectionRef.doc('docId/colId/docId'); + expect(documentRef).to.be.an.instanceOf(DocumentReference); + }); + + it('has parent() method', () => { + const collection = firestore.collection('col1/doc/col2'); + expect(collection.path).to.equal('col1/doc/col2'); + const document = collection.parent; + expect(document!.path).to.equal('col1/doc'); + }); + + it('parent() returns null for root', () => { + const collection = firestore.collection('col1'); + expect(collection.parent).to.equal(null); + }); + + it('supports auto-generated ids', () => { + const collectionRef = firestore.collection('collectionId'); + const documentRef = collectionRef.doc(); + expect(documentRef).to.be.an.instanceOf(DocumentReference); + expect(collectionRef.id).to.equal('collectionId'); + expect(documentRef.id).to.have.length(20); + }); + + it('has add() method', () => { + const overrides: ApiOverride = { + commit: request => { + // Verify that the document name uses an auto-generated id. + const docIdRe = + /^projects\/test-project\/databases\/\(default\)\/documents\/collectionId\/[a-zA-Z0-9]{20}$/; + expect(request.writes![0].update!.name).to.match(docIdRe); + delete request.writes![0].update!.name; + + // Verify that the rest of the protobuf matches. + expect(request).to.deep.equal({ + database: DATABASE_ROOT, + writes: [ + { + update: { + fields: {}, + }, + currentDocument: { + exists: false, + }, + }, + ], + }); + + return response({ + commitTime: { + nanos: 0, + seconds: 0, + }, + writeResults: [ + { + updateTime: { + nanos: 0, + seconds: 0, + }, + }, + ], + }); + }, + }; + + return createInstance(overrides).then(firestore => { + const collectionRef = firestore.collection('collectionId'); + const promise = collectionRef.add({}); + expect(promise).to.be.an.instanceOf(Promise); + + return promise.then(documentRef => { + expect(documentRef).to.be.an.instanceOf(DocumentReference); + expect(collectionRef.id).to.equal('collectionId'); + expect(documentRef.id).to.have.length(20); + }); + }); + }); + + it('has list() method', () => { + const overrides: ApiOverride = { + listDocuments: request => { + expect(request).to.deep.eq({ + parent: `${DATABASE_ROOT}/documents/a/b`, + collectionId: 'c', + showMissing: true, + mask: {fieldPaths: []}, + }); + + return response([document('first'), document('second')]); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore + .collection('a/b/c') + .listDocuments() + .then(documentRefs => { + expect(documentRefs[0].id).to.equal('first'); + expect(documentRefs[1].id).to.equal('second'); + }); + }); + }); + + it('has isEqual() method', () => { + const coll1 = firestore.collection('coll1'); + const coll1Equals = firestore.collection('coll1'); + const coll2 = firestore.collection('coll2'); + expect(coll1.isEqual(coll1Equals)).to.be.ok; + expect(coll1.isEqual(coll2)).to.not.be.ok; + }); + + it('for CollectionReference.withConverter().doc()', async () => { + const doc = document('documentId', 'author', 'author', 'title', 'post'); + const overrides: ApiOverride = { + commit: request => { + const expectedRequest = set({ + document: doc, + }); + requestEquals(request, expectedRequest); + + return response(writeResult(1)); + }, + batchGetDocuments: () => { + const stream = through2.obj(); + setImmediate(() => { + stream.push({found: doc, readTime: {seconds: 5, nanos: 6}}); + stream.push(null); + }); + + return stream; + }, + }; + + return createInstance(overrides).then(async firestore => { + const docRef = firestore + .collection('collectionId') + .withConverter(postConverter) + .doc('documentId'); + await docRef.set(new Post('post', 'author')); + const postData = await docRef.get(); + const post = postData.data(); + expect(post).to.not.be.undefined; + expect(post!.toString()).to.equal('post, by author'); + }); + }); + + it('for CollectionReference.withConverter().add()', async () => { + let doc = document('dummy'); + const overrides: ApiOverride = { + commit: request => { + // Extract the auto-generated document ID. + const docId = request.writes![0].update!.name!; + const docIdSplit = docId.split('/'); + doc = document( + docIdSplit[docIdSplit.length - 1], + 'author', + 'author', + 'title', + 'post', + ); + expect(request).to.deep.equal({ + database: DATABASE_ROOT, + writes: [ + { + update: { + fields: { + author: { + stringValue: 'author', + }, + title: { + stringValue: 'post', + }, + }, + name: docId, + }, + currentDocument: { + exists: false, + }, + }, + ], + }); + + return response(writeResult(1)); + }, + batchGetDocuments: () => { + const stream = through2.obj(); + setImmediate(() => { + stream.push({found: doc, readTime: {seconds: 5, nanos: 6}}); + stream.push(null); + }); + return stream; + }, + }; + + return createInstance(overrides).then(async firestore => { + const docRef = await firestore + .collection('collectionId') + .withConverter(postConverter) + .add(new Post('post', 'author')); + const postData = await docRef.get(); + const post = postData.data(); + expect(post).to.not.be.undefined; + expect(post!.toString()).to.equal('post, by author'); + }); + }); + + it('withConverter(null) applies the default converter', async () => { + return createInstance().then(async firestore => { + const docRef = firestore + .collection('collectionId') + .withConverter(postConverter) + .withConverter(null) + .doc('documentId'); + expect(() => docRef.set(new Post('post', 'author'))).to.throw(); + }); + }); + + it('drops the converter when calling CollectionReference.parent()', () => { + return createInstance().then(async firestore => { + const postsCollection = firestore + .collection('users/user1/posts') + .withConverter(postConverter); + + const usersCollection = postsCollection.parent; + expect(usersCollection!.isEqual(firestore.doc('users/user1'))).to.be.true; + }); + }); +}); diff --git a/handwritten/firestore/dev/test/document.ts b/handwritten/firestore/dev/test/document.ts new file mode 100644 index 00000000000..32bb38dcec1 --- /dev/null +++ b/handwritten/firestore/dev/test/document.ts @@ -0,0 +1,2199 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {describe, it, beforeEach, afterEach} from 'mocha'; +import {expect} from 'chai'; +import {GoogleError, Status} from 'google-gax'; +import * as through2 from 'through2'; + +import { + DocumentReference, + FieldPath, + FieldValue, + Firestore, + GeoPoint, + setLogFunction, + Timestamp, +} from '../src'; +import { + ApiOverride, + create, + createInstance, + document, + found, + InvalidApiUsage, + missing, + Post, + postConverter, + postConverterMerge, + remove, + requestEquals, + response, + retrieve, + serverTimestamp, + set, + stream, + update, + updateMask, + verifyInstance, + writeResult, +} from './util/helpers'; +import {Precondition} from '@google-cloud/firestore'; + +const PROJECT_ID = 'test-project'; + +const INVALID_ARGUMENTS_TO_UPDATE = new RegExp( + 'Update\\(\\) requires either ' + + 'a single JavaScript object or an alternating list of field/value pairs ' + + 'that can be followed by an optional precondition.', +); + +// Change the argument to 'console.log' to enable debug output. +setLogFunction(null); + +describe('DocumentReference interface', () => { + let firestore: Firestore; + let documentRef: DocumentReference; + + beforeEach(() => { + return createInstance().then(firestoreInstance => { + firestore = firestoreInstance; + documentRef = firestore.doc('collectionId/documentId'); + }); + }); + + afterEach(() => verifyInstance(firestore)); + + it('has collection() method', () => { + expect(() => documentRef.collection(42 as InvalidApiUsage)).to.throw( + 'Value for argument "collectionPath" is not a valid resource path. Path must be a non-empty string.', + ); + + let collection = documentRef.collection('col'); + expect(collection.id).to.equal('col'); + + expect(() => documentRef.collection('col/doc')).to.throw( + 'Value for argument "collectionPath" must point to a collection, but was "col/doc". Your path does not contain an odd number of components.', + ); + + collection = documentRef.collection('col/doc/col'); + expect(collection.id).to.equal('col'); + }); + + it('has path property', () => { + expect(documentRef.path).to.equal('collectionId/documentId'); + }); + + it('has parent property', () => { + expect(documentRef.parent.path).to.equal('collectionId'); + }); + + it('has isEqual() method', () => { + const doc1 = firestore.doc('coll/doc1'); + const doc1Equals = firestore.doc('coll/doc1'); + const doc2 = firestore.doc('coll/doc1/coll/doc1'); + expect(doc1.isEqual(doc1Equals)).to.be.true; + expect(doc1.isEqual(doc2)).to.be.false; + }); +}); + +describe('serialize document', () => { + let firestore: Firestore; + + beforeEach(() => { + return createInstance().then(firestoreInstance => { + firestore = firestoreInstance; + }); + }); + + afterEach(() => verifyInstance(firestore)); + + it('serializes to Protobuf JS', () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', 'bytes', { + bytesValue: Buffer.from('AG=', 'base64'), + }), + }), + ); + return response(writeResult(1)); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.doc('collectionId/documentId').set({ + bytes: Buffer.from('AG=', 'base64'), + }); + }); + }); + + it("doesn't serialize unsupported types", () => { + expect(() => { + void firestore.doc('collectionId/documentId').set({foo: undefined}); + }).to.throw( + 'Value for argument "data" is not a valid Firestore document. Cannot use "undefined" as a Firestore value (found in field "foo").', + ); + + expect(() => { + void firestore.doc('collectionId/documentId').set({ + foo: FieldPath.documentId(), + }); + }).to.throw( + 'Value for argument "data" is not a valid Firestore document. Cannot use object of type "FieldPath" as a Firestore value (found in field "foo").', + ); + + expect(() => { + class Foo {} + void firestore.doc('collectionId/documentId').set({foo: new Foo()}); + }).to.throw( + 'Value for argument "data" is not a valid Firestore document. Couldn\'t serialize object of type "Foo" (found in field "foo"). Firestore doesn\'t support JavaScript objects with custom prototypes (i.e. objects that were created via the "new" operator).', + ); + + expect(() => { + class Foo {} + void firestore + .doc('collectionId/documentId') + .set(new Foo() as InvalidApiUsage); + }).to.throw( + 'Value for argument "data" is not a valid Firestore document. Couldn\'t serialize object of type "Foo". Firestore doesn\'t support JavaScript objects with custom prototypes (i.e. objects that were created via the "new" operator).', + ); + + expect(() => { + class Foo {} + class Bar extends Foo {} + void firestore + .doc('collectionId/documentId') + .set(new Bar() as InvalidApiUsage); + }).to.throw( + 'Value for argument "data" is not a valid Firestore document. Couldn\'t serialize object of type "Bar". Firestore doesn\'t support JavaScript objects with custom prototypes (i.e. objects that were created via the "new" operator).', + ); + }); + + it('provides custom error for objects from different Firestore instance', () => { + class FieldPath {} + class GeoPoint {} + class Timestamp {} + + const customClasses = [new FieldPath(), new GeoPoint(), new Timestamp()]; + + for (const customClass of customClasses) { + expect(() => { + void firestore + .doc('collectionId/documentId') + .set(customClass as InvalidApiUsage); + }).to.throw( + 'Value for argument "data" is not a valid Firestore document. ' + + `Detected an object of type "${customClass.constructor.name}" that doesn't match the expected instance.`, + ); + } + }); + + it('serializes large numbers into doubles', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', 'largeNumber', { + doubleValue: 18014398509481984, + }), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').set({ + // Set to 2^54, which should be stored as a double. + largeNumber: 18014398509481984, + }); + }); + + it('serializes negative zero into double', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', 'negativeZero', { + doubleValue: -0, + }), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').set({ + // Set to -0, which should be stored as a double. + negativeZero: -0, + }); + }); + + it('serializes date before 1970', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', 'moonLanding', { + timestampValue: { + nanos: 123000000, + seconds: -14182920, + }, + }), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').set({ + moonLanding: new Date('Jul 20 1969 20:18:00.123 UTC'), + }); + }); + + it('supports Moment.js', async () => { + class Moment { + toDate(): Date { + return new Date('Jul 20 1969 20:18:00.123 UTC'); + } + } + + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', 'moonLanding', { + timestampValue: { + nanos: 123000000, + seconds: -14182920, + }, + }), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').set({ + moonLanding: new Moment(), + }); + }); + + it('supports BigInt', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', 'bigIntValue', { + integerValue: '9007199254740992', + }), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').set({ + bigIntValue: BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1), + }); + }); + + it('serializes unicode keys', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', '😀', '😜'), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').set({ + '😀': '😜', + }); + }); + + it('accepts both blob formats', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document( + 'documentId', + 'blob1', + {bytesValue: new Uint8Array([0, 1, 2])}, + 'blob2', + { + bytesValue: Buffer.from([0, 1, 2]), + }, + ), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').set({ + blob1: new Uint8Array([0, 1, 2]), + blob2: Buffer.from([0, 1, 2]), + }); + }); + + it('supports NaN and Infinity', async () => { + const overrides: ApiOverride = { + commit: request => { + const fields = request.writes![0].update!.fields!; + expect(fields.nanValue.doubleValue).to.be.a('number'); + expect(fields.nanValue.doubleValue).to.be.NaN; + expect(fields.posInfinity.doubleValue).to.equal(Infinity); + expect(fields.negInfinity.doubleValue).to.equal(-Infinity); + + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').set({ + nanValue: NaN, + posInfinity: Infinity, + negInfinity: -Infinity, + }); + }); + + it('with invalid geopoint', () => { + expect(() => { + new GeoPoint(57.2999988, 'INVALID' as InvalidApiUsage); + }).to.throw('Value for argument "longitude" is not a valid number'); + + expect(() => { + new GeoPoint('INVALID' as InvalidApiUsage, -4.4499982); + }).to.throw('Value for argument "latitude" is not a valid number'); + + expect(() => { + new (GeoPoint as InvalidApiUsage)(); + }).to.throw('Value for argument "latitude" is not a valid number'); + + expect(() => { + new GeoPoint(NaN, 0); + }).to.throw('Value for argument "latitude" is not a valid number'); + + expect(() => { + new GeoPoint(Infinity, 0); + }).to.throw( + 'Value for argument "latitude" must be within [-90, 90] inclusive, but was: Infinity', + ); + + expect(() => { + new GeoPoint(91, 0); + }).to.throw( + 'Value for argument "latitude" must be within [-90, 90] inclusive, but was: 91', + ); + + expect(() => { + new GeoPoint(90, 181); + }).to.throw( + 'Value for argument "longitude" must be within [-180, 180] inclusive, but was: 181', + ); + }); + + it('resolves infinite nesting', () => { + const obj: {foo?: {}} = {}; + obj.foo = obj; + + expect(() => { + void firestore.doc('collectionId/documentId').update(obj); + }).to.throw( + 'Value for argument "dataOrField" is not a valid Firestore value. Input object is deeper than 20 levels or contains a cycle.', + ); + }); + + it('is able to write a document reference with cycles', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', 'ref', { + referenceValue: `projects/${PROJECT_ID}/databases/(default)/documents/collectionId/documentId`, + }), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + // The Firestore Admin SDK adds a cyclic reference to the 'Firestore' + // member of 'DocumentReference'. We emulate this behavior in this + // test to verify that we can properly serialize DocumentReference + // instances, even if they have cyclic references (we shouldn't try to + // validate them beyond the instanceof check). + const ref = firestore.doc('collectionId/documentId'); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (ref.firestore as any).firestore = firestore; + await ref.set({ref}); + }); + + it('is able to translate FirestoreVector to internal representation with set', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', 'embedding1', { + mapValue: { + fields: { + __type__: { + stringValue: '__vector__', + }, + value: { + arrayValue: { + values: [ + {doubleValue: 0}, + {doubleValue: 1}, + {doubleValue: 2}, + ], + }, + }, + }, + }, + }), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').set({ + embedding1: FieldValue.vector([0, 1, 2]), + }); + }); +}); + +describe('deserialize document', () => { + it('deserializes Protobuf JS', async () => { + const overrides: ApiOverride = { + batchGetDocuments: () => { + return stream( + found( + document('documentId', 'foo', { + bytesValue: Buffer.from('AG=', 'base64'), + }), + ), + ); + }, + }; + + const firestore = await createInstance(overrides); + const res = await firestore.doc('collectionId/documentId').get(); + expect(res.data()).to.deep.eq({foo: Buffer.from('AG=', 'base64')}); + }); + + it('deserializes date before 1970', async () => { + const overrides: ApiOverride = { + batchGetDocuments: () => { + return stream( + found( + document('documentId', 'moonLanding', { + timestampValue: { + nanos: 123000000, + seconds: -14182920, + }, + }), + ), + ); + }, + }; + + const firestore = await createInstance(overrides); + const res = await firestore.doc('collectionId/documentId').get(); + expect(res.get('moonLanding').toMillis()).to.equal( + new Date('Jul 20 1969 20:18:00.123 UTC').getTime(), + ); + }); + + it('returns undefined for unknown fields', async () => { + const overrides: ApiOverride = { + batchGetDocuments: () => { + return stream(found(document('documentId'))); + }, + }; + + const firestore = await createInstance(overrides); + const res = await firestore.doc('collectionId/documentId').get(); + expect(res.get('bar')).to.not.exist; + expect(res.get('bar.foo')).to.not.exist; + }); + + it('supports NaN and Infinity', async () => { + const overrides: ApiOverride = { + batchGetDocuments: () => { + return stream( + found( + document( + 'documentId', + 'nanValue', + {doubleValue: NaN}, + 'posInfinity', + {doubleValue: Infinity}, + 'negInfinity', + {doubleValue: -Infinity}, + ), + ), + ); + }, + }; + + const firestore = await createInstance(overrides); + const res = await firestore.doc('collectionId/documentId').get(); + expect(res.get('nanValue')).to.be.a('number'); + expect(res.get('nanValue')).to.be.NaN; + expect(res.get('posInfinity')).to.equal(Infinity); + expect(res.get('negInfinity')).to.equal(-Infinity); + }); + + it('deserializes BigInt', async () => { + const overrides: ApiOverride = { + batchGetDocuments: () => { + return stream( + found( + document('documentId', 'bigIntValue', { + integerValue: '9007199254740992', + }), + ), + ); + }, + }; + + const firestore = await createInstance(overrides, {useBigInt: true}); + const res = await firestore.doc('collectionId/documentId').get(); + expect(res.get('bigIntValue')).to.be.a('bigint'); + expect(res.get('bigIntValue')).to.equal(BigInt('9007199254740992')); + }); + + it('deserializes FirestoreVector', async () => { + const overrides: ApiOverride = { + batchGetDocuments: () => { + return stream( + found( + document('documentId', 'embedding', { + mapValue: { + fields: { + __type__: { + stringValue: '__vector__', + }, + value: { + arrayValue: { + values: [ + {doubleValue: -41.0}, + {doubleValue: 0}, + {doubleValue: 42}, + ], + }, + }, + }, + }, + }), + ), + ); + }, + }; + + const firestore = await createInstance(overrides); + const res = await firestore.doc('collectionId/documentId').get(); + expect(res.get('embedding')).to.deep.equal( + FieldValue.vector([-41.0, 0, 42]), + ); + }); + + it("doesn't deserialize unsupported types", async () => { + const overrides: ApiOverride = { + batchGetDocuments: () => { + return stream( + found( + document('documentId', 'moonLanding', { + valueType: 'foo', + } as InvalidApiUsage), + ), + ); + }, + }; + + const firestore = await createInstance(overrides); + const doc = await firestore.doc('collectionId/documentId').get(); + expect(() => { + doc.data(); + }).to.throw('Cannot decode type from Firestore Value: {"valueType":"foo"}'); + }); + + it("doesn't deserialize invalid latitude", async () => { + const overrides: ApiOverride = { + batchGetDocuments: () => { + return stream( + found( + document('documentId', 'geoPointValue', { + geoPointValue: { + latitude: 'foo' as InvalidApiUsage, + longitude: -122.947778, + }, + }), + ), + ); + }, + }; + + const firestore = await createInstance(overrides); + const doc = await firestore.doc('collectionId/documentId').get(); + expect(() => doc.data()).to.throw( + 'Value for argument "latitude" is not a valid number.', + ); + }); + + it("doesn't deserialize invalid longitude", async () => { + const overrides: ApiOverride = { + batchGetDocuments: () => { + return stream( + found( + document('documentId', 'geoPointValue', { + geoPointValue: { + latitude: 50.1430847, + longitude: 'foo' as InvalidApiUsage, + }, + }), + ), + ); + }, + }; + + const firestore = await createInstance(overrides); + const doc = await firestore.doc('collectionId/documentId').get(); + expect(() => doc.data()).to.throw( + 'Value for argument "longitude" is not a valid number.', + ); + }); +}); + +describe('get document', () => { + it('returns document', async () => { + const overrides: ApiOverride = { + batchGetDocuments: request => { + requestEquals(request, retrieve('documentId')); + + return stream( + found( + document('documentId', 'foo', { + mapValue: { + fields: { + bar: { + stringValue: 'foobar', + }, + }, + }, + }), + ), + ); + }, + }; + + const firestore = await createInstance(overrides); + const result = await firestore.doc('collectionId/documentId').get(); + expect(result.data()).to.deep.eq({foo: {bar: 'foobar'}}); + expect(result.get('foo')).to.deep.eq({bar: 'foobar'}); + expect(result.get('foo.bar')).to.equal('foobar'); + expect(result.get(new FieldPath('foo', 'bar'))).to.equal('foobar'); + expect(result.ref.id).to.equal('documentId'); + }); + + it('returns read, update and create times', async () => { + const overrides: ApiOverride = { + batchGetDocuments: () => { + return stream(found(document('documentId'))); + }, + }; + + const firestore = await createInstance(overrides); + const result = await firestore.doc('collectionId/documentId').get(); + expect(result.createTime!.isEqual(new Timestamp(1, 2))).to.be.true; + expect(result.updateTime!.isEqual(new Timestamp(3, 4))).to.be.true; + expect(result.readTime.isEqual(new Timestamp(5, 6))).to.be.true; + }); + + it('returns not found', async () => { + const overrides: ApiOverride = { + batchGetDocuments: () => { + return stream(missing('documentId')); + }, + }; + + const firestore = await createInstance(overrides); + const result = await firestore.doc('collectionId/documentId').get(); + expect(result.exists).to.be.false; + expect(result.readTime.isEqual(new Timestamp(5, 6))).to.be.true; + expect(result.data()).to.not.exist; + expect(result.get('foo')).to.not.exist; + }); + + it('throws error', done => { + const overrides: ApiOverride = { + batchGetDocuments: () => { + const error = new GoogleError('RPC Error'); + error.code = Status.PERMISSION_DENIED; + return stream(error); + }, + }; + + void createInstance(overrides).then(firestore => { + firestore + .doc('collectionId/documentId') + .get() + .catch(err => { + expect(err.message).to.equal('RPC Error'); + done(); + }); + }); + }); + + it('cannot obtain field value without field path', async () => { + const overrides: ApiOverride = { + batchGetDocuments: () => { + return stream( + found( + document('documentId', 'foo', { + mapValue: { + fields: { + bar: { + stringValue: 'foobar', + }, + }, + }, + }), + ), + ); + }, + }; + + const firestore = await createInstance(overrides); + const doc = await firestore.doc('collectionId/documentId').get(); + expect(() => (doc as InvalidApiUsage).get()).to.throw( + 'Value for argument "field" is not a valid field path. The path cannot be omitted.', + ); + }); +}); + +describe('delete document', () => { + let firestore: Firestore; + + beforeEach(() => { + return createInstance().then(firestoreClient => { + firestore = firestoreClient; + }); + }); + + afterEach(() => verifyInstance(firestore)); + + it('generates proto', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals(request, remove('documentId')); + + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').delete(); + }); + + it('returns update time', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals(request, remove('documentId')); + + return response({ + commitTime: { + nanos: 123000000, + seconds: 479978400, + }, + writeResults: [{}], + }); + }, + }; + + const firestore = await createInstance(overrides); + const res = await firestore.doc('collectionId/documentId').delete(); + expect(res.writeTime.isEqual(new Timestamp(479978400, 123000000))).to.be + .true; + }); + + it('with last update time precondition', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + remove('documentId', { + updateTime: { + nanos: 123000000, + seconds: '479978400', + }, + }), + ); + + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + const docRef = firestore.doc('collectionId/documentId'); + + await Promise.all([ + docRef.delete({ + lastUpdateTime: new Timestamp(479978400, 123000000), + }), + docRef.delete({ + lastUpdateTime: Timestamp.fromMillis(479978400123), + }), + docRef.delete({ + lastUpdateTime: Timestamp.fromDate(new Date(479978400123)), + }), + ]); + }); + + it('with invalid last update time precondition', () => { + expect(() => { + return firestore.doc('collectionId/documentId').delete({ + lastUpdateTime: 1337 as InvalidApiUsage, + }); + }).to.throw('"lastUpdateTime" is not a Firestore Timestamp.'); + }); + + it('throws if "exists" is not a boolean', () => { + expect(() => { + return firestore.doc('collectionId/documentId').delete({ + exists: 42, + } as InvalidApiUsage); + }).to.throw('"exists" is not a boolean.'); + }); + + it('throws if no delete conditions are provided', () => { + expect(() => { + return firestore + .doc('collectionId/documentId') + .delete(42 as InvalidApiUsage); + }).to.throw('Input is not an object.'); + }); + + it('throws if more than one condition is provided', () => { + expect(() => { + return firestore.doc('collectionId/documentId').delete({ + exists: false, + lastUpdateTime: Timestamp.now(), + } as InvalidApiUsage); + }).to.throw('Input specifies more than one precondition.'); + }); +}); + +describe('set document', () => { + let firestore: Firestore; + + beforeEach(() => { + return createInstance().then(firestoreClient => { + firestore = firestoreClient; + }); + }); + + afterEach(() => verifyInstance(firestore)); + + it('supports empty map', () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId'), + }), + ); + return response(writeResult(1)); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.doc('collectionId/documentId').set({}); + }); + }); + + it('supports nested empty map', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', 'a', { + mapValue: {}, + }), + }), + ); + return response(writeResult(1)); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.doc('collectionId/documentId').set({a: {}}); + }); + }); + + it('skips merges with just field transform', () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId'), + transforms: [serverTimestamp('a'), serverTimestamp('b.c')], + mask: updateMask(), + }), + ); + return response(writeResult(1)); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.doc('collectionId/documentId').set( + { + a: FieldValue.serverTimestamp(), + b: {c: FieldValue.serverTimestamp()}, + }, + {merge: true}, + ); + }); + }); + + it('sends empty non-merge write even with just field transform', () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId'), + transforms: [serverTimestamp('a'), serverTimestamp('b.c')], + }), + ); + return response(writeResult(1)); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.doc('collectionId/documentId').set({ + a: FieldValue.serverTimestamp(), + b: {c: FieldValue.serverTimestamp()}, + }); + }); + }); + + it('supports document merges', () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', 'a', 'b', 'c', { + mapValue: { + fields: { + d: { + stringValue: 'e', + }, + }, + }, + }), + mask: updateMask('a', 'c.d', 'f'), + }), + ); + return response(writeResult(1)); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore + .doc('collectionId/documentId') + .set({a: 'b', c: {d: 'e'}, f: FieldValue.delete()}, {merge: true}); + }); + }); + + it('supports document merges with field mask', () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document( + 'documentId', + 'a', + 'foo', + 'b', + { + mapValue: { + fields: { + c: { + stringValue: 'foo', + }, + }, + }, + }, + 'd', + { + mapValue: { + fields: { + e: { + stringValue: 'foo', + }, + }, + }, + }, + ), + mask: updateMask('a', 'b', 'd.e', 'f'), + }), + ); + return response(writeResult(1)); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.doc('collectionId/documentId').set( + { + a: 'foo', + b: {c: 'foo'}, + d: {e: 'foo', ignore: 'foo'}, + f: FieldValue.delete(), + ignore: 'foo', + ignoreMap: {a: 'foo'}, + }, + {mergeFields: ['a', new FieldPath('b'), 'd.e', 'f']}, + ); + }); + }); + + it('supports document merges with empty field mask', () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId'), + mask: updateMask(), + }), + ); + return response(writeResult(1)); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.doc('collectionId/documentId').set( + {}, + { + mergeFields: [], + }, + ); + }); + }); + + it('supports document merges with field mask and empty maps', () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document( + 'documentId', + 'a', + { + mapValue: { + fields: { + b: { + mapValue: {}, + }, + }, + }, + }, + 'c', + { + mapValue: { + fields: { + d: { + mapValue: {}, + }, + }, + }, + }, + ), + mask: updateMask('a', 'c.d'), + }), + ); + return response(writeResult(1)); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.doc('collectionId/documentId').set( + { + a: {b: {}}, + c: {d: {}}, + }, + {mergeFields: ['a', new FieldPath('c', 'd')]}, + ); + }); + }); + + it('supports document merges with field mask and field transform', () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId'), + mask: updateMask('b', 'f'), + transforms: [ + serverTimestamp('a'), + serverTimestamp('b.c'), + serverTimestamp('d.e'), + ], + }), + ); + return response(writeResult(1)); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.doc('collectionId/documentId').set( + { + a: FieldValue.serverTimestamp(), + b: {c: FieldValue.serverTimestamp()}, + d: { + e: FieldValue.serverTimestamp(), + ignore: FieldValue.serverTimestamp(), + }, + f: FieldValue.delete(), + ignore: FieldValue.serverTimestamp(), + ignoreMap: {a: FieldValue.serverTimestamp()}, + }, + {mergeFields: ['a', new FieldPath('b'), 'd.e', 'f']}, + ); + }); + }); + + it('supports empty merge', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId'), + mask: updateMask(), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').set({}, {merge: true}); + }); + + it('supports nested empty merge', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', 'a', { + mapValue: {}, + }), + mask: updateMask('a'), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').set( + {a: {}}, + { + merge: true, + }, + ); + }); + + it('supports partials with merge', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', 'title', { + stringValue: 'story', + }), + mask: updateMask('title'), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore + .doc('collectionId/documentId') + .withConverter(postConverterMerge) + .set({title: 'story'} as Partial, { + merge: true, + }); + }); + + it('supports partials with mergeFields', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', 'title', { + stringValue: 'story', + }), + mask: updateMask('title'), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore + .doc('collectionId/documentId') + .withConverter(postConverterMerge) + .set({title: 'story', author: 'writer'} as Partial, { + mergeFields: ['title'], + }); + }); + + it("doesn't split on dots", async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', 'a.b', 'c'), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').set({'a.b': 'c'}); + }); + + it('validates merge option', () => { + expect(() => { + void firestore.doc('collectionId/documentId').set( + {foo: 'bar'}, + { + mergeFields: ['foobar'], + }, + ); + }).to.throw('Input data is missing for field "foobar".'); + + expect(() => { + void firestore.doc('collectionId/documentId').set( + {foo: 'bar'}, + { + mergeFields: ['foobar..'], + }, + ); + }).to.throw( + 'Value for argument "options" is not a valid set() options argument. ' + + '"mergeFields" is not valid: Element at index 0 is not a valid ' + + 'field path. Paths must not contain ".." in them.', + ); + + expect(() => { + void firestore + .doc('collectionId/documentId') + .set({foo: 'bar'}, {merge: true, mergeFields: []}); + }).to.throw( + 'Value for argument "options" is not a valid set() options argument. You cannot specify both "merge" and "mergeFields".', + ); + }); + + it('requires an object', () => { + expect(() => { + void firestore + .doc('collectionId/documentId') + .set(null as InvalidApiUsage); + }).to.throw( + 'Value for argument "data" is not a valid Firestore document. Input is not a plain JavaScript object.', + ); + }); + + it("doesn't support non-merge deletes", () => { + expect(() => { + void firestore + .doc('collectionId/documentId') + .set({foo: FieldValue.delete()}); + }).to.throw( + 'Value for argument "data" is not a valid Firestore document. FieldValue.delete() must appear at the top-level and can only be used in update() or set() with {merge:true} (found in field "foo").', + ); + }); + + it("doesn't accept arrays", () => { + expect(() => { + void firestore + .doc('collectionId/documentId') + .set([42] as InvalidApiUsage); + }).to.throw( + 'Value for argument "data" is not a valid Firestore document. Input is not a plain JavaScript object.', + ); + }); +}); + +describe('create document', () => { + let firestore: Firestore; + + beforeEach(() => { + return createInstance().then(firestoreClient => { + firestore = firestoreClient; + }); + }); + + afterEach(() => verifyInstance(firestore)); + + it('generates proto', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals(request, create({document: document('documentId')})); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').create({}); + }); + + it('returns update time', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals(request, create({document: document('documentId')})); + + return response({ + commitTime: { + nanos: 0, + seconds: 0, + }, + writeResults: [ + { + updateTime: { + nanos: 123000000, + seconds: 479978400, + }, + }, + ], + }); + }, + }; + + const firestore = await createInstance(overrides); + const res = await firestore.doc('collectionId/documentId').create({}); + expect(res.writeTime.isEqual(new Timestamp(479978400, 123000000))).to.be + .true; + }); + + it('supports field transform', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + create({ + document: document('documentId'), + transforms: [ + serverTimestamp('field'), + serverTimestamp('map.field'), + ], + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').create({ + field: FieldValue.serverTimestamp(), + map: {field: FieldValue.serverTimestamp()}, + }); + }); + + it('supports nested empty map', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + create({ + document: document('documentId', 'a', { + mapValue: { + fields: { + b: { + mapValue: {}, + }, + }, + }, + }), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').create({a: {b: {}}}); + }); + + it('requires an object', () => { + expect(() => { + void firestore + .doc('collectionId/documentId') + .create(null as InvalidApiUsage); + }).to.throw( + 'Value for argument "data" is not a valid Firestore document. Input is not a plain JavaScript object.', + ); + }); + + it("doesn't accept arrays", () => { + expect(() => { + void firestore + .doc('collectionId/documentId') + .create([42] as InvalidApiUsage); + }).to.throw( + 'Value for argument "data" is not a valid Firestore document. Input is not a plain JavaScript object.', + ); + }); +}); + +describe('update document', () => { + let firestore: Firestore; + + beforeEach(() => { + return createInstance().then(firestoreClient => { + firestore = firestoreClient; + }); + }); + + afterEach(() => verifyInstance(firestore)); + + it('generates proto', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + update({ + document: document('documentId', 'foo', 'bar'), + mask: updateMask('foo'), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').update({foo: 'bar'}); + }); + + it('supports nested field transform', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + update({ + document: document('documentId', 'foo', { + mapValue: {}, + }), + transforms: [serverTimestamp('a.b'), serverTimestamp('c.d')], + mask: updateMask('a', 'foo'), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').update({ + foo: {}, + a: {b: FieldValue.serverTimestamp()}, + 'c.d': FieldValue.serverTimestamp(), + }); + }); + + it('skips write for single field transform', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + update({ + document: document('documentId'), + transforms: [serverTimestamp('a')], + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore + .doc('collectionId/documentId') + .update('a', FieldValue.serverTimestamp()); + }); + + it('supports nested empty map', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + update({ + document: document('documentId', 'a', { + mapValue: {}, + }), + mask: updateMask('a'), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').update({a: {}}); + }); + + it('supports nested delete', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + update({document: document('documentId'), mask: updateMask('a.b')}), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').update({ + 'a.b': FieldValue.delete(), + }); + }); + + it('allows explicitly specifying {exists:true} precondition', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + update({ + document: document('documentId', 'foo', 'bar'), + mask: updateMask('foo'), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore + .doc('collectionId/documentId') + .update('foo', 'bar', {exists: true}); + }); + + it('returns update time', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + update({ + document: document('documentId', 'foo', 'bar'), + mask: updateMask('foo'), + }), + ); + return response({ + commitTime: { + nanos: 0, + seconds: 0, + }, + writeResults: [ + { + updateTime: { + nanos: 123000000, + seconds: 479978400, + }, + }, + ], + }); + }, + }; + + const firestore = await createInstance(overrides); + const res = await firestore + .doc('collectionId/documentId') + .update({foo: 'bar'}); + expect(res.writeTime.isEqual(new Timestamp(479978400, 123000000))).to.be + .true; + }); + + it('with last update time precondition', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + update({ + document: document('documentId', 'foo', 'bar'), + mask: updateMask('foo'), + precondition: { + updateTime: { + nanos: 123000000, + seconds: '479978400', + }, + }, + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await Promise.all([ + firestore.doc('collectionId/documentId').update( + {foo: 'bar'}, + { + lastUpdateTime: new Timestamp(479978400, 123000000), + }, + ), + firestore.doc('collectionId/documentId').update('foo', 'bar', { + lastUpdateTime: new Timestamp(479978400, 123000000), + }), + ]); + }); + + it('with invalid last update time precondition', () => { + expect(() => { + const malformedPrecondition: Precondition = { + lastUpdateTime: 'foo', + } as unknown as Precondition; + void firestore + .doc('collectionId/documentId') + .update({foo: 'bar'}, malformedPrecondition); + }).to.throw('"lastUpdateTime" is not a Firestore Timestamp.'); + }); + + it('requires at least one field', () => { + expect(() => { + void firestore.doc('collectionId/documentId').update({}); + }).to.throw('At least one field must be updated.'); + + expect(() => { + (firestore.doc('collectionId/documentId') as InvalidApiUsage).update(); + }).to.throw( + 'Function "DocumentReference.update()" requires at least 1 argument.', + ); + }); + + it('rejects nested deletes', () => { + expect(() => { + void firestore.doc('collectionId/documentId').update({ + a: {b: FieldValue.delete()}, + }); + }).to.throw( + 'Update() requires either a single JavaScript object or an alternating list of field/value pairs that can be followed by an optional precondition. Value for argument "dataOrField" is not a valid Firestore value. FieldValue.delete() must appear at the top-level and can only be used in update() or set() with {merge:true} (found in field "a.b").', + ); + + expect(() => { + void firestore.doc('collectionId/documentId').update('a', { + b: FieldValue.delete(), + }); + }).to.throw( + 'Update() requires either a single JavaScript object or an alternating list of field/value pairs that can be followed by an optional precondition. Element at index 1 is not a valid Firestore value. FieldValue.delete() must appear at the top-level and can only be used in update() or set() with {merge:true} (found in field "a.b").', + ); + + expect(() => { + void firestore + .doc('collectionId/documentId') + .update('a', FieldValue.arrayUnion(FieldValue.delete())); + }).to.throw( + 'Element at index 0 is not a valid array element. FieldValue.delete() cannot be used inside of an array.', + ); + }); + + it('with top-level document', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + update({ + document: document('documentId', 'foo', 'bar'), + mask: updateMask('foo'), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').update({ + foo: 'bar', + }); + }); + + it('with nested document', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + update({ + document: document( + 'documentId', + 'a', + { + mapValue: { + fields: { + b: { + mapValue: { + fields: { + c: { + stringValue: 'foobar', + }, + }, + }, + }, + }, + }, + }, + 'foo', + { + mapValue: { + fields: { + bar: { + stringValue: 'foobar', + }, + }, + }, + }, + ), + mask: updateMask('a.b.c', 'foo.bar'), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await Promise.all([ + firestore.doc('collectionId/documentId').update({ + 'foo.bar': 'foobar', + 'a.b.c': 'foobar', + }), + firestore + .doc('collectionId/documentId') + .update('foo.bar', 'foobar', new FieldPath('a', 'b', 'c'), 'foobar'), + ]); + }); + + it('with two nested fields ', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + update({ + document: document('documentId', 'foo', { + mapValue: { + fields: { + bar: {stringValue: 'two'}, + deep: { + mapValue: { + fields: { + bar: {stringValue: 'two'}, + foo: {stringValue: 'one'}, + }, + }, + }, + foo: {stringValue: 'one'}, + }, + }, + }), + mask: updateMask( + 'foo.bar', + 'foo.deep.bar', + 'foo.deep.foo', + 'foo.foo', + ), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await Promise.all([ + firestore.doc('collectionId/documentId').update({ + 'foo.foo': 'one', + 'foo.bar': 'two', + 'foo.deep.foo': 'one', + 'foo.deep.bar': 'two', + }), + firestore + .doc('collectionId/documentId') + .update( + 'foo.foo', + 'one', + 'foo.bar', + 'two', + 'foo.deep.foo', + 'one', + 'foo.deep.bar', + 'two', + ), + ]); + }); + + it('with nested field and document transform ', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + update({ + document: document('documentId', 'a', { + mapValue: { + fields: { + b: { + mapValue: { + fields: { + keep: { + stringValue: 'keep', + }, + }, + }, + }, + c: { + mapValue: { + fields: { + keep: { + stringValue: 'keep', + }, + }, + }, + }, + }, + }, + }), + mask: updateMask( + 'a.b.delete', + 'a.b.keep', + 'a.c.delete', + 'a.c.keep', + ), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides); + await firestore.doc('collectionId/documentId').update({ + 'a.b.delete': FieldValue.delete(), + 'a.b.keep': 'keep', + 'a.c.delete': FieldValue.delete(), + 'a.c.keep': 'keep', + }); + }); + + it('with field with dot ', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + update({ + document: document('documentId', 'a.b', 'c'), + mask: updateMask('`a.b`'), + }), + ); + return response(writeResult(1)); + }, + }; + const firestore = await createInstance(overrides); + await firestore + .doc('collectionId/documentId') + .update(new FieldPath('a.b'), 'c'); + }); + + it('with conflicting update', () => { + expect(() => { + void firestore.doc('collectionId/documentId').update({ + foo: 'foobar', + 'foo.bar': 'foobar', + }); + }).to.throw( + 'Value for argument "dataOrField" is not a valid update map. Field "foo" was specified multiple times.', + ); + + expect(() => { + void firestore.doc('collectionId/documentId').update({ + foo: 'foobar', + 'foo.bar.foobar': 'foobar', + }); + }).to.throw( + 'Value for argument "dataOrField" is not a valid update map. Field "foo" was specified multiple times.', + ); + + expect(() => { + void firestore.doc('collectionId/documentId').update({ + 'foo.bar': 'foobar', + foo: 'foobar', + }); + }).to.throw( + 'Value for argument "dataOrField" is not a valid update map. Field "foo" was specified multiple times.', + ); + + expect(() => { + void firestore.doc('collectionId/documentId').update({ + 'foo.bar': 'foobar', + 'foo.bar.foo': 'foobar', + }); + }).to.throw( + 'Value for argument "dataOrField" is not a valid update map. Field "foo.bar" was specified multiple times.', + ); + + expect(() => { + void firestore.doc('collectionId/documentId').update({ + 'foo.bar': {foo: 'foobar'}, + 'foo.bar.foo': 'foobar', + }); + }).to.throw( + 'Value for argument "dataOrField" is not a valid update map. Field "foo.bar" was specified multiple times.', + ); + + expect(() => { + void firestore + .doc('collectionId/documentId') + .update('foo.bar', 'foobar', 'foo', 'foobar'); + }).to.throw( + 'Value for argument "dataOrField" is not a valid update map. Field "foo" was specified multiple times.', + ); + + expect(() => { + void firestore + .doc('collectionId/documentId') + .update('foo', {foobar: 'foobar'}, 'foo.bar', {foobar: 'foobar'}); + }).to.throw( + 'Value for argument "dataOrField" is not a valid update map. Field "foo" was specified multiple times.', + ); + + expect(() => { + void firestore + .doc('collectionId/documentId') + .update('foo', {foobar: 'foobar'}, 'foo.bar', {foobar: 'foobar'}); + }).to.throw( + 'Value for argument "dataOrField" is not a valid update map. Field "foo" was specified multiple times.', + ); + }); + + it('with valid field paths', () => { + const validFields = ['foo.bar', '_', 'foo.bar.foobar', '\n`']; + + for (let i = 0; i < validFields.length; ++i) { + firestore.collection('col').select(validFields[i]); + } + }); + + it('with empty field path', () => { + expect(() => { + const doc = {'': 'foo'}; + void firestore.doc('col/doc').update(doc); + }).to.throw( + 'Update() requires either a single JavaScript object or an alternating list of field/value pairs that can be followed by an optional precondition. Element at index 0 should not be an empty string.', + ); + }); + + it('with invalid field paths', () => { + const invalidFields = [ + '.a', + 'a.', + '.a.', + 'a..a', + 'a*a', + 'a/a', + 'a[a', + 'a]a', + ]; + + for (let i = 0; i < invalidFields.length; ++i) { + expect(() => { + const doc: {[k: string]: string} = {}; + doc[invalidFields[i]] = 'foo'; + void firestore.doc('col/doc').update(doc); + }).to.throw(/Value for argument ".*" is not a valid field path/); + } + }); + + it("doesn't accept argument after precondition", () => { + expect(() => { + void firestore.doc('collectionId/documentId').update('foo', 'bar', { + exists: false, + }); + }).to.throw(INVALID_ARGUMENTS_TO_UPDATE); + + expect(() => { + void firestore + .doc('collectionId/documentId') + .update({foo: 'bar'}, {exists: true}, 'foo'); + }).to.throw(INVALID_ARGUMENTS_TO_UPDATE); + }); + + it('accepts an object', () => { + expect(() => + firestore.doc('collectionId/documentId').update(null as InvalidApiUsage), + ).to.throw( + 'Value for argument "dataOrField" is not a valid Firestore document. Input is not a plain JavaScript object.', + ); + }); + + it("doesn't accept arrays", () => { + expect(() => + firestore.doc('collectionId/documentId').update([42] as InvalidApiUsage), + ).to.throw( + 'Value for argument "dataOrField" is not a valid Firestore document. Input is not a plain JavaScript object.', + ); + }); + + it('with field delete', () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + update({ + document: document('documentId', 'bar', 'foobar'), + mask: updateMask('bar', 'foo'), + }), + ); + return response(writeResult(1)); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.doc('collectionId/documentId').update({ + foo: FieldValue.delete(), + bar: 'foobar', + }); + }); + }); +}); + +describe('listCollections() method', () => { + it('sorts results', () => { + const overrides: ApiOverride = { + listCollectionIds: request => { + expect(request).to.deep.eq({ + parent: `projects/${PROJECT_ID}/databases/(default)/documents/coll/doc`, + }); + + return response(['second', 'first']); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore + .doc('coll/doc') + .listCollections() + .then(collections => { + expect(collections[0].path).to.equal('coll/doc/first'); + expect(collections[1].path).to.equal('coll/doc/second'); + }); + }); + }); +}); + +describe('withConverter() support', () => { + let firestore: Firestore; + + beforeEach(() => { + return createInstance().then(firestoreInstance => { + firestore = firestoreInstance; + }); + }); + + afterEach(() => verifyInstance(firestore)); + + it('for DocumentReference.get()', async () => { + const doc = document('documentId', 'author', 'author', 'title', 'post'); + const overrides: ApiOverride = { + commit: request => { + const expectedRequest = set({ + document: doc, + }); + requestEquals(request, expectedRequest); + + return response(writeResult(1)); + }, + batchGetDocuments: () => { + const stream = through2.obj(); + setImmediate(() => { + stream.push({found: doc, readTime: {seconds: 5, nanos: 6}}); + stream.push(null); + }); + + return stream; + }, + }; + + return createInstance(overrides).then(async firestore => { + const docRef = firestore + .collection('collectionId') + .doc('documentId') + .withConverter(postConverter); + + await docRef.set(new Post('post', 'author')); + const postData = await docRef.get(); + const post = postData.data(); + expect(post).to.not.be.undefined; + expect(post!.toString()).to.equal('post, by author'); + }); + }); + + it('withConverter(null) applies the default converter', async () => { + return createInstance().then(async firestore => { + const docRef = firestore + .collection('collectionId') + .doc('documentId') + .withConverter(postConverter) + .withConverter(null); + expect(() => docRef.set(new Post('post', 'author'))).to.throw(); + }); + }); +}); diff --git a/handwritten/firestore/dev/test/field-value.ts b/handwritten/firestore/dev/test/field-value.ts new file mode 100644 index 00000000000..1387967415e --- /dev/null +++ b/handwritten/firestore/dev/test/field-value.ts @@ -0,0 +1,281 @@ +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {describe, it} from 'mocha'; +import {expect} from 'chai'; + +import {FieldValue} from '../src'; +import { + ApiOverride, + arrayTransform, + createInstance, + document, + incrementTransform, + InvalidApiUsage, + requestEquals, + response, + serverTimestamp, + set, + writeResult, +} from './util/helpers'; + +function genericFieldValueTests(methodName: string, sentinel: FieldValue) { + it("can't be used inside arrays", () => { + return createInstance().then(firestore => { + const docRef = firestore.doc('coll/doc'); + const expectedErr = new RegExp( + `${methodName}\\(\\) cannot be used inside of an array`, + ); + expect(() => docRef.set({a: [sentinel]})).to.throw(expectedErr); + expect(() => docRef.set({a: {b: [sentinel]}})).to.throw(expectedErr); + expect(() => + docRef.set({ + a: [{b: sentinel}], + }), + ).to.throw(expectedErr); + expect(() => docRef.set({a: {b: {c: [sentinel]}}})).to.throw(expectedErr); + }); + }); + + it("can't be used inside arrayUnion()", () => { + return createInstance().then(firestore => { + const docRef = firestore.doc('collectionId/documentId'); + expect(() => docRef.set({foo: FieldValue.arrayUnion(sentinel)})).to.throw( + `Element at index 0 is not a valid array element. ${methodName}() cannot be used inside of an array.`, + ); + }); + }); + + it("can't be used inside arrayRemove()", () => { + return createInstance().then(firestore => { + const docRef = firestore.doc('collectionId/documentId'); + expect(() => + docRef.set({foo: FieldValue.arrayRemove(sentinel)}), + ).to.throw( + `Element at index 0 is not a valid array element. ${methodName}() cannot be used inside of an array.`, + ); + }); + }); + + it("can't be used with queries", () => { + return createInstance().then(firestore => { + const collRef = firestore.collection('coll'); + expect(() => collRef.where('a', '==', sentinel)).to.throw( + `Value for argument "value" is not a valid query constraint. ${methodName}() can only be used in set(), create() or update().`, + ); + expect(() => collRef.orderBy('a').startAt(sentinel)).to.throw( + `Element at index 0 is not a valid query constraint. ${methodName}() can only be used in set(), create() or update().`, + ); + }); + }); +} + +describe('FieldValue.arrayUnion()', () => { + it('requires one argument', () => { + expect(() => FieldValue.arrayUnion()).to.throw( + 'Function "FieldValue.arrayUnion()" requires at least 1 argument.', + ); + }); + + it('supports isEqual()', () => { + const arrayUnionFoo1 = FieldValue.arrayUnion('foo'); + const arrayUnionFoo2 = FieldValue.arrayUnion('foo'); + const arrayUnionBar = FieldValue.arrayUnion('bar'); + expect(arrayUnionFoo1.isEqual(arrayUnionFoo2)).to.be.true; + expect(arrayUnionFoo1.isEqual(arrayUnionBar)).to.be.false; + }); + + it('can be used with set()', () => { + const overrides: ApiOverride = { + commit: request => { + const expectedRequest = set({ + document: document('documentId', 'foo', 'bar'), + transforms: [ + arrayTransform('field', 'appendMissingElements', 'foo', 'bar'), + arrayTransform('map.field', 'appendMissingElements', 'foo', 'bar'), + ], + }); + + requestEquals(request, expectedRequest); + + return response(writeResult(1)); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.doc('collectionId/documentId').set({ + foo: 'bar', + field: FieldValue.arrayUnion('foo', 'bar'), + map: {field: FieldValue.arrayUnion('foo', 'bar')}, + }); + }); + }); + + it('must not contain directly nested arrays', () => { + return createInstance().then(firestore => { + const docRef = firestore.doc('collectionId/documentId'); + expect(() => docRef.set({foo: FieldValue.arrayUnion([])})).to.throw( + 'Element at index 0 is not a valid array element. Nested arrays are ' + + 'not supported.', + ); + }); + }); + + genericFieldValueTests('FieldValue.arrayUnion', FieldValue.arrayUnion('foo')); +}); + +describe('FieldValue.increment()', () => { + it('requires one argument', () => { + expect(() => (FieldValue as InvalidApiUsage).increment()).to.throw( + 'Function "FieldValue.increment()" requires at least 1 argument.', + ); + }); + + it('validates that operand is number', () => { + return createInstance().then(firestore => { + expect(() => { + return firestore.doc('collectionId/documentId').set({ + foo: FieldValue.increment('foo' as InvalidApiUsage), + }); + }).to.throw( + 'Value for argument "FieldValue.increment()" is not a valid number', + ); + }); + }); + + it('supports isEqual()', () => { + const arrayUnionA = FieldValue.increment(13.37); + const arrayUnionB = FieldValue.increment(13.37); + const arrayUnionC = FieldValue.increment(42); + expect(arrayUnionA.isEqual(arrayUnionB)).to.be.true; + expect(arrayUnionC.isEqual(arrayUnionB)).to.be.false; + }); + + it('can be used with set()', () => { + const overrides: ApiOverride = { + commit: request => { + const expectedRequest = set({ + document: document('documentId', 'foo', 'bar'), + transforms: [ + incrementTransform('field', 42), + incrementTransform('map.field', 13.37), + ], + }); + requestEquals(request, expectedRequest); + return response(writeResult(1)); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.doc('collectionId/documentId').set({ + foo: 'bar', + field: FieldValue.increment(42), + map: {field: FieldValue.increment(13.37)}, + }); + }); + }); + + genericFieldValueTests('FieldValue.increment', FieldValue.increment(42)); +}); + +describe('FieldValue.arrayRemove()', () => { + it('requires one argument', () => { + expect(() => FieldValue.arrayRemove()).to.throw( + 'Function "FieldValue.arrayRemove()" requires at least 1 argument.', + ); + }); + + it('supports isEqual()', () => { + const arrayRemoveFoo1 = FieldValue.arrayUnion('foo'); + const arrayRemoveFoo2 = FieldValue.arrayUnion('foo'); + const arrayRemoveBar = FieldValue.arrayUnion('bar'); + expect(arrayRemoveFoo1.isEqual(arrayRemoveFoo2)).to.be.true; + expect(arrayRemoveFoo1.isEqual(arrayRemoveBar)).to.be.false; + }); + + it('can be used with set()', () => { + const overrides: ApiOverride = { + commit: request => { + const expectedRequest = set({ + document: document('documentId', 'foo', 'bar'), + transforms: [ + arrayTransform('field', 'removeAllFromArray', 'foo', 'bar'), + arrayTransform('map.field', 'removeAllFromArray', 'foo', 'bar'), + ], + }); + requestEquals(request, expectedRequest); + + return response(writeResult(1)); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.doc('collectionId/documentId').set({ + foo: 'bar', + field: FieldValue.arrayRemove('foo', 'bar'), + map: {field: FieldValue.arrayRemove('foo', 'bar')}, + }); + }); + }); + + it('must not contain directly nested arrays', () => { + return createInstance().then(firestore => { + const docRef = firestore.doc('collectionId/documentId'); + expect(() => docRef.set({foo: FieldValue.arrayRemove([])})).to.throw( + 'Element at index 0 is not a valid array element. Nested arrays are ' + + 'not supported.', + ); + }); + }); + + genericFieldValueTests( + 'FieldValue.arrayRemove', + FieldValue.arrayRemove('foo'), + ); +}); + +describe('FieldValue.serverTimestamp()', () => { + it('supports isEqual()', () => { + const firstTimestamp = FieldValue.serverTimestamp(); + const secondTimestamp = FieldValue.serverTimestamp(); + expect(firstTimestamp.isEqual(secondTimestamp)).to.be.true; + }); + + it('can be used with set()', () => { + const overrides: ApiOverride = { + commit: request => { + const expectedRequest = set({ + document: document('documentId', 'foo', 'bar'), + transforms: [serverTimestamp('field'), serverTimestamp('map.field')], + }); + requestEquals(request, expectedRequest); + + return response(writeResult(1)); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.doc('collectionId/documentId').set({ + foo: 'bar', + field: FieldValue.serverTimestamp(), + map: {field: FieldValue.serverTimestamp()}, + }); + }); + }); + + genericFieldValueTests( + 'FieldValue.serverTimestamp', + FieldValue.serverTimestamp(), + ); +}); diff --git a/handwritten/firestore/dev/test/gapic_firestore_admin_v1.ts b/handwritten/firestore/dev/test/gapic_firestore_admin_v1.ts new file mode 100644 index 00000000000..cb1e4171f55 --- /dev/null +++ b/handwritten/firestore/dev/test/gapic_firestore_admin_v1.ts @@ -0,0 +1,6597 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/firestore_admin_v1_proto_api'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it} from 'mocha'; +import * as firestoreadminModule from '../src/v1'; + +import {PassThrough} from 'stream'; + +import { + protobuf, + LROperation, + operationsProtos, + LocationProtos, +} from 'google-gax'; + +// Dynamically loaded proto JSON is needed to get the type information +// to fill in default values for request objects +const root = protobuf.Root.fromJSON( + require('../protos/admin_v1.json'), +).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + +function generateSampleMessage(instance: T) { + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); +} + +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); +} + +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); +} + +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); + } + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); +} + +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); +} + +describe('v1.FirestoreAdminClient', () => { + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new firestoreadminModule.FirestoreAdminClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = new firestoreadminModule.FirestoreAdminClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); + + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + firestoreadminModule.FirestoreAdminClient.servicePath; + assert.strictEqual(servicePath, 'firestore.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + firestoreadminModule.FirestoreAdminClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new firestoreadminModule.FirestoreAdminClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new firestoreadminModule.FirestoreAdminClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new firestoreadminModule.FirestoreAdminClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', + }); + }); + }); + + it('has port', () => { + const port = firestoreadminModule.FirestoreAdminClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new firestoreadminModule.FirestoreAdminClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.firestoreAdminStub, undefined); + await client.initialize(); + assert(client.firestoreAdminStub); + }); + + it('has close method for the initialized client', done => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize().catch(err => { + throw err; + }); + assert(client.firestoreAdminStub); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; + }); + }); + + it('has close method for the non-initialized client', done => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.firestoreAdminStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; + }); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getIndex', () => { + it('invokes getIndex without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetIndexRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetIndexRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Index(), + ); + client.innerApiCalls.getIndex = stubSimpleCall(expectedResponse); + const [response] = await client.getIndex(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIndex without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetIndexRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetIndexRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Index(), + ); + client.innerApiCalls.getIndex = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getIndex( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IIndex | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIndex with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetIndexRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetIndexRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getIndex = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getIndex(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIndex with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetIndexRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetIndexRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getIndex(request), expectedError); + }); + }); + + describe('deleteIndex', () => { + it('invokes deleteIndex without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteIndexRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteIndexRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteIndex = stubSimpleCall(expectedResponse); + const [response] = await client.deleteIndex(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteIndex without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteIndexRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteIndexRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteIndex = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteIndex( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteIndex with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteIndexRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteIndexRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteIndex = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteIndex(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteIndex with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteIndexRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteIndexRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.deleteIndex(request), expectedError); + }); + }); + + describe('getField', () => { + it('invokes getField without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetFieldRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetFieldRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Field(), + ); + client.innerApiCalls.getField = stubSimpleCall(expectedResponse); + const [response] = await client.getField(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getField as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getField as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getField without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetFieldRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetFieldRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Field(), + ); + client.innerApiCalls.getField = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getField( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IField | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getField as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getField as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getField with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetFieldRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetFieldRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getField = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getField(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getField as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getField as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getField with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetFieldRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetFieldRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getField(request), expectedError); + }); + }); + + describe('getDatabase', () => { + it('invokes getDatabase without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetDatabaseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Database(), + ); + client.innerApiCalls.getDatabase = stubSimpleCall(expectedResponse); + const [response] = await client.getDatabase(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDatabase without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetDatabaseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Database(), + ); + client.innerApiCalls.getDatabase = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDatabase( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IDatabase | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDatabase with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetDatabaseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDatabase = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getDatabase(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDatabase with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetDatabaseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getDatabase(request), expectedError); + }); + }); + + describe('listDatabases', () => { + it('invokes listDatabases without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListDatabasesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesResponse(), + ); + client.innerApiCalls.listDatabases = stubSimpleCall(expectedResponse); + const [response] = await client.listDatabases(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDatabases without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListDatabasesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesResponse(), + ); + client.innerApiCalls.listDatabases = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDatabases( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IListDatabasesResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDatabases with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListDatabasesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDatabases = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listDatabases(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDatabases with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListDatabasesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.listDatabases(request), expectedError); + }); + }); + + describe('createUserCreds', () => { + it('invokes createUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateUserCredsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds(), + ); + client.innerApiCalls.createUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.createUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateUserCredsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds(), + ); + client.innerApiCalls.createUserCreds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createUserCreds( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IUserCreds | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateUserCredsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createUserCreds = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createUserCreds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateUserCredsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.createUserCreds(request), expectedError); + }); + }); + + describe('getUserCreds', () => { + it('invokes getUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetUserCredsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds(), + ); + client.innerApiCalls.getUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.getUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetUserCredsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds(), + ); + client.innerApiCalls.getUserCreds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getUserCreds( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IUserCreds | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetUserCredsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getUserCreds = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getUserCreds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetUserCredsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getUserCreds(request), expectedError); + }); + }); + + describe('listUserCreds', () => { + it('invokes listUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListUserCredsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsResponse(), + ); + client.innerApiCalls.listUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.listUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListUserCredsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsResponse(), + ); + client.innerApiCalls.listUserCreds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUserCreds( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IListUserCredsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListUserCredsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listUserCreds = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listUserCreds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListUserCredsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.listUserCreds(request), expectedError); + }); + }); + + describe('enableUserCreds', () => { + it('invokes enableUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.EnableUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.EnableUserCredsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds(), + ); + client.innerApiCalls.enableUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.enableUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.enableUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.enableUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes enableUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.EnableUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.EnableUserCredsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds(), + ); + client.innerApiCalls.enableUserCreds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.enableUserCreds( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IUserCreds | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.enableUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.enableUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes enableUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.EnableUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.EnableUserCredsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.enableUserCreds = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.enableUserCreds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.enableUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.enableUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes enableUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.EnableUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.EnableUserCredsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.enableUserCreds(request), expectedError); + }); + }); + + describe('disableUserCreds', () => { + it('invokes disableUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DisableUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DisableUserCredsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds(), + ); + client.innerApiCalls.disableUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.disableUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.disableUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.disableUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes disableUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DisableUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DisableUserCredsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds(), + ); + client.innerApiCalls.disableUserCreds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.disableUserCreds( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IUserCreds | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.disableUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.disableUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes disableUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DisableUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DisableUserCredsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.disableUserCreds = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.disableUserCreds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.disableUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.disableUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes disableUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DisableUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DisableUserCredsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.disableUserCreds(request), expectedError); + }); + }); + + describe('resetUserPassword', () => { + it('invokes resetUserPassword without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ResetUserPasswordRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ResetUserPasswordRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds(), + ); + client.innerApiCalls.resetUserPassword = stubSimpleCall(expectedResponse); + const [response] = await client.resetUserPassword(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.resetUserPassword as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resetUserPassword as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes resetUserPassword without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ResetUserPasswordRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ResetUserPasswordRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds(), + ); + client.innerApiCalls.resetUserPassword = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.resetUserPassword( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IUserCreds | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.resetUserPassword as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resetUserPassword as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes resetUserPassword with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ResetUserPasswordRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ResetUserPasswordRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.resetUserPassword = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.resetUserPassword(request), expectedError); + const actualRequest = ( + client.innerApiCalls.resetUserPassword as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resetUserPassword as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes resetUserPassword with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ResetUserPasswordRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ResetUserPasswordRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.resetUserPassword(request), expectedError); + }); + }); + + describe('deleteUserCreds', () => { + it('invokes deleteUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteUserCredsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.deleteUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteUserCredsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteUserCreds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteUserCreds( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteUserCredsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteUserCreds = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteUserCreds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteUserCredsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteUserCredsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.deleteUserCreds(request), expectedError); + }); + }); + + describe('getBackup', () => { + it('invokes getBackup without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetBackupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Backup(), + ); + client.innerApiCalls.getBackup = stubSimpleCall(expectedResponse); + const [response] = await client.getBackup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getBackup without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetBackupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Backup(), + ); + client.innerApiCalls.getBackup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBackup( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IBackup | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getBackup with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetBackupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBackup = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getBackup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getBackup with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetBackupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getBackup(request), expectedError); + }); + }); + + describe('listBackups', () => { + it('invokes listBackups without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListBackupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsResponse(), + ); + client.innerApiCalls.listBackups = stubSimpleCall(expectedResponse); + const [response] = await client.listBackups(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listBackups without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListBackupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsResponse(), + ); + client.innerApiCalls.listBackups = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBackups( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IListBackupsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listBackups with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListBackupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBackups = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listBackups(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listBackups with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListBackupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.listBackups(request), expectedError); + }); + }); + + describe('deleteBackup', () => { + it('invokes deleteBackup without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteBackupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBackup = stubSimpleCall(expectedResponse); + const [response] = await client.deleteBackup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteBackup without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteBackupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBackup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteBackup( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteBackup with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteBackupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteBackup = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteBackup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteBackup with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteBackupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.deleteBackup(request), expectedError); + }); + }); + + describe('createBackupSchedule', () => { + it('invokes createBackupSchedule without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateBackupScheduleRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule(), + ); + client.innerApiCalls.createBackupSchedule = + stubSimpleCall(expectedResponse); + const [response] = await client.createBackupSchedule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createBackupSchedule without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateBackupScheduleRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule(), + ); + client.innerApiCalls.createBackupSchedule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createBackupSchedule( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IBackupSchedule | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createBackupSchedule with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateBackupScheduleRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createBackupSchedule = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createBackupSchedule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createBackupSchedule with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateBackupScheduleRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.createBackupSchedule(request), expectedError); + }); + }); + + describe('getBackupSchedule', () => { + it('invokes getBackupSchedule without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetBackupScheduleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule(), + ); + client.innerApiCalls.getBackupSchedule = stubSimpleCall(expectedResponse); + const [response] = await client.getBackupSchedule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getBackupSchedule without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetBackupScheduleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule(), + ); + client.innerApiCalls.getBackupSchedule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBackupSchedule( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IBackupSchedule | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getBackupSchedule with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetBackupScheduleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBackupSchedule = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getBackupSchedule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getBackupSchedule with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetBackupScheduleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getBackupSchedule(request), expectedError); + }); + }); + + describe('listBackupSchedules', () => { + it('invokes listBackupSchedules without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListBackupSchedulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesResponse(), + ); + client.innerApiCalls.listBackupSchedules = + stubSimpleCall(expectedResponse); + const [response] = await client.listBackupSchedules(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listBackupSchedules without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListBackupSchedulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesResponse(), + ); + client.innerApiCalls.listBackupSchedules = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBackupSchedules( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IListBackupSchedulesResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listBackupSchedules with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListBackupSchedulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBackupSchedules = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listBackupSchedules(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listBackupSchedules with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListBackupSchedulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.listBackupSchedules(request), expectedError); + }); + }); + + describe('updateBackupSchedule', () => { + it('invokes updateBackupSchedule without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest(), + ); + request.backupSchedule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateBackupScheduleRequest', + ['backupSchedule', 'name'], + ); + request.backupSchedule.name = defaultValue1; + const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule(), + ); + client.innerApiCalls.updateBackupSchedule = + stubSimpleCall(expectedResponse); + const [response] = await client.updateBackupSchedule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateBackupSchedule without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest(), + ); + request.backupSchedule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateBackupScheduleRequest', + ['backupSchedule', 'name'], + ); + request.backupSchedule.name = defaultValue1; + const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule(), + ); + client.innerApiCalls.updateBackupSchedule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateBackupSchedule( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IBackupSchedule | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateBackupSchedule with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest(), + ); + request.backupSchedule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateBackupScheduleRequest', + ['backupSchedule', 'name'], + ); + request.backupSchedule.name = defaultValue1; + const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateBackupSchedule = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateBackupSchedule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateBackupSchedule with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest(), + ); + request.backupSchedule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateBackupScheduleRequest', + ['backupSchedule', 'name'], + ); + request.backupSchedule.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.updateBackupSchedule(request), expectedError); + }); + }); + + describe('deleteBackupSchedule', () => { + it('invokes deleteBackupSchedule without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteBackupScheduleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBackupSchedule = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteBackupSchedule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteBackupSchedule without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteBackupScheduleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBackupSchedule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteBackupSchedule( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteBackupSchedule with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteBackupScheduleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteBackupSchedule = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteBackupSchedule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteBackupSchedule with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteBackupScheduleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.deleteBackupSchedule(request), expectedError); + }); + }); + + describe('createIndex', () => { + it('invokes createIndex without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateIndexRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateIndexRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createIndex = stubLongRunningCall(expectedResponse); + const [operation] = await client.createIndex(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createIndex without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateIndexRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateIndexRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createIndex = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createIndex( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createIndex with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateIndexRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateIndexRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createIndex = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createIndex(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createIndex with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateIndexRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateIndexRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createIndex = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createIndex(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkCreateIndexProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCreateIndexProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkCreateIndexProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkCreateIndexProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('updateField', () => { + it('invokes updateField without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateFieldRequest(), + ); + request.field ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateFieldRequest', + ['field', 'name'], + ); + request.field.name = defaultValue1; + const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateField = stubLongRunningCall(expectedResponse); + const [operation] = await client.updateField(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateField as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateField as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateField without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateFieldRequest(), + ); + request.field ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateFieldRequest', + ['field', 'name'], + ); + request.field.name = defaultValue1; + const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateField = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateField( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateField as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateField as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateField with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateFieldRequest(), + ); + request.field ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateFieldRequest', + ['field', 'name'], + ); + request.field.name = defaultValue1; + const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateField = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateField(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateField as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateField as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateField with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateFieldRequest(), + ); + request.field ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateFieldRequest', + ['field', 'name'], + ); + request.field.name = defaultValue1; + const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateField = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.updateField(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.updateField as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateField as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkUpdateFieldProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkUpdateFieldProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkUpdateFieldProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkUpdateFieldProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('exportDocuments', () => { + it('invokes exportDocuments without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ExportDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ExportDocumentsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportDocuments = + stubLongRunningCall(expectedResponse); + const [operation] = await client.exportDocuments(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes exportDocuments without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ExportDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ExportDocumentsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportDocuments = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.exportDocuments( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes exportDocuments with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ExportDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ExportDocumentsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportDocuments = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.exportDocuments(request), expectedError); + const actualRequest = ( + client.innerApiCalls.exportDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes exportDocuments with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ExportDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ExportDocumentsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportDocuments = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.exportDocuments(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.exportDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkExportDocumentsProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkExportDocumentsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkExportDocumentsProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkExportDocumentsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('importDocuments', () => { + it('invokes importDocuments without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ImportDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ImportDocumentsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importDocuments = + stubLongRunningCall(expectedResponse); + const [operation] = await client.importDocuments(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes importDocuments without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ImportDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ImportDocumentsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importDocuments = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.importDocuments( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes importDocuments with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ImportDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ImportDocumentsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importDocuments = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.importDocuments(request), expectedError); + const actualRequest = ( + client.innerApiCalls.importDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes importDocuments with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ImportDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ImportDocumentsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importDocuments = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.importDocuments(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.importDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkImportDocumentsProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkImportDocumentsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkImportDocumentsProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkImportDocumentsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('bulkDeleteDocuments', () => { + it('invokes bulkDeleteDocuments without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.BulkDeleteDocumentsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.bulkDeleteDocuments = + stubLongRunningCall(expectedResponse); + const [operation] = await client.bulkDeleteDocuments(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes bulkDeleteDocuments without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.BulkDeleteDocumentsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.bulkDeleteDocuments = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.bulkDeleteDocuments( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes bulkDeleteDocuments with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.BulkDeleteDocumentsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.bulkDeleteDocuments = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.bulkDeleteDocuments(request), expectedError); + const actualRequest = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes bulkDeleteDocuments with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.BulkDeleteDocumentsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.bulkDeleteDocuments = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.bulkDeleteDocuments(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkBulkDeleteDocumentsProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkBulkDeleteDocumentsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkBulkDeleteDocumentsProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkBulkDeleteDocumentsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('createDatabase', () => { + it('invokes createDatabase without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateDatabaseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createDatabase = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createDatabase(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDatabase without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateDatabaseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createDatabase = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDatabase( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDatabase with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateDatabaseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDatabase = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createDatabase(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDatabase with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateDatabaseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDatabase = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createDatabase(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkCreateDatabaseProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCreateDatabaseProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkCreateDatabaseProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkCreateDatabaseProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('updateDatabase', () => { + it('invokes updateDatabase without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateDatabaseRequest(), + ); + request.database ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateDatabaseRequest', + ['database', 'name'], + ); + request.database.name = defaultValue1; + const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateDatabase = + stubLongRunningCall(expectedResponse); + const [operation] = await client.updateDatabase(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDatabase without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateDatabaseRequest(), + ); + request.database ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateDatabaseRequest', + ['database', 'name'], + ); + request.database.name = defaultValue1; + const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateDatabase = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDatabase( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDatabase with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateDatabaseRequest(), + ); + request.database ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateDatabaseRequest', + ['database', 'name'], + ); + request.database.name = defaultValue1; + const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDatabase = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateDatabase(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDatabase with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateDatabaseRequest(), + ); + request.database ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateDatabaseRequest', + ['database', 'name'], + ); + request.database.name = defaultValue1; + const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDatabase = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.updateDatabase(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkUpdateDatabaseProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkUpdateDatabaseProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkUpdateDatabaseProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkUpdateDatabaseProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('deleteDatabase', () => { + it('invokes deleteDatabase without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteDatabaseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.deleteDatabase = + stubLongRunningCall(expectedResponse); + const [operation] = await client.deleteDatabase(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDatabase without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteDatabaseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.deleteDatabase = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDatabase( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDatabase with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteDatabaseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDatabase = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteDatabase(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDatabase with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteDatabaseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDatabase = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.deleteDatabase(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkDeleteDatabaseProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkDeleteDatabaseProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkDeleteDatabaseProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkDeleteDatabaseProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('restoreDatabase', () => { + it('invokes restoreDatabase without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.RestoreDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.RestoreDatabaseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.restoreDatabase = + stubLongRunningCall(expectedResponse); + const [operation] = await client.restoreDatabase(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes restoreDatabase without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.RestoreDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.RestoreDatabaseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.restoreDatabase = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.restoreDatabase( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes restoreDatabase with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.RestoreDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.RestoreDatabaseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.restoreDatabase = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.restoreDatabase(request), expectedError); + const actualRequest = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes restoreDatabase with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.RestoreDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.RestoreDatabaseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.restoreDatabase = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.restoreDatabase(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkRestoreDatabaseProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkRestoreDatabaseProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkRestoreDatabaseProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkRestoreDatabaseProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('cloneDatabase', () => { + it('invokes cloneDatabase without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CloneDatabaseRequest(), + ); + request.pitrSnapshot = {}; + // path template: projects/*/databases/{database_id=*}/** + request.pitrSnapshot.database = 'projects/value/databases/value/value'; + const expectedHeaderRequestParams = 'database_id=value'; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.cloneDatabase = + stubLongRunningCall(expectedResponse); + const [operation] = await client.cloneDatabase(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.cloneDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.cloneDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes cloneDatabase without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CloneDatabaseRequest(), + ); + request.pitrSnapshot = {}; + // path template: projects/*/databases/{database_id=*}/** + request.pitrSnapshot.database = 'projects/value/databases/value/value'; + const expectedHeaderRequestParams = 'database_id=value'; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.cloneDatabase = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.cloneDatabase( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICloneDatabaseMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICloneDatabaseMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.cloneDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.cloneDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes cloneDatabase with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CloneDatabaseRequest(), + ); + request.pitrSnapshot = {}; + // path template: projects/*/databases/{database_id=*}/** + request.pitrSnapshot.database = 'projects/value/databases/value/value'; + const expectedHeaderRequestParams = 'database_id=value'; + const expectedError = new Error('expected'); + client.innerApiCalls.cloneDatabase = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.cloneDatabase(request), expectedError); + const actualRequest = ( + client.innerApiCalls.cloneDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.cloneDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes cloneDatabase with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CloneDatabaseRequest(), + ); + request.pitrSnapshot = {}; + // path template: projects/*/databases/{database_id=*}/** + request.pitrSnapshot.database = 'projects/value/databases/value/value'; + const expectedHeaderRequestParams = 'database_id=value'; + const expectedError = new Error('expected'); + client.innerApiCalls.cloneDatabase = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.cloneDatabase(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.cloneDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.cloneDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkCloneDatabaseProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCloneDatabaseProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkCloneDatabaseProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkCloneDatabaseProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listIndexes', () => { + it('invokes listIndexes without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListIndexesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + ]; + client.innerApiCalls.listIndexes = stubSimpleCall(expectedResponse); + const [response] = await client.listIndexes(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listIndexes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listIndexes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listIndexes without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListIndexesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + ]; + client.innerApiCalls.listIndexes = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listIndexes( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IIndex[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listIndexes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listIndexes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listIndexes with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListIndexesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listIndexes = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listIndexes(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listIndexes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listIndexes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listIndexesStream without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListIndexesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + ]; + client.descriptors.page.listIndexes.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listIndexesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.admin.v1.Index[] = []; + stream.on( + 'data', + (response: protos.google.firestore.admin.v1.Index) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listIndexes.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listIndexes, request), + ); + assert( + (client.descriptors.page.listIndexes.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listIndexesStream with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListIndexesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listIndexes.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listIndexesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.admin.v1.Index[] = []; + stream.on( + 'data', + (response: protos.google.firestore.admin.v1.Index) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listIndexes.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listIndexes, request), + ); + assert( + (client.descriptors.page.listIndexes.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listIndexes without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListIndexesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + ]; + client.descriptors.page.listIndexes.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.firestore.admin.v1.IIndex[] = []; + const iterable = client.listIndexesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listIndexes.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listIndexes.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listIndexes with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListIndexesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listIndexes.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listIndexesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.firestore.admin.v1.IIndex[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listIndexes.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listIndexes.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listFields', () => { + it('invokes listFields without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListFieldsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + ]; + client.innerApiCalls.listFields = stubSimpleCall(expectedResponse); + const [response] = await client.listFields(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listFields as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFields as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listFields without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListFieldsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + ]; + client.innerApiCalls.listFields = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listFields( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IField[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listFields as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFields as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listFields with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListFieldsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listFields = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listFields(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listFields as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFields as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listFieldsStream without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListFieldsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + ]; + client.descriptors.page.listFields.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listFieldsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.admin.v1.Field[] = []; + stream.on( + 'data', + (response: protos.google.firestore.admin.v1.Field) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listFields.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listFields, request), + ); + assert( + (client.descriptors.page.listFields.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listFieldsStream with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListFieldsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listFields.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listFieldsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.admin.v1.Field[] = []; + stream.on( + 'data', + (response: protos.google.firestore.admin.v1.Field) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listFields.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listFields, request), + ); + assert( + (client.descriptors.page.listFields.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listFields without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListFieldsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + ]; + client.descriptors.page.listFields.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.firestore.admin.v1.IField[] = []; + const iterable = client.listFieldsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listFields.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listFields.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listFields with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListFieldsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listFields.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listFieldsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.firestore.admin.v1.IField[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listFields.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listFields.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + describe('getLocation', () => { + it('invokes getLocation without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest(), + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new LocationProtos.google.cloud.location.Location(), + ); + client.locationsClient.getLocation = stubSimpleCall(expectedResponse); + const response = await client.getLocation(request, expectedOptions); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.locationsClient.getLocation as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + it('invokes getLocation without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest(), + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new LocationProtos.google.cloud.location.Location(), + ); + client.locationsClient.getLocation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getLocation( + request, + expectedOptions, + ( + err?: Error | null, + result?: LocationProtos.google.cloud.location.ILocation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.locationsClient.getLocation as SinonStub).getCall(0)); + }); + it('invokes getLocation with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest(), + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.locationsClient.getLocation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getLocation(request, expectedOptions), + expectedError, + ); + assert( + (client.locationsClient.getLocation as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + }); + describe('listLocationsAsync', () => { + it('uses async iteration with listLocations without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.ListLocationsRequest(), + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedResponse = [ + generateSampleMessage( + new LocationProtos.google.cloud.location.Location(), + ), + generateSampleMessage( + new LocationProtos.google.cloud.location.Location(), + ), + generateSampleMessage( + new LocationProtos.google.cloud.location.Location(), + ), + ]; + client.locationsClient.descriptors.page.listLocations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: LocationProtos.google.cloud.location.ILocation[] = []; + const iterable = client.listLocationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.locationsClient.descriptors.page.listLocations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.locationsClient.descriptors.page.listLocations + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + it('uses async iteration with listLocations with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.ListLocationsRequest(), + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedError = new Error('expected'); + client.locationsClient.descriptors.page.listLocations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listLocationsAsync(request); + await assert.rejects(async () => { + const responses: LocationProtos.google.cloud.location.ILocation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.locationsClient.descriptors.page.listLocations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.locationsClient.descriptors.page.listLocations + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + describe('getOperation', () => { + it('invokes getOperation without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const response = await client.getOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.getOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + it('invokes getOperation without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + client.operationsClient.getOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .getOperation( + request, + undefined, + ( + err?: Error | null, + result?: operationsProtos.google.longrunning.Operation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(err => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + it('invokes getOperation with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(async () => { + await client.getOperation(request); + }, expectedError); + assert( + (client.operationsClient.getOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + }); + describe('cancelOperation', () => { + it('invokes cancelOperation without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.cancelOperation = + stubSimpleCall(expectedResponse); + const response = await client.cancelOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.cancelOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + it('invokes cancelOperation without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.cancelOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .cancelOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(err => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.cancelOperation as SinonStub).getCall(0)); + }); + it('invokes cancelOperation with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.cancelOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(async () => { + await client.cancelOperation(request); + }, expectedError); + assert( + (client.operationsClient.cancelOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + }); + describe('deleteOperation', () => { + it('invokes deleteOperation without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.deleteOperation = + stubSimpleCall(expectedResponse); + const response = await client.deleteOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.deleteOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + it('invokes deleteOperation without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.deleteOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .deleteOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(err => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.deleteOperation as SinonStub).getCall(0)); + }); + it('invokes deleteOperation with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.deleteOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(async () => { + await client.deleteOperation(request); + }, expectedError); + assert( + (client.operationsClient.deleteOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + }); + describe('listOperationsAsync', () => { + it('uses async iteration with listOperations without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse(), + ), + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse(), + ), + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse(), + ), + ]; + client.operationsClient.descriptor.listOperations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: operationsProtos.google.longrunning.IOperation[] = []; + const iterable = client.operationsClient.listOperationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.operationsClient.descriptor.listOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + it('uses async iteration with listOperations with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.descriptor.listOperations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.operationsClient.listOperationsAsync(request); + await assert.rejects(async () => { + const responses: operationsProtos.google.longrunning.IOperation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.operationsClient.descriptor.listOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('backup', async () => { + const fakePath = '/rendered/path/backup'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + backup: 'backupValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.backupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.backupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('backupPath', () => { + const result = client.backupPath( + 'projectValue', + 'locationValue', + 'backupValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.backupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBackupName', () => { + const result = client.matchProjectFromBackupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.backupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBackupName', () => { + const result = client.matchLocationFromBackupName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.backupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBackupFromBackupName', () => { + const result = client.matchBackupFromBackupName(fakePath); + assert.strictEqual(result, 'backupValue'); + assert( + (client.pathTemplates.backupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('backupSchedule', async () => { + const fakePath = '/rendered/path/backupSchedule'; + const expectedParameters = { + project: 'projectValue', + database: 'databaseValue', + backup_schedule: 'backupScheduleValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.backupSchedulePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.backupSchedulePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('backupSchedulePath', () => { + const result = client.backupSchedulePath( + 'projectValue', + 'databaseValue', + 'backupScheduleValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.backupSchedulePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBackupScheduleName', () => { + const result = client.matchProjectFromBackupScheduleName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatabaseFromBackupScheduleName', () => { + const result = client.matchDatabaseFromBackupScheduleName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBackupScheduleFromBackupScheduleName', () => { + const result = + client.matchBackupScheduleFromBackupScheduleName(fakePath); + assert.strictEqual(result, 'backupScheduleValue'); + assert( + (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('collectionGroup', async () => { + const fakePath = '/rendered/path/collectionGroup'; + const expectedParameters = { + project: 'projectValue', + database: 'databaseValue', + collection: 'collectionValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.collectionGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.collectionGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('collectionGroupPath', () => { + const result = client.collectionGroupPath( + 'projectValue', + 'databaseValue', + 'collectionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.collectionGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCollectionGroupName', () => { + const result = client.matchProjectFromCollectionGroupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.collectionGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatabaseFromCollectionGroupName', () => { + const result = client.matchDatabaseFromCollectionGroupName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.collectionGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCollectionFromCollectionGroupName', () => { + const result = client.matchCollectionFromCollectionGroupName(fakePath); + assert.strictEqual(result, 'collectionValue'); + assert( + (client.pathTemplates.collectionGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('database', async () => { + const fakePath = '/rendered/path/database'; + const expectedParameters = { + project: 'projectValue', + database: 'databaseValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.databasePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.databasePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('databasePath', () => { + const result = client.databasePath('projectValue', 'databaseValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.databasePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromDatabaseName', () => { + const result = client.matchProjectFromDatabaseName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.databasePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatabaseFromDatabaseName', () => { + const result = client.matchDatabaseFromDatabaseName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.databasePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('field', async () => { + const fakePath = '/rendered/path/field'; + const expectedParameters = { + project: 'projectValue', + database: 'databaseValue', + collection: 'collectionValue', + field: 'fieldValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.fieldPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.fieldPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('fieldPath', () => { + const result = client.fieldPath( + 'projectValue', + 'databaseValue', + 'collectionValue', + 'fieldValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.fieldPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromFieldName', () => { + const result = client.matchProjectFromFieldName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.fieldPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatabaseFromFieldName', () => { + const result = client.matchDatabaseFromFieldName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.fieldPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCollectionFromFieldName', () => { + const result = client.matchCollectionFromFieldName(fakePath); + assert.strictEqual(result, 'collectionValue'); + assert( + (client.pathTemplates.fieldPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchFieldFromFieldName', () => { + const result = client.matchFieldFromFieldName(fakePath); + assert.strictEqual(result, 'fieldValue'); + assert( + (client.pathTemplates.fieldPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('index', async () => { + const fakePath = '/rendered/path/index'; + const expectedParameters = { + project: 'projectValue', + database: 'databaseValue', + collection: 'collectionValue', + index: 'indexValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.indexPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.indexPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('indexPath', () => { + const result = client.indexPath( + 'projectValue', + 'databaseValue', + 'collectionValue', + 'indexValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.indexPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromIndexName', () => { + const result = client.matchProjectFromIndexName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.indexPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatabaseFromIndexName', () => { + const result = client.matchDatabaseFromIndexName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.indexPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCollectionFromIndexName', () => { + const result = client.matchCollectionFromIndexName(fakePath); + assert.strictEqual(result, 'collectionValue'); + assert( + (client.pathTemplates.indexPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchIndexFromIndexName', () => { + const result = client.matchIndexFromIndexName(fakePath); + assert.strictEqual(result, 'indexValue'); + assert( + (client.pathTemplates.indexPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('location', async () => { + const fakePath = '/rendered/path/location'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.locationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.locationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('locationPath', () => { + const result = client.locationPath('projectValue', 'locationValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.locationPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLocationName', () => { + const result = client.matchProjectFromLocationName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromLocationName', () => { + const result = client.matchLocationFromLocationName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('project', async () => { + const fakePath = '/rendered/path/project'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectPath', () => { + const result = client.projectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectName', () => { + const result = client.matchProjectFromProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('userCreds', async () => { + const fakePath = '/rendered/path/userCreds'; + const expectedParameters = { + project: 'projectValue', + database: 'databaseValue', + user_creds: 'userCredsValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userCredsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userCredsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userCredsPath', () => { + const result = client.userCredsPath( + 'projectValue', + 'databaseValue', + 'userCredsValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userCredsPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromUserCredsName', () => { + const result = client.matchProjectFromUserCredsName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.userCredsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatabaseFromUserCredsName', () => { + const result = client.matchDatabaseFromUserCredsName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.userCredsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserCredsFromUserCredsName', () => { + const result = client.matchUserCredsFromUserCredsName(fakePath); + assert.strictEqual(result, 'userCredsValue'); + assert( + (client.pathTemplates.userCredsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + }); +}); diff --git a/handwritten/firestore/dev/test/gapic_firestore_v1.ts b/handwritten/firestore/dev/test/gapic_firestore_v1.ts new file mode 100644 index 00000000000..6060a98713a --- /dev/null +++ b/handwritten/firestore/dev/test/gapic_firestore_v1.ts @@ -0,0 +1,3379 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/firestore_v1_proto_api'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it} from 'mocha'; +import * as firestoreModule from '../src/v1'; + +import {PassThrough} from 'stream'; + +import {protobuf, LocationProtos} from 'google-gax'; + +// Dynamically loaded proto JSON is needed to get the type information +// to fill in default values for request objects +const root = protobuf.Root.fromJSON(require('../protos/v1.json')).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + +function generateSampleMessage(instance: T) { + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); +} + +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); +} + +function stubBidiStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); +} + +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); + } + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); +} + +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); +} + +describe('v1.FirestoreClient', () => { + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new firestoreModule.FirestoreClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = new firestoreModule.FirestoreClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); + + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = firestoreModule.FirestoreClient.servicePath; + assert.strictEqual(servicePath, 'firestore.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = firestoreModule.FirestoreClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new firestoreModule.FirestoreClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new firestoreModule.FirestoreClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new firestoreModule.FirestoreClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new firestoreModule.FirestoreClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new firestoreModule.FirestoreClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', + }); + }); + }); + + it('has port', () => { + const port = firestoreModule.FirestoreClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new firestoreModule.FirestoreClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new firestoreModule.FirestoreClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.firestoreStub, undefined); + await client.initialize(); + assert(client.firestoreStub); + }); + + it('has close method for the initialized client', done => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize().catch(err => { + throw err; + }); + assert(client.firestoreStub); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; + }); + }); + + it('has close method for the non-initialized client', done => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.firestoreStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; + }); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getDocument', () => { + it('invokes getDocument without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.GetDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.GetDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document(), + ); + client.innerApiCalls.getDocument = stubSimpleCall(expectedResponse); + const [response] = await client.getDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDocument without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.GetDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.GetDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document(), + ); + client.innerApiCalls.getDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDocument( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1.IDocument | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDocument with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.GetDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.GetDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDocument = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getDocument(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDocument with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.GetDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.GetDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getDocument(request), expectedError); + }); + }); + + describe('updateDocument', () => { + it('invokes updateDocument without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.UpdateDocumentRequest(), + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.UpdateDocumentRequest', + ['document', 'name'], + ); + request.document.name = defaultValue1; + const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document(), + ); + client.innerApiCalls.updateDocument = stubSimpleCall(expectedResponse); + const [response] = await client.updateDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDocument without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.UpdateDocumentRequest(), + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.UpdateDocumentRequest', + ['document', 'name'], + ); + request.document.name = defaultValue1; + const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document(), + ); + client.innerApiCalls.updateDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDocument( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1.IDocument | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDocument with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.UpdateDocumentRequest(), + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.UpdateDocumentRequest', + ['document', 'name'], + ); + request.document.name = defaultValue1; + const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDocument = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateDocument(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDocument with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.UpdateDocumentRequest(), + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.UpdateDocumentRequest', + ['document', 'name'], + ); + request.document.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.updateDocument(request), expectedError); + }); + }); + + describe('deleteDocument', () => { + it('invokes deleteDocument without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.DeleteDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.DeleteDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDocument = stubSimpleCall(expectedResponse); + const [response] = await client.deleteDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDocument without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.DeleteDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.DeleteDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDocument( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDocument with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.DeleteDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.DeleteDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDocument = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteDocument(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDocument with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.DeleteDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.DeleteDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.deleteDocument(request), expectedError); + }); + }); + + describe('beginTransaction', () => { + it('invokes beginTransaction without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BeginTransactionRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionResponse(), + ); + client.innerApiCalls.beginTransaction = stubSimpleCall(expectedResponse); + const [response] = await client.beginTransaction(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes beginTransaction without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BeginTransactionRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionResponse(), + ); + client.innerApiCalls.beginTransaction = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.beginTransaction( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1.IBeginTransactionResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes beginTransaction with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BeginTransactionRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.beginTransaction = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.beginTransaction(request), expectedError); + const actualRequest = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes beginTransaction with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BeginTransactionRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.beginTransaction(request), expectedError); + }); + }); + + describe('commit', () => { + it('invokes commit without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CommitRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.CommitRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.CommitResponse(), + ); + client.innerApiCalls.commit = stubSimpleCall(expectedResponse); + const [response] = await client.commit(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.commit as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.commit as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes commit without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CommitRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.CommitRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.CommitResponse(), + ); + client.innerApiCalls.commit = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.commit( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1.ICommitResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.commit as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.commit as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes commit with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CommitRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.CommitRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.commit = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.commit(request), expectedError); + const actualRequest = (client.innerApiCalls.commit as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.commit as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes commit with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CommitRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.CommitRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.commit(request), expectedError); + }); + }); + + describe('rollback', () => { + it('invokes rollback without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RollbackRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RollbackRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.rollback = stubSimpleCall(expectedResponse); + const [response] = await client.rollback(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes rollback without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RollbackRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RollbackRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.rollback = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.rollback( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes rollback with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RollbackRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RollbackRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.rollback = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.rollback(request), expectedError); + const actualRequest = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes rollback with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RollbackRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RollbackRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.rollback(request), expectedError); + }); + }); + + describe('batchWrite', () => { + it('invokes batchWrite without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BatchWriteRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteResponse(), + ); + client.innerApiCalls.batchWrite = stubSimpleCall(expectedResponse); + const [response] = await client.batchWrite(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchWrite without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BatchWriteRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteResponse(), + ); + client.innerApiCalls.batchWrite = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchWrite( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1.IBatchWriteResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchWrite with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BatchWriteRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchWrite = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchWrite(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchWrite with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BatchWriteRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.batchWrite(request), expectedError); + }); + }); + + describe('createDocument', () => { + it('invokes createDocument without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CreateDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.CreateDocumentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.CreateDocumentRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document(), + ); + client.innerApiCalls.createDocument = stubSimpleCall(expectedResponse); + const [response] = await client.createDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDocument without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CreateDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.CreateDocumentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.CreateDocumentRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document(), + ); + client.innerApiCalls.createDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDocument( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1.IDocument | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDocument with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CreateDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.CreateDocumentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.CreateDocumentRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDocument = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createDocument(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDocument with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CreateDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.CreateDocumentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.CreateDocumentRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.createDocument(request), expectedError); + }); + }); + + describe('batchGetDocuments', () => { + it('invokes batchGetDocuments without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BatchGetDocumentsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsResponse(), + ); + client.innerApiCalls.batchGetDocuments = + stubServerStreamingCall(expectedResponse); + const stream = client.batchGetDocuments(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchGetDocuments without error and gaxServerStreamingRetries enabled', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BatchGetDocumentsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsResponse(), + ); + client.innerApiCalls.batchGetDocuments = + stubServerStreamingCall(expectedResponse); + const stream = client.batchGetDocuments(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchGetDocuments with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BatchGetDocumentsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchGetDocuments = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.batchGetDocuments(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchGetDocuments with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BatchGetDocumentsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + const stream = client.batchGetDocuments(request, { + retryRequestOptions: {noResponseRetries: 0}, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new firestoreModule.FirestoreClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('runQuery', () => { + it('invokes runQuery without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RunQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.RunQueryResponse(), + ); + client.innerApiCalls.runQuery = stubServerStreamingCall(expectedResponse); + const stream = client.runQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.RunQueryResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runQuery without error and gaxServerStreamingRetries enabled', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RunQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.RunQueryResponse(), + ); + client.innerApiCalls.runQuery = stubServerStreamingCall(expectedResponse); + const stream = client.runQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.RunQueryResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runQuery with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RunQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.runQuery = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.runQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.RunQueryResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runQuery with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RunQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + const stream = client.runQuery(request, { + retryRequestOptions: {noResponseRetries: 0}, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.RunQueryResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new firestoreModule.FirestoreClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('executePipeline', () => { + it('invokes executePipeline without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineRequest(), + ); + // path template: projects/*/databases/{database_id=*}/** + request.database = 'projects/value/databases/value/value'; + const expectedHeaderRequestParams = 'database_id=value'; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineResponse(), + ); + client.innerApiCalls.executePipeline = + stubServerStreamingCall(expectedResponse); + const stream = client.executePipeline(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.ExecutePipelineResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.executePipeline as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.executePipeline as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes executePipeline without error and gaxServerStreamingRetries enabled', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineRequest(), + ); + // path template: projects/*/databases/{database_id=*}/** + request.database = 'projects/value/databases/value/value'; + const expectedHeaderRequestParams = 'database_id=value'; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineResponse(), + ); + client.innerApiCalls.executePipeline = + stubServerStreamingCall(expectedResponse); + const stream = client.executePipeline(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.ExecutePipelineResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.executePipeline as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.executePipeline as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes executePipeline with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineRequest(), + ); + // path template: projects/*/databases/{database_id=*}/** + request.database = 'projects/value/databases/value/value'; + const expectedHeaderRequestParams = 'database_id=value'; + const expectedError = new Error('expected'); + client.innerApiCalls.executePipeline = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.executePipeline(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.ExecutePipelineResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.executePipeline as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.executePipeline as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes executePipeline with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineRequest(), + ); + // path template: projects/*/databases/{database_id=*}/** + request.database = 'projects/value/databases/value/value'; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + const stream = client.executePipeline(request, { + retryRequestOptions: {noResponseRetries: 0}, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.ExecutePipelineResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new firestoreModule.FirestoreClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('runAggregationQuery', () => { + it('invokes runAggregationQuery without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RunAggregationQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryResponse(), + ); + client.innerApiCalls.runAggregationQuery = + stubServerStreamingCall(expectedResponse); + const stream = client.runAggregationQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.firestore.v1.RunAggregationQueryResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runAggregationQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runAggregationQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runAggregationQuery without error and gaxServerStreamingRetries enabled', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RunAggregationQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryResponse(), + ); + client.innerApiCalls.runAggregationQuery = + stubServerStreamingCall(expectedResponse); + const stream = client.runAggregationQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.firestore.v1.RunAggregationQueryResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runAggregationQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runAggregationQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runAggregationQuery with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RunAggregationQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.runAggregationQuery = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.runAggregationQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.firestore.v1.RunAggregationQueryResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.runAggregationQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runAggregationQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runAggregationQuery with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RunAggregationQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + const stream = client.runAggregationQuery(request, { + retryRequestOptions: {noResponseRetries: 0}, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.firestore.v1.RunAggregationQueryResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new firestoreModule.FirestoreClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('write', () => { + it('invokes write without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.WriteRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.WriteResponse(), + ); + client.innerApiCalls.write = stubBidiStreamingCall(expectedResponse); + const stream = client.write(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.WriteResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.write as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + + it('invokes write with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.WriteRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.write = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.write(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.WriteResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.write as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('listen', () => { + it('invokes listen without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListenRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.ListenResponse(), + ); + client.innerApiCalls.listen = stubBidiStreamingCall(expectedResponse); + const stream = client.listen(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.ListenResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.listen as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + + it('invokes listen with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListenRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listen = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.listen(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.ListenResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.listen as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('listDocuments', () => { + it('invokes listDocuments without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + ]; + client.innerApiCalls.listDocuments = stubSimpleCall(expectedResponse); + const [response] = await client.listDocuments(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDocuments without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + ]; + client.innerApiCalls.listDocuments = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDocuments( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1.IDocument[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDocuments with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDocuments = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listDocuments(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDocumentsStream without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + ]; + client.descriptors.page.listDocuments.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDocumentsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.v1.Document[] = []; + stream.on('data', (response: protos.google.firestore.v1.Document) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listDocuments.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDocuments, request), + ); + assert( + (client.descriptors.page.listDocuments.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listDocumentsStream with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDocuments.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listDocumentsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.v1.Document[] = []; + stream.on('data', (response: protos.google.firestore.v1.Document) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listDocuments.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDocuments, request), + ); + assert( + (client.descriptors.page.listDocuments.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listDocuments without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + ]; + client.descriptors.page.listDocuments.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.firestore.v1.IDocument[] = []; + const iterable = client.listDocumentsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listDocuments.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listDocuments.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listDocuments with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDocuments.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listDocumentsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.firestore.v1.IDocument[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listDocuments.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listDocuments.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('partitionQuery', () => { + it('invokes partitionQuery without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.PartitionQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + ]; + client.innerApiCalls.partitionQuery = stubSimpleCall(expectedResponse); + const [response] = await client.partitionQuery(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes partitionQuery without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.PartitionQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + ]; + client.innerApiCalls.partitionQuery = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.partitionQuery( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1.ICursor[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes partitionQuery with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.PartitionQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.partitionQuery = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.partitionQuery(request), expectedError); + const actualRequest = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes partitionQueryStream without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.PartitionQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + ]; + client.descriptors.page.partitionQuery.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.partitionQueryStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.v1.Cursor[] = []; + stream.on('data', (response: protos.google.firestore.v1.Cursor) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.partitionQuery.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.partitionQuery, request), + ); + assert( + (client.descriptors.page.partitionQuery.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes partitionQueryStream with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.PartitionQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.partitionQuery.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.partitionQueryStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.v1.Cursor[] = []; + stream.on('data', (response: protos.google.firestore.v1.Cursor) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.partitionQuery.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.partitionQuery, request), + ); + assert( + (client.descriptors.page.partitionQuery.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with partitionQuery without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.PartitionQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + ]; + client.descriptors.page.partitionQuery.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.firestore.v1.ICursor[] = []; + const iterable = client.partitionQueryAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.partitionQuery.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with partitionQuery with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.PartitionQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.partitionQuery.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.partitionQueryAsync(request); + await assert.rejects(async () => { + const responses: protos.google.firestore.v1.ICursor[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.partitionQuery.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listCollectionIds', () => { + it('invokes listCollectionIds without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListCollectionIdsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.innerApiCalls.listCollectionIds = stubSimpleCall(expectedResponse); + const [response] = await client.listCollectionIds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCollectionIds without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListCollectionIdsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.innerApiCalls.listCollectionIds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCollectionIds( + request, + (err?: Error | null, result?: string[] | null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCollectionIds with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListCollectionIdsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listCollectionIds = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listCollectionIds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCollectionIdsStream without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListCollectionIdsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.descriptors.page.listCollectionIds.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCollectionIdsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: string[] = []; + stream.on('data', (response: string) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listCollectionIds.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCollectionIds, request), + ); + assert( + (client.descriptors.page.listCollectionIds.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listCollectionIdsStream with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListCollectionIdsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCollectionIds.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listCollectionIdsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: string[] = []; + stream.on('data', (response: string) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listCollectionIds.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCollectionIds, request), + ); + assert( + (client.descriptors.page.listCollectionIds.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listCollectionIds without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListCollectionIdsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.descriptors.page.listCollectionIds.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: string[] = []; + const iterable = client.listCollectionIdsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listCollectionIds.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listCollectionIds with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListCollectionIdsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCollectionIds.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCollectionIdsAsync(request); + await assert.rejects(async () => { + const responses: string[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listCollectionIds.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + describe('getLocation', () => { + it('invokes getLocation without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest(), + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new LocationProtos.google.cloud.location.Location(), + ); + client.locationsClient.getLocation = stubSimpleCall(expectedResponse); + const response = await client.getLocation(request, expectedOptions); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.locationsClient.getLocation as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + it('invokes getLocation without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest(), + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new LocationProtos.google.cloud.location.Location(), + ); + client.locationsClient.getLocation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getLocation( + request, + expectedOptions, + ( + err?: Error | null, + result?: LocationProtos.google.cloud.location.ILocation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.locationsClient.getLocation as SinonStub).getCall(0)); + }); + it('invokes getLocation with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest(), + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.locationsClient.getLocation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getLocation(request, expectedOptions), + expectedError, + ); + assert( + (client.locationsClient.getLocation as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + }); + describe('listLocationsAsync', () => { + it('uses async iteration with listLocations without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.ListLocationsRequest(), + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedResponse = [ + generateSampleMessage( + new LocationProtos.google.cloud.location.Location(), + ), + generateSampleMessage( + new LocationProtos.google.cloud.location.Location(), + ), + generateSampleMessage( + new LocationProtos.google.cloud.location.Location(), + ), + ]; + client.locationsClient.descriptors.page.listLocations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: LocationProtos.google.cloud.location.ILocation[] = []; + const iterable = client.listLocationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.locationsClient.descriptors.page.listLocations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.locationsClient.descriptors.page.listLocations + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + it('uses async iteration with listLocations with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.ListLocationsRequest(), + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedError = new Error('expected'); + client.locationsClient.descriptors.page.listLocations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listLocationsAsync(request); + await assert.rejects(async () => { + const responses: LocationProtos.google.cloud.location.ILocation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.locationsClient.descriptors.page.listLocations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.locationsClient.descriptors.page.listLocations + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); +}); diff --git a/handwritten/firestore/dev/test/gapic_firestore_v1beta1.ts b/handwritten/firestore/dev/test/gapic_firestore_v1beta1.ts new file mode 100644 index 00000000000..8ca18f6ba6f --- /dev/null +++ b/handwritten/firestore/dev/test/gapic_firestore_v1beta1.ts @@ -0,0 +1,2857 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/firestore_v1beta1_proto_api'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it} from 'mocha'; +import * as firestoreModule from '../src/v1beta1'; + +import {PassThrough} from 'stream'; + +import {protobuf} from 'google-gax'; + +// Dynamically loaded proto JSON is needed to get the type information +// to fill in default values for request objects +const root = protobuf.Root.fromJSON( + require('../protos/v1beta1.json'), +).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + +function generateSampleMessage(instance: T) { + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); +} + +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); +} + +function stubBidiStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); +} + +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); + } + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); +} + +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); +} + +describe('v1beta1.FirestoreClient', () => { + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new firestoreModule.FirestoreClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = new firestoreModule.FirestoreClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); + + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = firestoreModule.FirestoreClient.servicePath; + assert.strictEqual(servicePath, 'firestore.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = firestoreModule.FirestoreClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new firestoreModule.FirestoreClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new firestoreModule.FirestoreClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new firestoreModule.FirestoreClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new firestoreModule.FirestoreClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new firestoreModule.FirestoreClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', + }); + }); + }); + + it('has port', () => { + const port = firestoreModule.FirestoreClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new firestoreModule.FirestoreClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new firestoreModule.FirestoreClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.firestoreStub, undefined); + await client.initialize(); + assert(client.firestoreStub); + }); + + it('has close method for the initialized client', done => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize().catch(err => { + throw err; + }); + assert(client.firestoreStub); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; + }); + }); + + it('has close method for the non-initialized client', done => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.firestoreStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; + }); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getDocument', () => { + it('invokes getDocument without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.GetDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.GetDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.Document(), + ); + client.innerApiCalls.getDocument = stubSimpleCall(expectedResponse); + const [response] = await client.getDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDocument without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.GetDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.GetDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.Document(), + ); + client.innerApiCalls.getDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDocument( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1beta1.IDocument | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDocument with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.GetDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.GetDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDocument = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getDocument(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDocument with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.GetDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.GetDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getDocument(request), expectedError); + }); + }); + + describe('updateDocument', () => { + it('invokes updateDocument without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.UpdateDocumentRequest(), + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.UpdateDocumentRequest', + ['document', 'name'], + ); + request.document.name = defaultValue1; + const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.Document(), + ); + client.innerApiCalls.updateDocument = stubSimpleCall(expectedResponse); + const [response] = await client.updateDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDocument without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.UpdateDocumentRequest(), + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.UpdateDocumentRequest', + ['document', 'name'], + ); + request.document.name = defaultValue1; + const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.Document(), + ); + client.innerApiCalls.updateDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDocument( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1beta1.IDocument | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDocument with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.UpdateDocumentRequest(), + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.UpdateDocumentRequest', + ['document', 'name'], + ); + request.document.name = defaultValue1; + const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDocument = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateDocument(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDocument with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.UpdateDocumentRequest(), + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.UpdateDocumentRequest', + ['document', 'name'], + ); + request.document.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.updateDocument(request), expectedError); + }); + }); + + describe('deleteDocument', () => { + it('invokes deleteDocument without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.DeleteDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.DeleteDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDocument = stubSimpleCall(expectedResponse); + const [response] = await client.deleteDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDocument without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.DeleteDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.DeleteDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDocument( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDocument with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.DeleteDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.DeleteDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDocument = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteDocument(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDocument with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.DeleteDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.DeleteDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.deleteDocument(request), expectedError); + }); + }); + + describe('beginTransaction', () => { + it('invokes beginTransaction without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.BeginTransactionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.BeginTransactionRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.BeginTransactionResponse(), + ); + client.innerApiCalls.beginTransaction = stubSimpleCall(expectedResponse); + const [response] = await client.beginTransaction(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes beginTransaction without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.BeginTransactionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.BeginTransactionRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.BeginTransactionResponse(), + ); + client.innerApiCalls.beginTransaction = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.beginTransaction( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1beta1.IBeginTransactionResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes beginTransaction with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.BeginTransactionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.BeginTransactionRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.beginTransaction = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.beginTransaction(request), expectedError); + const actualRequest = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes beginTransaction with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.BeginTransactionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.BeginTransactionRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.beginTransaction(request), expectedError); + }); + }); + + describe('commit', () => { + it('invokes commit without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.CommitRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.CommitRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.CommitResponse(), + ); + client.innerApiCalls.commit = stubSimpleCall(expectedResponse); + const [response] = await client.commit(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.commit as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.commit as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes commit without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.CommitRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.CommitRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.CommitResponse(), + ); + client.innerApiCalls.commit = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.commit( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1beta1.ICommitResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.commit as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.commit as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes commit with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.CommitRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.CommitRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.commit = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.commit(request), expectedError); + const actualRequest = (client.innerApiCalls.commit as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.commit as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes commit with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.CommitRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.CommitRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.commit(request), expectedError); + }); + }); + + describe('rollback', () => { + it('invokes rollback without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.RollbackRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.RollbackRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.rollback = stubSimpleCall(expectedResponse); + const [response] = await client.rollback(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes rollback without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.RollbackRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.RollbackRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.rollback = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.rollback( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes rollback with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.RollbackRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.RollbackRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.rollback = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.rollback(request), expectedError); + const actualRequest = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes rollback with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.RollbackRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.RollbackRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.rollback(request), expectedError); + }); + }); + + describe('batchWrite', () => { + it('invokes batchWrite without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.BatchWriteRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.BatchWriteRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.BatchWriteResponse(), + ); + client.innerApiCalls.batchWrite = stubSimpleCall(expectedResponse); + const [response] = await client.batchWrite(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchWrite without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.BatchWriteRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.BatchWriteRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.BatchWriteResponse(), + ); + client.innerApiCalls.batchWrite = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchWrite( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1beta1.IBatchWriteResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchWrite with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.BatchWriteRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.BatchWriteRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchWrite = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchWrite(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchWrite with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.BatchWriteRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.BatchWriteRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.batchWrite(request), expectedError); + }); + }); + + describe('createDocument', () => { + it('invokes createDocument without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.CreateDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.CreateDocumentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1beta1.CreateDocumentRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.Document(), + ); + client.innerApiCalls.createDocument = stubSimpleCall(expectedResponse); + const [response] = await client.createDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDocument without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.CreateDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.CreateDocumentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1beta1.CreateDocumentRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.Document(), + ); + client.innerApiCalls.createDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDocument( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1beta1.IDocument | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDocument with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.CreateDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.CreateDocumentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1beta1.CreateDocumentRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDocument = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createDocument(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDocument with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.CreateDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.CreateDocumentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1beta1.CreateDocumentRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.createDocument(request), expectedError); + }); + }); + + describe('batchGetDocuments', () => { + it('invokes batchGetDocuments without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.BatchGetDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.BatchGetDocumentsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.BatchGetDocumentsResponse(), + ); + client.innerApiCalls.batchGetDocuments = + stubServerStreamingCall(expectedResponse); + const stream = client.batchGetDocuments(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.firestore.v1beta1.BatchGetDocumentsResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchGetDocuments without error and gaxServerStreamingRetries enabled', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.BatchGetDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.BatchGetDocumentsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.BatchGetDocumentsResponse(), + ); + client.innerApiCalls.batchGetDocuments = + stubServerStreamingCall(expectedResponse); + const stream = client.batchGetDocuments(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.firestore.v1beta1.BatchGetDocumentsResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchGetDocuments with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.BatchGetDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.BatchGetDocumentsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchGetDocuments = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.batchGetDocuments(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.firestore.v1beta1.BatchGetDocumentsResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchGetDocuments with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.BatchGetDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.BatchGetDocumentsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + const stream = client.batchGetDocuments(request, { + retryRequestOptions: {noResponseRetries: 0}, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.firestore.v1beta1.BatchGetDocumentsResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new firestoreModule.FirestoreClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('runQuery', () => { + it('invokes runQuery without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.RunQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.RunQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.RunQueryResponse(), + ); + client.innerApiCalls.runQuery = stubServerStreamingCall(expectedResponse); + const stream = client.runQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1beta1.RunQueryResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runQuery without error and gaxServerStreamingRetries enabled', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.RunQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.RunQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.RunQueryResponse(), + ); + client.innerApiCalls.runQuery = stubServerStreamingCall(expectedResponse); + const stream = client.runQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1beta1.RunQueryResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runQuery with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.RunQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.RunQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.runQuery = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.runQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1beta1.RunQueryResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runQuery with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.RunQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.RunQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + const stream = client.runQuery(request, { + retryRequestOptions: {noResponseRetries: 0}, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1beta1.RunQueryResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new firestoreModule.FirestoreClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('write', () => { + it('invokes write without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.WriteRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.WriteResponse(), + ); + client.innerApiCalls.write = stubBidiStreamingCall(expectedResponse); + const stream = client.write(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1beta1.WriteResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.write as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + + it('invokes write with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.WriteRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.write = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.write(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1beta1.WriteResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.write as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('listen', () => { + it('invokes listen without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.ListenRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1beta1.ListenResponse(), + ); + client.innerApiCalls.listen = stubBidiStreamingCall(expectedResponse); + const stream = client.listen(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1beta1.ListenResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.listen as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + + it('invokes listen with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.ListenRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listen = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.listen(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1beta1.ListenResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.listen as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('listDocuments', () => { + it('invokes listDocuments without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListDocumentsRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1beta1.Document()), + generateSampleMessage(new protos.google.firestore.v1beta1.Document()), + generateSampleMessage(new protos.google.firestore.v1beta1.Document()), + ]; + client.innerApiCalls.listDocuments = stubSimpleCall(expectedResponse); + const [response] = await client.listDocuments(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDocuments without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListDocumentsRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1beta1.Document()), + generateSampleMessage(new protos.google.firestore.v1beta1.Document()), + generateSampleMessage(new protos.google.firestore.v1beta1.Document()), + ]; + client.innerApiCalls.listDocuments = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDocuments( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1beta1.IDocument[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDocuments with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListDocumentsRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDocuments = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listDocuments(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDocumentsStream without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListDocumentsRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1beta1.Document()), + generateSampleMessage(new protos.google.firestore.v1beta1.Document()), + generateSampleMessage(new protos.google.firestore.v1beta1.Document()), + ]; + client.descriptors.page.listDocuments.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDocumentsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.v1beta1.Document[] = []; + stream.on( + 'data', + (response: protos.google.firestore.v1beta1.Document) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listDocuments.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDocuments, request), + ); + assert( + (client.descriptors.page.listDocuments.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listDocumentsStream with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListDocumentsRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDocuments.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listDocumentsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.v1beta1.Document[] = []; + stream.on( + 'data', + (response: protos.google.firestore.v1beta1.Document) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listDocuments.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDocuments, request), + ); + assert( + (client.descriptors.page.listDocuments.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listDocuments without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListDocumentsRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1beta1.Document()), + generateSampleMessage(new protos.google.firestore.v1beta1.Document()), + generateSampleMessage(new protos.google.firestore.v1beta1.Document()), + ]; + client.descriptors.page.listDocuments.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.firestore.v1beta1.IDocument[] = []; + const iterable = client.listDocumentsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listDocuments.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listDocuments.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listDocuments with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListDocumentsRequest', + ['collectionId'], + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDocuments.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listDocumentsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.firestore.v1beta1.IDocument[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listDocuments.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listDocuments.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('partitionQuery', () => { + it('invokes partitionQuery without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.PartitionQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1beta1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1beta1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1beta1.Cursor()), + ]; + client.innerApiCalls.partitionQuery = stubSimpleCall(expectedResponse); + const [response] = await client.partitionQuery(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes partitionQuery without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.PartitionQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1beta1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1beta1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1beta1.Cursor()), + ]; + client.innerApiCalls.partitionQuery = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.partitionQuery( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1beta1.ICursor[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes partitionQuery with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.PartitionQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.partitionQuery = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.partitionQuery(request), expectedError); + const actualRequest = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes partitionQueryStream without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.PartitionQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1beta1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1beta1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1beta1.Cursor()), + ]; + client.descriptors.page.partitionQuery.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.partitionQueryStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.v1beta1.Cursor[] = []; + stream.on( + 'data', + (response: protos.google.firestore.v1beta1.Cursor) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.partitionQuery.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.partitionQuery, request), + ); + assert( + (client.descriptors.page.partitionQuery.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes partitionQueryStream with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.PartitionQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.partitionQuery.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.partitionQueryStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.v1beta1.Cursor[] = []; + stream.on( + 'data', + (response: protos.google.firestore.v1beta1.Cursor) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.partitionQuery.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.partitionQuery, request), + ); + assert( + (client.descriptors.page.partitionQuery.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with partitionQuery without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.PartitionQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1beta1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1beta1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1beta1.Cursor()), + ]; + client.descriptors.page.partitionQuery.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.firestore.v1beta1.ICursor[] = []; + const iterable = client.partitionQueryAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.partitionQuery.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with partitionQuery with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.PartitionQueryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.partitionQuery.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.partitionQueryAsync(request); + await assert.rejects(async () => { + const responses: protos.google.firestore.v1beta1.ICursor[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.partitionQuery.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listCollectionIds', () => { + it('invokes listCollectionIds without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.ListCollectionIdsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListCollectionIdsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.innerApiCalls.listCollectionIds = stubSimpleCall(expectedResponse); + const [response] = await client.listCollectionIds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCollectionIds without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.ListCollectionIdsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListCollectionIdsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.innerApiCalls.listCollectionIds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCollectionIds( + request, + (err?: Error | null, result?: string[] | null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCollectionIds with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.ListCollectionIdsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListCollectionIdsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listCollectionIds = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listCollectionIds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCollectionIdsStream without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.ListCollectionIdsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListCollectionIdsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.descriptors.page.listCollectionIds.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCollectionIdsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: string[] = []; + stream.on('data', (response: string) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listCollectionIds.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCollectionIds, request), + ); + assert( + (client.descriptors.page.listCollectionIds.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listCollectionIdsStream with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.ListCollectionIdsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListCollectionIdsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCollectionIds.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listCollectionIdsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: string[] = []; + stream.on('data', (response: string) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listCollectionIds.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCollectionIds, request), + ); + assert( + (client.descriptors.page.listCollectionIds.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listCollectionIds without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.ListCollectionIdsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListCollectionIdsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.descriptors.page.listCollectionIds.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: string[] = []; + const iterable = client.listCollectionIdsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listCollectionIds.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listCollectionIds with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1beta1.ListCollectionIdsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1beta1.ListCollectionIdsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCollectionIds.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCollectionIdsAsync(request); + await assert.rejects(async () => { + const responses: string[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listCollectionIds.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); +}); diff --git a/handwritten/firestore/dev/test/ignore-undefined.ts b/handwritten/firestore/dev/test/ignore-undefined.ts new file mode 100644 index 00000000000..4847829a01a --- /dev/null +++ b/handwritten/firestore/dev/test/ignore-undefined.ts @@ -0,0 +1,331 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {describe, it} from 'mocha'; +import {expect} from 'chai'; +import {fieldFiltersQuery, orderBy, queryEquals, startAt} from './query'; +import { + ApiOverride, + create, + createInstance, + document, + emptyQueryStream, + InvalidApiUsage, + requestEquals, + response, + set, + update, + updateMask, + writeResult, +} from './util/helpers'; + +const FOO_MAP = { + mapValue: { + fields: { + bar: { + stringValue: 'bar', + }, + }, + }, +}; + +describe('ignores undefined values', () => { + it('in set()', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', 'foo', 'foo'), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides, { + ignoreUndefinedProperties: true, + }); + await firestore.doc('collectionId/documentId').set({ + foo: 'foo', + bar: undefined, + }); + }); + + it('in set({ merge: true })', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + set({ + document: document('documentId', 'foo', 'foo'), + mask: updateMask('foo'), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides, { + ignoreUndefinedProperties: true, + }); + await firestore.doc('collectionId/documentId').set( + { + foo: 'foo', + bar: undefined, + }, + {merge: true}, + ); + }); + + it('in create()', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + create({ + document: document('documentId', 'foo', 'foo'), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides, { + ignoreUndefinedProperties: true, + }); + await firestore.doc('collectionId/documentId').create({ + foo: 'foo', + bar: undefined, + }); + }); + + it('in update()', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + update({ + document: document('documentId', 'foo', FOO_MAP), + mask: updateMask('foo'), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides, { + ignoreUndefinedProperties: true, + }); + await firestore.doc('collectionId/documentId').update('foo', { + bar: 'bar', + baz: undefined, + }); + await firestore + .doc('collectionId/documentId') + .update({foo: {bar: 'bar', baz: undefined}}); + }); + + it('with top-level field in update()', async () => { + const overrides: ApiOverride = { + commit: request => { + requestEquals( + request, + update({ + document: document('documentId', 'foo', 'bar'), + mask: updateMask('foo'), + }), + ); + return response(writeResult(1)); + }, + }; + + const firestore = await createInstance(overrides, { + ignoreUndefinedProperties: true, + }); + await firestore.doc('collectionId/documentId').update({ + foo: 'bar', + ignored: undefined, + }); + }); + + it('in query filters', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, fieldFiltersQuery('foo', 'EQUAL', FOO_MAP)); + return emptyQueryStream(); + }, + }; + + const firestore = await createInstance(overrides, { + ignoreUndefinedProperties: true, + }); + await firestore + .collection('collectionId') + .where('foo', '==', {bar: 'bar', baz: undefined}) + .get(); + }); + + it('in query cursors', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('foo', 'ASCENDING'), + startAt(true, FOO_MAP), + ); + return emptyQueryStream(); + }, + }; + + const firestore = await createInstance(overrides, { + ignoreUndefinedProperties: true, + }); + await firestore + .collection('collectionId') + .orderBy('foo') + .startAt({bar: 'bar', baz: undefined}) + .get(); + }); +}); + +describe('rejects undefined values', () => { + describe('in top-level call', () => { + it('to set()', async () => { + const firestore = await createInstance( + {}, + {ignoreUndefinedProperties: true}, + ); + expect(() => { + void firestore + .doc('collectionId/documentId') + .set(undefined as InvalidApiUsage); + }).to.throw( + 'Value for argument "data" is not a valid Firestore document. Input is not a plain JavaScript object.', + ); + }); + + it('to create()', async () => { + const firestore = await createInstance( + {}, + {ignoreUndefinedProperties: true}, + ); + expect(() => { + void firestore + .doc('collectionId/documentId') + .create(undefined as InvalidApiUsage); + }).to.throw( + 'Value for argument "data" is not a valid Firestore document. Input is not a plain JavaScript object.', + ); + }); + + it('to update()', async () => { + const firestore = await createInstance( + {}, + {ignoreUndefinedProperties: true}, + ); + expect(() => { + void firestore.doc('collectionId/documentId').update('foo', undefined); + }).to.throw('"undefined" values are only ignored inside of objects.'); + }); + + it('to Query.where()', async () => { + const firestore = await createInstance( + {}, + {ignoreUndefinedProperties: true}, + ); + expect(() => { + firestore + .doc('collectionId/documentId') + .collection('collectionId') + .where('foo', '==', undefined); + }).to.throw('"undefined" values are only ignored inside of objects.'); + }); + + it('to Query.startAt()', async () => { + const firestore = await createInstance( + {}, + {ignoreUndefinedProperties: true}, + ); + expect(() => { + firestore + .doc('collectionId/documentId') + .collection('collectionId') + .orderBy('foo') + .startAt(undefined); + }).to.throw('"undefined" values are only ignored inside of objects.'); + }); + }); + + describe('when setting is disabled', () => { + it('in set()', async () => { + const firestore = await createInstance({}); + expect(() => { + void firestore.doc('collectionId/documentId').set({ + foo: 'foo', + bar: undefined, + }); + }).to.throw( + 'Cannot use "undefined" as a Firestore value (found in field "bar"). If you want to ignore undefined values, enable `ignoreUndefinedProperties`.', + ); + }); + + it('in create()', async () => { + const firestore = await createInstance({}); + expect(() => { + void firestore.doc('collectionId/documentId').create({ + foo: 'foo', + bar: undefined, + }); + }).to.throw( + 'Cannot use "undefined" as a Firestore value (found in field "bar"). If you want to ignore undefined values, enable `ignoreUndefinedProperties`.', + ); + }); + + it('in update()', async () => { + const firestore = await createInstance({}); + expect(() => { + void firestore.doc('collectionId/documentId').update('foo', { + foo: 'foo', + bar: undefined, + }); + }).to.throw( + 'Cannot use "undefined" as a Firestore value (found in field "foo.bar"). If you want to ignore undefined values, enable `ignoreUndefinedProperties`.', + ); + }); + + it('in query filters', async () => { + const firestore = await createInstance({}); + expect(() => { + firestore + .collection('collectionId') + .where('foo', '==', {bar: 'bar', baz: undefined}); + }).to.throw( + 'Cannot use "undefined" as a Firestore value (found in field "baz"). If you want to ignore undefined values, enable `ignoreUndefinedProperties`.', + ); + }); + + it('in query cursors', async () => { + const firestore = await createInstance({}); + expect(() => { + firestore + .collection('collectionId') + .orderBy('foo') + .startAt({bar: 'bar', baz: undefined}); + }).to.throw( + 'Cannot use "undefined" as a Firestore value (found in field "baz"). If you want to ignore undefined values, enable `ignoreUndefinedProperties`.', + ); + }); + }); +}); diff --git a/handwritten/firestore/dev/test/index.ts b/handwritten/firestore/dev/test/index.ts new file mode 100644 index 00000000000..73359e14f78 --- /dev/null +++ b/handwritten/firestore/dev/test/index.ts @@ -0,0 +1,1469 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {describe, it, beforeEach, before, afterEach, after} from 'mocha'; +import {expect, use} from 'chai'; +import * as chaiAsPromised from 'chai-as-promised'; +import * as extend from 'extend'; +import {GoogleError, GrpcClient, Status} from 'google-gax'; + +import {google} from '../protos/firestore_v1_proto_api'; + +import * as Firestore from '../src'; +import {DocumentSnapshot, FieldPath, FieldValue} from '../src'; +import {setTimeoutHandler} from '../src/backoff'; +import {QualifiedResourcePath} from '../src/path'; +import { + ApiOverride, + createInstance, + document, + DOCUMENT_NAME, + found, + InvalidApiUsage, + missing, + response, + stream, + verifyInstance, +} from './util/helpers'; + +import api = google.firestore.v1; + +use(chaiAsPromised); + +const {grpc} = new GrpcClient({}); + +const PROJECT_ID = 'test-project'; +const DATABASE_ROOT = `projects/${PROJECT_ID}/databases/(default)`; +const DEFAULT_SETTINGS = { + projectId: PROJECT_ID, + sslCreds: grpc.credentials.createInsecure(), +}; + +// Change the argument to 'console.log' to enable debug output. +Firestore.setLogFunction(null); + +const bytesData = Buffer.from('AQI=', 'base64'); + +const allSupportedTypesProtobufJs = document( + 'documentId', + 'arrayValue', + { + arrayValue: { + values: [ + { + stringValue: 'foo', + }, + { + integerValue: 42, + }, + { + stringValue: 'bar', + }, + ], + }, + }, + 'emptyArray', + { + arrayValue: {}, + }, + 'dateValue', + { + timestampValue: { + nanos: 123000000, + seconds: 479978400, + }, + }, + 'timestampValue', + { + timestampValue: { + nanos: 123000000, + seconds: '479978400', + }, + }, + 'doubleValue', + { + doubleValue: 0.1, + }, + 'falseValue', + { + booleanValue: false, + }, + 'infinityValue', + { + doubleValue: Infinity, + }, + 'integerValue', + { + integerValue: 0, + }, + 'negativeInfinityValue', + { + doubleValue: -Infinity, + }, + 'nilValue', + { + nullValue: 'NULL_VALUE', + }, + 'objectValue', + { + mapValue: { + fields: { + foo: { + stringValue: 'bar', + }, + }, + }, + }, + 'vectorValue', + { + mapValue: { + fields: { + __type__: { + stringValue: '__vector__', + }, + value: { + arrayValue: { + values: [ + { + doubleValue: 0.1, + }, + { + doubleValue: 0.2, + }, + { + doubleValue: 0.3, + }, + ], + }, + }, + }, + }, + }, + 'emptyObject', + { + mapValue: {}, + }, + 'pathValue', + { + referenceValue: `${DATABASE_ROOT}/documents/collection/document`, + }, + 'stringValue', + { + stringValue: 'a', + }, + 'trueValue', + { + booleanValue: true, + }, + 'geoPointValue', + { + geoPointValue: { + latitude: 50.1430847, + longitude: -122.947778, + }, + }, + 'bytesValue', + { + bytesValue: Buffer.from('AQI=', 'base64'), + }, +); + +const allSupportedTypesJson = { + name: `${DOCUMENT_NAME}`, + fields: { + arrayValue: { + arrayValue: { + values: [ + { + stringValue: 'foo', + }, + { + integerValue: 42, + }, + { + stringValue: 'bar', + }, + ], + }, + }, + emptyArray: { + arrayValue: {}, + }, + dateValue: { + timestampValue: '1985-03-18T07:20:00.123000000Z', + }, + timestampValue: { + timestampValue: '1985-03-18T07:20:00.123000000Z', + }, + doubleValue: { + doubleValue: 0.1, + }, + falseValue: { + booleanValue: false, + }, + infinityValue: { + doubleValue: Infinity, + }, + integerValue: { + integerValue: 0, + }, + negativeInfinityValue: { + doubleValue: -Infinity, + }, + nilValue: { + nullValue: 'NULL_VALUE', + }, + objectValue: { + mapValue: { + fields: { + foo: { + stringValue: 'bar', + }, + }, + }, + }, + emptyObject: { + mapValue: {}, + }, + vectorValue: { + mapValue: { + fields: { + __type__: { + stringValue: '__vector__', + }, + value: { + arrayValue: { + values: [ + { + doubleValue: 0.1, + }, + { + doubleValue: 0.2, + }, + { + doubleValue: 0.3, + }, + ], + }, + }, + }, + }, + }, + pathValue: { + referenceValue: `${DATABASE_ROOT}/documents/collection/document`, + }, + stringValue: { + stringValue: 'a', + }, + trueValue: { + booleanValue: true, + }, + geoPointValue: { + geoPointValue: { + latitude: 50.1430847, + longitude: -122.947778, + }, + }, + bytesValue: { + bytesValue: 'AQI=', + }, + }, + createTime: {seconds: 1, nanos: 2}, + updateTime: {seconds: 3, nanos: 4}, +}; + +const allSupportedTypesInput = { + stringValue: 'a', + trueValue: true, + falseValue: false, + integerValue: 0, + doubleValue: 0.1, + infinityValue: Infinity, + negativeInfinityValue: -Infinity, + objectValue: {foo: 'bar'}, + emptyObject: {}, + vectorValue: FieldValue.vector([0.1, 0.2, 0.3]), + dateValue: new Date('Mar 18, 1985 08:20:00.123 GMT+0100 (CET)'), + timestampValue: Firestore.Timestamp.fromDate( + new Date('Mar 18, 1985 08:20:00.123 GMT+0100 (CET)'), + ), + pathValue: new Firestore.DocumentReference( + { + formattedName: DATABASE_ROOT, + _getProjectId: () => ({projectId: PROJECT_ID, databaseId: '(default)'}), + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any + new QualifiedResourcePath( + PROJECT_ID, + '(default)', + 'collection', + 'document', + ), + ), + arrayValue: ['foo', 42, 'bar'], + emptyArray: [], + nilValue: null, + geoPointValue: new Firestore.GeoPoint(50.1430847, -122.947778), + bytesValue: Buffer.from([0x1, 0x2]), +}; + +const allSupportedTypesOutput: {[field: string]: unknown} = { + stringValue: 'a', + trueValue: true, + falseValue: false, + integerValue: 0, + doubleValue: 0.1, + infinityValue: Infinity, + negativeInfinityValue: -Infinity, + objectValue: {foo: 'bar'}, + emptyObject: {}, + vectorValue: FieldValue.vector([0.1, 0.2, 0.3]), + dateValue: Firestore.Timestamp.fromDate( + new Date('Mar 18, 1985 08:20:00.123 GMT+0100 (CET)'), + ), + timestampValue: Firestore.Timestamp.fromDate( + new Date('Mar 18, 1985 08:20:00.123 GMT+0100 (CET)'), + ), + pathValue: new Firestore.DocumentReference( + { + formattedName: DATABASE_ROOT, + _getProjectId: () => ({projectId: PROJECT_ID, databaseId: '(default)'}), + } as any, // eslint-disable-line @typescript-eslint/no-explicit-any + new QualifiedResourcePath( + PROJECT_ID, + '(default)', + 'collection', + 'document', + ), + ), + arrayValue: ['foo', 42, 'bar'], + emptyArray: [], + nilValue: null, + geoPointValue: new Firestore.GeoPoint(50.1430847, -122.947778), + bytesValue: Buffer.from([0x1, 0x2]), +}; + +describe('instantiation', () => { + it('creates instance', () => { + const firestore = new Firestore.Firestore(DEFAULT_SETTINGS); + expect(firestore).to.be.an.instanceOf(Firestore.Firestore); + }); + + it('merges settings', () => { + const firestore = new Firestore.Firestore(DEFAULT_SETTINGS); + firestore.settings({foo: 'bar'}); + + /* eslint-disable @typescript-eslint/no-explicit-any */ + expect((firestore as any)._settings.projectId).to.equal(PROJECT_ID); + expect((firestore as any)._settings.databaseId).to.be.undefined; + expect((firestore as any)._settings.foo).to.equal('bar'); + /* eslint-enable @typescript-eslint/no-explicit-any */ + }); + + it('can only call settings() once', () => { + const firestore = new Firestore.Firestore(DEFAULT_SETTINGS); + firestore.settings({}); + + expect(() => firestore.settings({})).to.throw( + 'Firestore has already been initialized. You can only call settings() once, and only before calling any other methods on a Firestore object.', + ); + }); + + it('cannot change settings after client initialized', async () => { + const firestore = new Firestore.Firestore(DEFAULT_SETTINGS); + await firestore.initializeIfNeeded('tag'); + + expect(() => firestore.settings({})).to.throw( + 'Firestore has already been initialized. You can only call settings() once, and only before calling any other methods on a Firestore object.', + ); + }); + + it('validates project ID is string', () => { + expect(() => { + const settings = {...DEFAULT_SETTINGS, projectId: 1337}; + new Firestore.Firestore(settings as InvalidApiUsage); + }).to.throw( + 'Value for argument "settings.projectId" is not a valid string.', + ); + + expect(() => { + new Firestore.Firestore(DEFAULT_SETTINGS).settings({ + projectId: 1337, + } as InvalidApiUsage); + }).to.throw( + 'Value for argument "settings.projectId" is not a valid string.', + ); + }); + + it('validates database ID is string', () => { + expect(() => { + const settings = {...DEFAULT_SETTINGS, databaseId: 1337}; + new Firestore.Firestore(settings as InvalidApiUsage); + }).to.throw( + 'Value for argument "settings.databaseId" is not a valid string.', + ); + + expect(() => { + new Firestore.Firestore(DEFAULT_SETTINGS).settings({ + databaseId: 1337, + } as InvalidApiUsage); + }).to.throw( + 'Value for argument "settings.databaseId" is not a valid string.', + ); + }); + + it('validates ssl is a boolean', () => { + const invalidValues = ['true', 1337]; + + for (const value of invalidValues) { + expect(() => { + const settings = {...DEFAULT_SETTINGS, ssl: value}; + new Firestore.Firestore(settings as InvalidApiUsage); + }).to.throw('Value for argument "settings.ssl" is not a valid boolean.'); + } + + new Firestore.Firestore({ssl: true}); + }); + + it('validates host is a valid host', () => { + const invalidValues = [ + 'foo://bar', + 'foobar/foobaz', + 'foobar/?foo', + 'foo@foobar', + 'foo:80:81', + ]; + for (const value of invalidValues) { + expect(() => { + new Firestore.Firestore({host: value}); + }).to.throw('Value for argument "settings.host" is not a valid host.'); + } + + const validValues = [ + '127.0.0.1', + '127.0.0.1:8080', + '[::1]', + '[::1]:8080', + 'foo', + 'foo:8080', + ]; + for (const value of validValues) { + new Firestore.Firestore({host: value}); + } + }); + + it('validates FIRESTORE_EMULATOR_HOST is a valid host', () => { + const oldValue = process.env.FIRESTORE_EMULATOR_HOST; + + try { + const invalidValues = [ + 'foo://bar', + 'foobar/foobaz', + 'foobar/?foo', + 'foo@foobar', + 'foo:80:81', + ]; + for (const value of invalidValues) { + expect(() => { + process.env.FIRESTORE_EMULATOR_HOST = value; + new Firestore.Firestore(); + }).to.throw( + 'Value for argument "FIRESTORE_EMULATOR_HOST" is not a valid host.', + ); + } + + const validValues = [ + '127.0.0.1', + '127.0.0.1:8080', + '[::1]', + '[::1]:8080', + 'foo', + 'foo:8080', + ]; + for (const value of validValues) { + process.env.FIRESTORE_EMULATOR_HOST = value; + new Firestore.Firestore(); + } + } finally { + if (oldValue) { + process.env.FIRESTORE_EMULATOR_HOST = oldValue; + } else { + delete process.env.FIRESTORE_EMULATOR_HOST; + } + } + }); + + it('"settings.host" takes precedence without FIRESTORE_EMULATOR_HOST', () => { + const oldValue = process.env.FIRESTORE_EMULATOR_HOST; + + try { + delete process.env.FIRESTORE_EMULATOR_HOST; + + let firestore = new Firestore.Firestore({ + apiEndpoint: 'api-host', + }); + firestore.settings({host: 'new-host:100'}); + expect(firestore._settings.servicePath).to.equal('new-host'); + + firestore = new Firestore.Firestore({ + servicePath: 'service-host', + }); + firestore.settings({host: 'new-host:100'}); + expect(firestore._settings.servicePath).to.equal('new-host'); + + firestore = new Firestore.Firestore({ + apiEndpoint: 'api-host', + servicePath: 'service-host', + }); + firestore.settings({host: 'new-host:100'}); + expect(firestore._settings.servicePath).to.equal('new-host'); + } finally { + if (oldValue) { + process.env.FIRESTORE_EMULATOR_HOST = oldValue; + } else { + delete process.env.FIRESTORE_EMULATOR_HOST; + } + } + }); + + it('FIRESTORE_EMULATOR_HOST ignores host', () => { + const oldValue = process.env.FIRESTORE_EMULATOR_HOST; + + try { + process.env.FIRESTORE_EMULATOR_HOST = 'env-host:8080'; + const firestore = new Firestore.Firestore({ + host: 'localhost:8080', + }); + expect(firestore._settings.servicePath).to.equal('env-host'); + firestore.settings({host: 'localhost:8080'}); + expect(firestore._settings.servicePath).to.equal('env-host'); + } finally { + if (oldValue) { + process.env.FIRESTORE_EMULATOR_HOST = oldValue; + } else { + delete process.env.FIRESTORE_EMULATOR_HOST; + } + } + }); + + it('FIRESTORE_EMULATOR_HOST ignores servicePath', () => { + const oldValue = process.env.FIRESTORE_EMULATOR_HOST; + + try { + process.env.FIRESTORE_EMULATOR_HOST = 'foo'; + const firestore = new Firestore.Firestore({servicePath: 'bar'}); + expect(firestore._settings.servicePath).to.equal('foo'); + firestore.settings({servicePath: 'bar'}); + expect(firestore._settings.servicePath).to.equal('foo'); + } finally { + if (oldValue) { + process.env.FIRESTORE_EMULATOR_HOST = oldValue; + } else { + delete process.env.FIRESTORE_EMULATOR_HOST; + } + } + }); + + it('FIRESTORE_EMULATOR_HOST overrides other endpoint', done => { + const oldValue = process.env.FIRESTORE_EMULATOR_HOST; + + try { + process.env.FIRESTORE_EMULATOR_HOST = 'new'; + const firestore = new Firestore.Firestore({servicePath: 'old'}); + firestore['validateAndApplySettings'] = settings => { + expect(settings.servicePath).to.equal('new'); + done(); + }; + firestore.settings({}); + } finally { + if (oldValue) { + process.env.FIRESTORE_EMULATOR_HOST = oldValue; + } else { + delete process.env.FIRESTORE_EMULATOR_HOST; + } + } + }); + + it('FIRESTORE_EMULATOR_HOST keeps user-provided headers', done => { + const oldValue = process.env.FIRESTORE_EMULATOR_HOST; + + try { + process.env.FIRESTORE_EMULATOR_HOST = 'new'; + const firestore = new Firestore.Firestore({customHeaders: {foo: 'bar'}}); + firestore['validateAndApplySettings'] = settings => { + expect(settings.customHeaders.foo).to.equal('bar'); + done(); + }; + firestore.settings({}); + } finally { + if (oldValue) { + process.env.FIRESTORE_EMULATOR_HOST = oldValue; + } else { + delete process.env.FIRESTORE_EMULATOR_HOST; + } + } + }); + + it('validates maxIdleChannels', () => { + const invalidValues = [-1, 'foo', 1.3]; + + for (const value of invalidValues) { + expect(() => { + const settings = {...DEFAULT_SETTINGS, maxIdleChannels: value}; + new Firestore.Firestore(settings as InvalidApiUsage); + }).to.throw(); + } + + new Firestore.Firestore({maxIdleChannels: 1}); + }); + + it('uses project id and database id from constructor', () => { + const firestore = new Firestore.Firestore({ + projectId: 'foo', + databaseId: 'bar', + }); + + return expect(firestore.formattedName).to.equal( + 'projects/foo/databases/bar', + ); + }); + + it('uses project id from gapic client', async () => { + return createInstance( + { + getProjectId: () => Promise.resolve('foo'), + }, + {projectId: undefined}, + ).then(async firestore => { + await firestore.initializeIfNeeded('tag'); + expect(firestore.projectId).to.equal('foo'); + expect(firestore.formattedName).to.equal( + 'projects/foo/databases/(default)', + ); + }); + }); + + it('uses project ID from settings() and default database ID', () => { + const firestore = new Firestore.Firestore({ + sslCreds: grpc.credentials.createInsecure(), + }); + + firestore.settings({projectId: PROJECT_ID}); + + expect(firestore.formattedName).to.equal( + `projects/${PROJECT_ID}/databases/(default)`, + ); + }); + + it('uses database ID and database ID from settings()', () => { + const firestore = new Firestore.Firestore({ + sslCreds: grpc.credentials.createInsecure(), + }); + + firestore.settings({projectId: PROJECT_ID, databaseId: 'bar'}); + + expect(firestore.formattedName).to.equal( + `projects/${PROJECT_ID}/databases/bar`, + ); + }); + + it('handles error from project ID detection', () => { + return createInstance( + { + getProjectId: () => Promise.reject(new Error('Injected Error')), + }, + {projectId: undefined}, + ).then(firestore => { + return expect( + firestore.collection('foo').add({}), + ).to.eventually.be.rejectedWith('Injected Error'); + }); + }); + + it('can instantiate client with ssl:false', async () => { + const firestore = new Firestore.Firestore({ + ssl: false, + projectId: 'foo', + }); + await firestore['_clientPool'].run('tag', /* requiresGrpc= */ false, () => + Promise.resolve(), + ); + }); + + describe('preferRest configuration', () => { + let originalValue: string | undefined; + + beforeEach(() => { + originalValue = process.env.FIRESTORE_PREFER_REST; + }); + + afterEach(() => { + if (originalValue === undefined) { + delete process.env.FIRESTORE_PREFER_REST; + } else { + process.env.FIRESTORE_PREFER_REST = originalValue; + } + }); + + it('preferRest is disabled (falsy) by default', async () => { + delete process.env.FIRESTORE_PREFER_REST; + const firestore = new Firestore.Firestore({}); + // Convention with settings is to leave undefined settings as + // undefined. We could test for undefined here, but converting + // to boolean and testing for falsy-ness is consistent with the + // code that consumes settings. + expect(!!firestore['_settings'].preferRest).to.be.false; + }); + + it('preferRest can be enabled by setting', async () => { + delete process.env.FIRESTORE_PREFER_REST; + const firestore = new Firestore.Firestore({ + preferRest: true, + }); + expect(firestore['_settings'].preferRest).to.be.true; + }); + + it('preferRest can be enabled by environment variable', async () => { + process.env.FIRESTORE_PREFER_REST = 'true'; + const firestore = new Firestore.Firestore({}); + expect(firestore['_settings'].preferRest).to.be.true; + }); + + it('the preferRest value from settings takes precedent over the environment var - disable', async () => { + process.env.FIRESTORE_PREFER_REST = 'true'; + const firestore = new Firestore.Firestore({ + preferRest: false, + }); + expect(firestore['_settings'].preferRest).to.be.false; + }); + + it('the preferRest value from settings takes precedent over the environment var - enable', async () => { + process.env.FIRESTORE_PREFER_REST = 'false'; + const firestore = new Firestore.Firestore({ + preferRest: true, + }); + expect(firestore['_settings'].preferRest).to.be.true; + }); + }); + + it('exports all types', () => { + // Ordering as per firestore.d.ts + expect(Firestore.Firestore).to.exist; + expect(Firestore.Firestore.name).to.equal('Firestore'); + expect(Firestore.Timestamp).to.exist; + expect(Firestore.Timestamp.name).to.equal('Timestamp'); + expect(Firestore.GeoPoint).to.exist; + expect(Firestore.GeoPoint.name).to.equal('GeoPoint'); + expect(Firestore.Transaction).to.exist; + expect(Firestore.Transaction.name).to.equal('Transaction'); + expect(Firestore.WriteBatch).to.exist; + expect(Firestore.WriteBatch.name).to.equal('WriteBatch'); + expect(Firestore.DocumentReference).to.exist; + expect(Firestore.DocumentReference.name).to.equal('DocumentReference'); + expect(Firestore.WriteResult).to.exist; + expect(Firestore.WriteResult.name).to.equal('WriteResult'); + expect(Firestore.DocumentSnapshot).to.exist; + expect(Firestore.DocumentSnapshot.name).to.equal('DocumentSnapshot'); + expect(Firestore.QueryDocumentSnapshot).to.exist; + expect(Firestore.QueryDocumentSnapshot.name).to.equal( + 'QueryDocumentSnapshot', + ); + expect(Firestore.Query).to.exist; + expect(Firestore.Query.name).to.equal('Query'); + expect(Firestore.QuerySnapshot).to.exist; + expect(Firestore.QuerySnapshot.name).to.equal('QuerySnapshot'); + expect(Firestore.CollectionReference).to.exist; + expect(Firestore.CollectionReference.name).to.equal('CollectionReference'); + expect(Firestore.FieldValue).to.exist; + expect(Firestore.FieldValue.name).to.equal('FieldValue'); + expect(Firestore.FieldPath).to.exist; + expect(Firestore.Firestore.name).to.equal('Firestore'); + expect( + Firestore.FieldValue.serverTimestamp().isEqual( + Firestore.FieldValue.delete(), + ), + ).to.be.false; + }); +}); + +describe('serializer', () => { + it('supports all types', () => { + const overrides: ApiOverride = { + commit: request => { + expect(allSupportedTypesProtobufJs.fields).to.deep.eq( + request.writes![0].update!.fields, + ); + return response({ + commitTime: {}, + writeResults: [ + { + updateTime: {}, + }, + ], + }); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.collection('coll').add(allSupportedTypesInput); + }); + }); +}); + +describe('snapshot_() method', () => { + let firestore: Firestore.Firestore; + + function verifyAllSupportedTypes(actualObject: DocumentSnapshot) { + const expected = extend(true, {}, allSupportedTypesOutput); + // Deep Equal doesn't support matching instances of DocumentRefs, so we + // compare them manually and remove them from the resulting object. + expect(actualObject.get('pathValue').formattedName).to.equal( + (expected.pathValue as Firestore.DocumentReference).formattedName, + ); + const data = actualObject.data()!; + delete data.pathValue; + delete expected.pathValue; + expect(data).to.deep.eq(expected); + + // We specifically test the GeoPoint properties to ensure 100% test + // coverage. + expect(data.geoPointValue.latitude).to.equal(50.1430847); + expect(data.geoPointValue.longitude).to.equal(-122.947778); + expect( + data.geoPointValue.isEqual( + new Firestore.GeoPoint(50.1430847, -122.947778), + ), + ).to.be.true; + } + + beforeEach(() => { + // Unlike most other tests, we don't call `ensureClient` since the + // `snapshot_` method does not require a GAPIC client. + firestore = new Firestore.Firestore({ + projectId: PROJECT_ID, + sslCreds: grpc.credentials.createInsecure(), + }); + }); + + afterEach(() => verifyInstance(firestore)); + + it('handles ProtobufJS', () => { + const doc = firestore.snapshot_( + document('doc', 'foo', {bytesValue: bytesData}), + {seconds: 5, nanos: 6}, + ); + + expect(doc.exists).to.be.true; + expect({foo: bytesData}).to.deep.eq(doc.data()); + expect(doc.createTime!.isEqual(new Firestore.Timestamp(1, 2))).to.be.true; + expect(doc.updateTime!.isEqual(new Firestore.Timestamp(3, 4))).to.be.true; + expect(doc.readTime.isEqual(new Firestore.Timestamp(5, 6))).to.be.true; + }); + + it('handles Proto3 JSON together with existing types', () => { + // Google Cloud Functions must be able to call snapshot_() with Proto3 JSON + // data. + const doc = firestore.snapshot_( + { + name: `${DATABASE_ROOT}/documents/collectionId/doc`, + fields: { + a: {bytesValue: 'AQI='}, + b: {timestampValue: '1985-03-18T07:20:00.000Z'}, + c: { + valueType: 'bytesValue', + bytesValue: Buffer.from('AQI=', 'base64'), + }, + }, + createTime: '1970-01-01T00:00:01.002Z', + updateTime: '1970-01-01T00:00:03.000004Z', + }, + '1970-01-01T00:00:05.000000006Z', + 'json', + ); + + expect(doc.exists).to.be.true; + expect(doc.data()).to.deep.eq({ + a: bytesData, + b: Firestore.Timestamp.fromDate(new Date('1985-03-18T07:20:00.000Z')), + c: bytesData, + }); + expect(doc.createTime!.isEqual(new Firestore.Timestamp(1, 2000000))).to.be + .true; + expect(doc.updateTime!.isEqual(new Firestore.Timestamp(3, 4000))).to.be + .true; + expect(doc.readTime.isEqual(new Firestore.Timestamp(5, 6))).to.be.true; + }); + + it('deserializes all supported types from Protobuf JS', () => { + const doc = firestore.snapshot_(allSupportedTypesProtobufJs, { + seconds: 5, + nanos: 6, + }); + + verifyAllSupportedTypes(doc); + }); + + it('deserializes all supported types from Proto3 JSON', () => { + const doc = firestore.snapshot_( + allSupportedTypesJson, + '1970-01-01T00:00:05.000000006Z', + 'json', + ); + verifyAllSupportedTypes(doc); + }); + + it('handles invalid Proto3 JSON', () => { + expect(() => { + firestore.snapshot_( + { + name: `${DATABASE_ROOT}/documents/collectionId/doc`, + fields: {foo: {}}, + createTime: '1970-01-01T00:00:01.000000002Z', + updateTime: '1970-01-01T00:00:03.000000004Z', + }, + '1970-01-01T00:00:05.000000006Z', + 'json', + ); + }).to.throw("Unable to infer type value from '{}'."); + + expect(() => { + firestore.snapshot_( + { + name: `${DATABASE_ROOT}/documents/collectionId/doc`, + fields: {foo: {stringValue: 'bar', integerValue: 42}}, + createTime: '1970-01-01T00:00:01.000000002Z', + updateTime: '1970-01-01T00:00:03.000000004Z', + }, + '1970-01-01T00:00:05.000000006Z', + 'json', + ); + }).to.throw( + 'Unable to infer type value from \'{"stringValue":"bar","integerValue":42}\'.', + ); + + expect(() => { + firestore.snapshot_( + { + name: `${DATABASE_ROOT}/documents/collectionId/doc`, + fields: {foo: {stringValue: 'bar'}}, + createTime: '1970-01-01T00:00:01.NaNZ', + updateTime: '1970-01-01T00:00:03.000000004Z', + }, + '1970-01-01T00:00:05.000000006Z', + 'json', + ); + }).to.throw( + 'Specify a valid ISO 8601 timestamp for "documentOrName.createTime".', + ); + }); + + it('handles missing document ', () => { + const doc = firestore.snapshot_( + `${DATABASE_ROOT}/documents/collectionId/doc`, + '1970-01-01T00:00:05.000000006Z', + 'json', + ); + + expect(doc.exists).to.be.false; + expect(doc.readTime.isEqual(new Firestore.Timestamp(5, 6))).to.be.true; + }); + + it('handles invalid encoding format ', () => { + expect(() => { + firestore.snapshot_( + `${DATABASE_ROOT}/documents/collectionId/doc`, + '1970-01-01T00:00:05.000000006Z', + 'ascii' as InvalidApiUsage, + ); + }).to.throw( + 'Unsupported encoding format. Expected "json" or "protobufJS", but was "ascii".', + ); + }); +}); + +describe('doc() method', () => { + let firestore: Firestore.Firestore; + + beforeEach(() => { + return createInstance().then(firestoreInstance => { + firestore = firestoreInstance; + }); + }); + + afterEach(() => verifyInstance(firestore)); + + it('returns DocumentReference', () => { + const documentRef = firestore.doc('collectionId/documentId'); + expect(documentRef).to.be.an.instanceOf(Firestore.DocumentReference); + }); + + it('requires document path', () => { + expect(() => (firestore as InvalidApiUsage).doc()).to.throw( + 'Value for argument "documentPath" is not a valid resource path. Path must be a non-empty string.', + ); + }); + + it("doesn't accept empty components", () => { + expect(() => firestore.doc('coll//doc')).to.throw( + 'Value for argument "documentPath" is not a valid resource path. Paths must not contain //.', + ); + }); + + it('must point to document', () => { + expect(() => firestore.doc('collectionId')).to.throw( + 'Value for argument "documentPath" must point to a document, but was "collectionId". Your path does not contain an even number of components.', + ); + }); + + it('exposes properties', () => { + const documentRef = firestore.doc('collectionId/documentId'); + expect(documentRef.id).to.equal('documentId'); + expect(documentRef.firestore).to.equal(firestore); + }); +}); + +describe('collection() method', () => { + let firestore: Firestore.Firestore; + + beforeEach(() => { + return createInstance().then(firestoreInstance => { + firestore = firestoreInstance; + }); + }); + + afterEach(() => verifyInstance(firestore)); + + it('returns collection', () => { + const collection = firestore.collection('col1/doc1/col2'); + expect(collection).to.be.an.instanceOf(Firestore.CollectionReference); + }); + + it('requires collection id', () => { + expect(() => (firestore as InvalidApiUsage).collection()).to.throw( + 'Value for argument "collectionPath" is not a valid resource path. Path must be a non-empty string.', + ); + }); + + it('must point to a collection', () => { + expect(() => firestore.collection('collectionId/documentId')).to.throw( + 'Value for argument "collectionPath" must point to a collection, but was "collectionId/documentId". Your path does not contain an odd number of components.', + ); + }); + + it('exposes properties', () => { + const collection = firestore.collection('collectionId'); + expect(collection.id).to.exist; + expect(collection.doc).to.exist; + expect(collection.id).to.equal('collectionId'); + }); +}); + +describe('listCollections() method', () => { + it('returns collections', () => { + const overrides: ApiOverride = { + listCollectionIds: request => { + expect(request).to.deep.eq({ + parent: `projects/${PROJECT_ID}/databases/(default)/documents`, + }); + + return response(['first', 'second']); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.listCollections().then(collections => { + expect(collections[0].path).to.equal('first'); + expect(collections[1].path).to.equal('second'); + }); + }); + }); +}); + +describe('getAll() method', () => { + before(() => { + setTimeoutHandler(setImmediate); + }); + + after(() => setTimeoutHandler(setTimeout)); + + function resultEquals( + result: DocumentSnapshot[], + ...docs: api.IBatchGetDocumentsResponse[] + ) { + expect(result.length).to.equal(docs.length); + + for (let i = 0; i < result.length; ++i) { + const doc = docs[i]; + + if (doc.found) { + expect(result[i].exists).to.be.true; + expect(result[i].ref.formattedName).to.equal(doc.found.name); + } else { + expect(result[i].exists).to.be.false; + expect(result[i].ref.formattedName).to.equal(doc.missing); + } + } + } + + it('accepts single document', () => { + const overrides: ApiOverride = { + batchGetDocuments: () => { + return stream(found('documentId')); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore + .getAll(firestore.doc('collectionId/documentId')) + .then(result => { + resultEquals(result, found('documentId')); + }); + }); + }); + + it('verifies response', () => { + const overrides: ApiOverride = { + batchGetDocuments: () => { + return stream(found('documentId2')); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore + .getAll(firestore.doc('collectionId/documentId')) + .then(() => { + throw new Error('Unexpected success in Promise'); + }) + .catch(err => { + expect(err.message).to.equal( + 'Did not receive document for "collectionId/documentId".', + ); + }); + }); + }); + + it('handles stream exception during initialization', () => { + let attempts = 0; + + const overrides: ApiOverride = { + batchGetDocuments: () => { + ++attempts; + return stream(new Error('Expected exception')); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore + .getAll(firestore.doc('collectionId/documentId')) + .then(() => { + throw new Error('Unexpected success in Promise'); + }) + .catch(err => { + expect(attempts).to.equal(5); + expect(err.message).to.equal('Expected exception'); + }); + }); + }); + + it('handles stream exception (before first result)', () => { + let attempts = 0; + + const overrides: ApiOverride = { + batchGetDocuments: () => { + if (attempts < 3) { + ++attempts; + throw new Error('Expected error'); + } else { + return stream(found(document('documentId'))); + } + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore + .doc('collectionId/documentId') + .get() + .then(() => { + expect(attempts).to.equal(3); + }); + }); + }); + + it('handles stream exception (with retryable error)', () => { + let attempts = 0; + + const error = new GoogleError('Expected exception'); + error.code = Status.DEADLINE_EXCEEDED; + + const overrides: ApiOverride = { + batchGetDocuments: () => { + ++attempts; + return stream(found(document(`doc${attempts}`)), error); + }, + }; + + return createInstance(overrides).then(async firestore => { + const docs = await firestore.getAll( + firestore.doc('collectionId/doc1'), + firestore.doc('collectionId/doc2'), + firestore.doc('collectionId/doc3'), + ); + + expect(attempts).to.equal(3); + expect(docs.length).to.equal(3); + expect(docs[0].ref.path).to.equal('collectionId/doc1'); + expect(docs[1].ref.path).to.equal('collectionId/doc2'); + expect(docs[2].ref.path).to.equal('collectionId/doc3'); + }); + }); + + it('handles stream exception (with non-retryable error)', () => { + let attempts = 0; + + const error = new GoogleError('Expected exception'); + error.code = Status.PERMISSION_DENIED; + + const overrides: ApiOverride = { + batchGetDocuments: () => { + ++attempts; + return stream(found(document(`doc${attempts}`)), error); + }, + }; + + return createInstance(overrides).then(async firestore => { + try { + await firestore.getAll( + firestore.doc('collectionId/doc1'), + firestore.doc('collectionId/doc2'), + firestore.doc('collectionId/doc3'), + ); + expect.fail(); + } catch (err) { + expect(attempts).to.equal(1); + expect(err.code).to.equal(Status.PERMISSION_DENIED); + } + }); + }); + + it('retries based on error code', () => { + const expectedErrorAttempts: {[key: number]: number} = { + [Status.CANCELLED]: 1, + [Status.UNKNOWN]: 1, + [Status.INVALID_ARGUMENT]: 1, + [Status.DEADLINE_EXCEEDED]: 5, + [Status.NOT_FOUND]: 1, + [Status.ALREADY_EXISTS]: 1, + [Status.PERMISSION_DENIED]: 1, + [Status.RESOURCE_EXHAUSTED]: 5, + [Status.FAILED_PRECONDITION]: 1, + [Status.ABORTED]: 1, + [Status.OUT_OF_RANGE]: 1, + [Status.UNIMPLEMENTED]: 1, + [Status.INTERNAL]: 5, + [Status.UNAVAILABLE]: 5, + [Status.DATA_LOSS]: 1, + [Status.UNAUTHENTICATED]: 1, + }; + + const actualErrorAttempts: {[key: number]: number} = {}; + + const overrides: ApiOverride = { + batchGetDocuments: request => { + const errorCode = Number(request!.documents![0].split('/').pop()); + actualErrorAttempts[errorCode] = + (actualErrorAttempts[errorCode] || 0) + 1; + const error = new GoogleError('Expected exception'); + error.code = errorCode; + return stream(error); + }, + }; + + return createInstance(overrides).then(async firestore => { + const coll = firestore.collection('collectionId'); + + for (const errorCode of Object.keys(expectedErrorAttempts)) { + await firestore + .getAll(coll.doc(`${errorCode}`)) + .then(() => { + throw new Error('Unexpected success in Promise'); + }) + .catch(err => { + expect(err.code).to.equal(Number(errorCode)); + }); + } + + expect(actualErrorAttempts).to.deep.eq(expectedErrorAttempts); + }); + }).timeout(5000); + + it('requires at least one argument', () => { + return createInstance().then(firestore => { + expect(() => (firestore as InvalidApiUsage).getAll()).to.throw( + 'Function "Firestore.getAll()" requires at least 1 argument.', + ); + }); + }); + + it('validates document references', () => { + return createInstance().then(firestore => { + expect(() => firestore.getAll(null as InvalidApiUsage)).to.throw( + 'Element at index 0 is not a valid DocumentReference.', + ); + }); + }); + + it('returns not found for missing documents', () => { + const overrides: ApiOverride = { + batchGetDocuments: () => stream(found('exists'), missing('missing')), + }; + + return createInstance(overrides).then(firestore => { + return firestore + .getAll( + firestore.doc('collectionId/exists'), + firestore.doc('collectionId/missing'), + ) + .then(result => { + resultEquals(result, found('exists'), missing('missing')); + }); + }); + }); + + it('returns results in order', () => { + const overrides: ApiOverride = { + batchGetDocuments: () => { + return stream( + // Note that these are out of order. + found('second'), + found('first'), + found('fourth'), + found('third'), + ); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore + .getAll( + firestore.doc('collectionId/first'), + firestore.doc('collectionId/second'), + firestore.doc('collectionId/third'), + firestore.doc('collectionId/fourth'), + ) + .then(result => { + resultEquals( + result, + found('first'), + found('second'), + found('third'), + found(document('fourth')), + ); + }); + }); + }); + + it('accepts same document multiple times', () => { + const overrides: ApiOverride = { + batchGetDocuments: request => { + expect(request!.documents!.length).to.equal(2); + return stream(found('a'), found('b')); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore + .getAll( + firestore.doc('collectionId/a'), + firestore.doc('collectionId/a'), + firestore.doc('collectionId/b'), + firestore.doc('collectionId/a'), + ) + .then(result => { + resultEquals(result, found('a'), found('a'), found('b'), found('a')); + }); + }); + }); + + it('applies field mask', () => { + const overrides: ApiOverride = { + batchGetDocuments: request => { + expect(request!.mask!.fieldPaths).to.have.members([ + 'foo.bar', + '`foo.bar`', + ]); + return stream(found('a')); + }, + }; + + return createInstance(overrides).then(firestore => { + return firestore.getAll(firestore.doc('collectionId/a'), { + fieldMask: ['foo.bar', new FieldPath('foo.bar')], + }); + }); + }); + + it('validates field mask', () => { + return createInstance().then(firestore => { + expect(() => + firestore.getAll(firestore.doc('collectionId/a'), { + fieldMask: null, + } as InvalidApiUsage), + ).to.throw( + 'Value for argument "options" is not a valid read option. "fieldMask" is not an array.', + ); + + expect(() => + firestore.getAll(firestore.doc('collectionId/a'), { + fieldMask: ['a', new FieldPath('b'), null], + } as InvalidApiUsage), + ).to.throw( + 'Value for argument "options" is not a valid read option. "fieldMask" is not valid: Element at index 2 is not a valid field path. Paths can only be specified as strings or via a FieldPath object.', + ); + }); + }); +}); + +describe('toJSON', () => { + it('Serializing Firestore settings redacts credentials', () => { + const firestore = new Firestore.Firestore({ + projectId: 'myProjectId', + credentials: {client_email: 'foo@bar', private_key: 'asdf1234'}, + }); + + const serializedSettings = JSON.stringify(firestore._settings); + + // Instead of validating the serialized string for redacted credentials, + // parse the settings and check the credential values. + const parsedSettings = JSON.parse(serializedSettings); + expect(parsedSettings.credentials.client_email).to.equal('***'); + expect(parsedSettings.credentials.private_key).to.equal('***'); + }); + + it('Serializing Firestore instance', () => { + const firestore = new Firestore.Firestore({ + projectId: 'myProjectId', + credentials: {client_email: 'foo@bar', private_key: 'asdf1234'}, + }); + + const serializedFirestore = JSON.stringify(firestore); + + // Instead of validating the serialized string, + // parse the JSON back to an object and check the properties. + const expectedParsedFirestore = { + projectId: 'myProjectId', + }; + + const parsedFirestore = JSON.parse(serializedFirestore); + expect(parsedFirestore).to.deep.equal(expectedParsedFirestore); + }); +}); diff --git a/handwritten/firestore/dev/test/lazy-load.ts b/handwritten/firestore/dev/test/lazy-load.ts new file mode 100644 index 00000000000..aba93acb02c --- /dev/null +++ b/handwritten/firestore/dev/test/lazy-load.ts @@ -0,0 +1,40 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {describe, it} from 'mocha'; +import {expect} from 'chai'; + +function isModuleLoaded(moduleName: string) { + return !!Object.keys(require.cache).find( + path => path.indexOf(`node_modules/${moduleName}`) !== -1, + ); +} + +describe('Index.js', () => { + (isModuleLoaded('google-gax') ? it.skip : it)( + 'does not load google-gax', + () => { + require('../src/index'); + expect(isModuleLoaded('google-gax')).to.be.false; + }, + ); + + (isModuleLoaded('protobufjs') ? it.skip : it)( + 'does not load protobufjs', + () => { + require('../src/index'); + expect(isModuleLoaded('protobufjs')).to.be.false; + }, + ); +}); diff --git a/handwritten/firestore/dev/test/mocha.opts b/handwritten/firestore/dev/test/mocha.opts new file mode 100644 index 00000000000..086387a236c --- /dev/null +++ b/handwritten/firestore/dev/test/mocha.opts @@ -0,0 +1,3 @@ +--enable-source-maps +--timeout 2000 +--throw-deprecation diff --git a/handwritten/firestore/dev/test/options-util.ts b/handwritten/firestore/dev/test/options-util.ts new file mode 100644 index 00000000000..ebcd5fb9035 --- /dev/null +++ b/handwritten/firestore/dev/test/options-util.ts @@ -0,0 +1,227 @@ +/** + * @license + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {expect} from 'chai'; +import {Serializer} from '../src/serializer'; +import {createInstance} from './util/helpers'; +import {Firestore} from '../src'; +import {OptionsUtil} from '../src/pipelines/options-util'; + +describe('OptionsUtil', () => { + let db: Firestore | undefined; + beforeEach(async () => { + db = await createInstance(); + }); + + afterEach(async () => { + if (db) { + await db.terminate(); + db = undefined; + } + }); + + it('should support known options', () => { + const optionsUtil = new OptionsUtil({ + fooBar: { + serverName: 'foo_bar', + }, + }); + const proto = optionsUtil.getOptionsProto(new Serializer(db!), { + fooBar: 'recommended', + }); + + expect(proto).deep.equal({ + foo_bar: { + stringValue: 'recommended', + }, + }); + }); + + it('should support unknown options', () => { + const optionsUtil = new OptionsUtil({}); + const proto = optionsUtil.getOptionsProto( + new Serializer(db!), + {}, + {baz: 'foo'}, + ); + + expect(proto).to.deep.equal({ + baz: { + stringValue: 'foo', + }, + }); + }); + + it('should support unknown nested options', () => { + const optionsUtil = new OptionsUtil({}); + const proto = optionsUtil.getOptionsProto( + new Serializer(db!), + {}, + {'foo.bar': 'baz'}, + ); + + expect(proto).to.deep.equal({ + foo: { + mapValue: { + fields: { + bar: {stringValue: 'baz'}, + }, + }, + }, + }); + }); + + it('should support options override', () => { + const optionsUtil = new OptionsUtil({ + indexMode: { + serverName: 'index_mode', + }, + }); + const proto = optionsUtil.getOptionsProto( + new Serializer(db!), + { + indexMode: 'recommended', + }, + { + index_mode: 'baz', + }, + ); + + expect(proto).to.deep.equal({ + index_mode: { + stringValue: 'baz', + }, + }); + }); + + it('should support options override of nested field', () => { + const optionsUtil = new OptionsUtil({ + foo: { + serverName: 'foo', + nestedOptions: { + bar: { + serverName: 'bar', + }, + waldo: { + serverName: 'waldo', + }, + }, + }, + }); + const proto = optionsUtil.getOptionsProto( + new Serializer(db!), + { + foo: {bar: 'yep', waldo: 'found'}, + }, + { + 'foo.bar': 123, + 'foo.baz': true, + }, + ); + + expect(proto).to.deep.equal({ + foo: { + mapValue: { + fields: { + bar: { + integerValue: '123', + }, + waldo: { + stringValue: 'found', + }, + baz: { + booleanValue: true, + }, + }, + }, + }, + }); + }); + + it('will replace a nested object if given a new object', () => { + const optionsUtil = new OptionsUtil({ + foo: { + serverName: 'foo', + nestedOptions: { + bar: { + serverName: 'bar', + }, + waldo: { + serverName: 'waldo', + }, + }, + }, + }); + const proto = optionsUtil.getOptionsProto( + new Serializer(db!), + { + foo: {bar: 'yep', waldo: 'found'}, + }, + { + foo: { + bar: 123, + }, + }, + ); + + expect(proto).to.deep.equal({ + foo: { + mapValue: { + fields: { + bar: { + integerValue: '123', + }, + }, + }, + }, + }); + }); + + it('will replace a top level property that is not an object if given a nested field with dot notation', () => { + const optionsUtil = new OptionsUtil({ + foo: { + serverName: 'foo', + }, + }); + + const proto = optionsUtil.getOptionsProto( + new Serializer(db!), + { + foo: 'bar', + }, + { + 'foo.bar': '123', + 'foo.waldo': true, + }, + ); + + expect(proto).to.deep.equal({ + foo: { + mapValue: { + fields: { + bar: { + stringValue: '123', + }, + waldo: { + booleanValue: true, + }, + }, + }, + }, + }); + }); +}); diff --git a/handwritten/firestore/dev/test/order.ts b/handwritten/firestore/dev/test/order.ts new file mode 100644 index 00000000000..17abcf79fb6 --- /dev/null +++ b/handwritten/firestore/dev/test/order.ts @@ -0,0 +1,500 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {describe, it, beforeEach, afterEach} from 'mocha'; +import {expect} from 'chai'; + +import {google} from '../protos/firestore_v1_proto_api'; + +import { + Firestore, + QueryDocumentSnapshot, + setLogFunction, + Timestamp, +} from '../src'; +import {GeoPoint} from '../src'; +import {DocumentReference} from '../src'; +import * as order from '../src/order'; +import {QualifiedResourcePath} from '../src/path'; +import {createInstance, InvalidApiUsage, verifyInstance} from './util/helpers'; + +import api = google.firestore.v1; + +// Change the argument to 'console.log' to enable debug output. +setLogFunction(null); + +describe('Order', () => { + let firestore: Firestore; + + beforeEach(async () => { + firestore = await createInstance(); + }); + + afterEach(() => verifyInstance(firestore)); + + /** Converts a value into its proto representation. */ + function wrap(value: unknown): api.IValue { + const val = firestore._serializer!.encodeValue(value); + expect(val).to.not.be.null; + return val!; + } + + function blob(data: number[]): api.IValue { + return wrap(Buffer.from(data)); + } + + function resource(pathString: string): api.IValue { + return wrap( + new DocumentReference( + firestore, + QualifiedResourcePath.fromSlashSeparatedString(pathString), + ), + ); + } + + function geopoint(lat: number, lng: number): api.IValue { + return wrap(new GeoPoint(lat, lng)); + } + + function int(n: number): api.IValue { + return { + integerValue: n, + }; + } + + function double(n: number): api.IValue { + return { + doubleValue: n, + }; + } + + it('throws on invalid value', () => { + expect(() => { + order.compare( + {valueType: 'foo'} as InvalidApiUsage, + {valueType: 'foo'} as InvalidApiUsage, + ); + }).to.throw('Unexpected value type: foo'); + }); + + it('throws on invalid blob', () => { + expect(() => { + order.compare( + { + bytesValue: new Uint8Array([1, 2, 3]), + }, + { + bytesValue: new Uint8Array([1, 2, 3]), + }, + ); + }).to.throw('Blobs can only be compared if they are Buffers'); + }); + + it('compares document snapshots by name', () => { + const docs = [ + new QueryDocumentSnapshot( + firestore.doc('col/doc3'), + {}, + Timestamp.now(), + Timestamp.now(), + Timestamp.now(), + ), + new QueryDocumentSnapshot( + firestore.doc('col/doc2'), + {}, + Timestamp.now(), + Timestamp.now(), + Timestamp.now(), + ), + new QueryDocumentSnapshot( + firestore.doc('col/doc2'), + {}, + Timestamp.now(), + Timestamp.now(), + Timestamp.now(), + ), + new QueryDocumentSnapshot( + firestore.doc('col/doc1'), + {}, + Timestamp.now(), + Timestamp.now(), + Timestamp.now(), + ), + ]; + + docs.sort(firestore.collection('col').comparator()); + + expect(docs.map(doc => doc.id)).to.deep.eq([ + 'doc1', + 'doc2', + 'doc2', + 'doc3', + ]); + }); + + it('is correct', () => { + const groups = [ + // null first + [wrap(null)], + + // booleans + [wrap(false)], + [wrap(true)], + + // numbers + [double(NaN), double(NaN)], + [double(-Infinity)], + [double(-Number.MAX_VALUE)], + [int(Number.MIN_SAFE_INTEGER - 1)], + [int(Number.MIN_SAFE_INTEGER)], + [double(-1.1)], + // Integers and Doubles order the same. + [int(-1), double(-1.0)], + [double(-Number.MIN_VALUE)], + // zeros all compare the same. + [int(0), double(0.0), double(-0)], + [double(Number.MIN_VALUE)], + [int(1), double(1.0)], + [double(1.1)], + [int(2)], + [int(10)], + [int(Number.MAX_SAFE_INTEGER)], + [int(Number.MAX_SAFE_INTEGER + 1)], + [double(Infinity)], + + // timestamps + [wrap(new Date(2016, 5, 20, 10, 20))], + [wrap(new Date(2016, 10, 21, 15, 32))], + + // strings + [wrap('')], + [wrap('\u0000\ud7ff\ue000\uffff')], + [wrap('(╯°□°)╯︵ ┻━┻')], + [wrap('a')], + [wrap('abc def')], + // latin small letter e + combining acute accent + latin small letter b + [wrap('e\u0301b')], + [wrap('æ')], + // latin small letter e with acute accent + latin small letter a + [wrap('\u00e9a')], + + // blobs + [blob([])], + [blob([0])], + [blob([0, 1, 2, 3, 4])], + [blob([0, 1, 2, 4, 3])], + [blob([255])], + + // resource names + [resource('projects/p1/databases/d1/documents/c1/doc1')], + [resource('projects/p1/databases/d1/documents/c1/doc2')], + [resource('projects/p1/databases/d1/documents/c1/doc2/c2/doc1')], + [resource('projects/p1/databases/d1/documents/c1/doc2/c2/doc2')], + [resource('projects/p1/databases/d1/documents/c10/doc1')], + [resource('projects/p1/databases/d1/documents/c2/doc1')], + [resource('projects/p2/databases/d2/documents/c1/doc1')], + [resource('projects/p2/databases/d2/documents/c1-/doc1')], + [resource('projects/p2/databases/d3/documents/c1-/doc1')], + + // geo points + [geopoint(-90, -180)], + [geopoint(-90, 0)], + [geopoint(-90, 180)], + [geopoint(0, -180)], + [geopoint(0, 0)], + [geopoint(0, 180)], + [geopoint(1, -180)], + [geopoint(1, 0)], + [geopoint(1, 180)], + [geopoint(90, -180)], + [geopoint(90, 0)], + [geopoint(90, 180)], + + // arrays + [wrap([])], + [wrap(['bar'])], + [wrap(['foo'])], + [wrap(['foo', 1])], + [wrap(['foo', 2])], + [wrap(['foo', '0'])], + + // objects + [wrap({bar: 0})], + [wrap({bar: 0, foo: 1})], + [wrap({foo: 1})], + [wrap({foo: 2})], + [wrap({foo: '0'})], + ]; + + for (let i = 0; i < groups.length; i++) { + for (const left of groups[i]) { + for (let j = 0; j < groups.length; j++) { + for (const right of groups[j]) { + let expected = order.primitiveComparator(i, j); + expect(order.compare(left, right)).to.equal( + expected, + 'comparing ' + + left + + ' (' + + JSON.stringify(left) + + ') to ' + + right + + ' (' + + JSON.stringify(right) + + ') at (' + + i + + ', ' + + j + + ')', + ); + + expected = order.primitiveComparator(j, i); + expect(order.compare(right, left)).to.equal( + expected, + 'comparing ' + + right + + ' (' + + JSON.stringify(right) + + ') to ' + + left + + ' (' + + JSON.stringify(left) + + ') at (' + + j + + ', ' + + i + + ')', + ); + } + } + } + } + }); +}); + +class StringPair { + constructor( + readonly s1: string, + readonly s2: string, + ) {} +} + +class StringPairGenerator { + constructor(private stringGenerator: StringGenerator) {} + + next(): StringPair { + const prefix = this.stringGenerator.next(); + const s1 = prefix + this.stringGenerator.next(); + const s2 = prefix + this.stringGenerator.next(); + return new StringPair(s1, s2); + } +} + +class StringGenerator { + private static readonly DEFAULT_SURROGATE_PAIR_PROBABILITY = 0.33; + private static readonly DEFAULT_MAX_LENGTH = 20; + + private readonly rnd: Random; + private readonly surrogatePairProbability: number; + private readonly maxLength: number; + + constructor(seed: number); + constructor(rnd: Random, surrogatePairProbability: number, maxLength: number); + constructor( + seedOrRnd: number | Random, + surrogatePairProbability?: number, + maxLength?: number, + ) { + if (typeof seedOrRnd === 'number') { + this.rnd = new Random(seedOrRnd); + this.surrogatePairProbability = + StringGenerator.DEFAULT_SURROGATE_PAIR_PROBABILITY; + this.maxLength = StringGenerator.DEFAULT_MAX_LENGTH; + } else { + this.rnd = seedOrRnd; + this.surrogatePairProbability = StringGenerator.validateProbability( + surrogatePairProbability!, + ); + this.maxLength = StringGenerator.validateLength(maxLength!); + } + } + + private static validateProbability(probability: number): number { + if (!Number.isFinite(probability)) { + throw new Error( + `invalid surrogate pair probability: ${probability} (must be between 0.0 and 1.0, inclusive)`, + ); + } else if (probability < 0.0) { + throw new Error( + `invalid surrogate pair probability: ${probability} (must be greater than or equal to zero)`, + ); + } else if (probability > 1.0) { + throw new Error( + `invalid surrogate pair probability: ${probability} (must be less than or equal to 1)`, + ); + } + return probability; + } + + private static validateLength(length: number): number { + if (length < 0) { + throw new Error( + `invalid maximum string length: ${length} (must be greater than or equal to zero)`, + ); + } + return length; + } + + next(): string { + const length = this.rnd.nextInt(this.maxLength + 1); + const sb = new StringBuilder(); + while (sb.length() < length) { + const codePoint = this.nextCodePoint(); + sb.appendCodePoint(codePoint); + } + return sb.toString(); + } + + private isNextSurrogatePair(): boolean { + return StringGenerator.nextBoolean(this.rnd, this.surrogatePairProbability); + } + + private static nextBoolean(rnd: Random, probability: number): boolean { + if (probability === 0.0) { + return false; + } else if (probability === 1.0) { + return true; + } else { + return rnd.nextFloat() < probability; + } + } + + private nextCodePoint(): number { + if (this.isNextSurrogatePair()) { + return this.nextSurrogateCodePoint(); + } else { + return this.nextNonSurrogateCodePoint(); + } + } + + private nextSurrogateCodePoint(): number { + const highSurrogateMin = 0xd800; + const highSurrogateMax = 0xdbff; + const lowSurrogateMin = 0xdc00; + const lowSurrogateMax = 0xdfff; + + const highSurrogate = this.nextCodePointRange( + highSurrogateMin, + highSurrogateMax, + ); + const lowSurrogate = this.nextCodePointRange( + lowSurrogateMin, + lowSurrogateMax, + ); + + return (highSurrogate - 0xd800) * 0x400 + (lowSurrogate - 0xdc00) + 0x10000; + } + + private nextNonSurrogateCodePoint(): number { + let codePoint; + do { + codePoint = this.nextCodePointRange(0, 0xffff); // BMP range + } while (codePoint >= 0xd800 && codePoint <= 0xdfff); // Exclude surrogate range + + return codePoint; + } + + private nextCodePointRange(min: number, max: number): number { + const rangeSize = max - min + 1; + const offset = this.rnd.nextInt(rangeSize); + return min + offset; + } +} + +class Random { + private seed: number; + + constructor(seed: number) { + this.seed = seed; + } + + nextInt(max: number): number { + this.seed = (this.seed * 9301 + 49297) % 233280; + const rnd = this.seed / 233280; + return Math.floor(rnd * max); + } + + nextFloat(): number { + this.seed = (this.seed * 9301 + 49297) % 233280; + return this.seed / 233280; + } +} + +class StringBuilder { + private buffer: string[] = []; + + append(str: string): StringBuilder { + this.buffer.push(str); + return this; + } + + appendCodePoint(codePoint: number): StringBuilder { + this.buffer.push(String.fromCodePoint(codePoint)); + return this; + } + + toString(): string { + return this.buffer.join(''); + } + + length(): number { + return this.buffer.join('').length; + } +} + +describe('CompareUtf8Strings', () => { + it('compareUtf8Strings should return correct results', () => { + const errors = []; + const seed = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); + let passCount = 0; + const stringGenerator = new StringGenerator(new Random(seed), 0.33, 20); + const stringPairGenerator = new StringPairGenerator(stringGenerator); + + for (let i = 0; i < 1000000 && errors.length < 10; i++) { + const {s1, s2} = stringPairGenerator.next(); + + const actual = order.compareUtf8Strings(s1, s2); + const expected = Buffer.from(s1, 'utf8').compare(Buffer.from(s2, 'utf8')); + + if (actual === expected) { + passCount++; + } else { + errors.push( + `compareUtf8Strings(s1="${s1}", s2="${s2}") returned ${actual}, ` + + `but expected ${expected} (i=${i}, s1.length=${s1.length}, s2.length=${s2.length})`, + ); + } + } + + if (errors.length > 0) { + console.error( + `${errors.length} test cases failed, ${passCount} test cases passed, seed=${seed};`, + ); + errors.forEach((error, index) => + console.error(`errors[${index}]: ${error}`), + ); + throw new Error('Test failed'); + } + }).timeout(30000); +}); diff --git a/handwritten/firestore/dev/test/partition-query.ts b/handwritten/firestore/dev/test/partition-query.ts new file mode 100644 index 00000000000..3a3ecfd99f8 --- /dev/null +++ b/handwritten/firestore/dev/test/partition-query.ts @@ -0,0 +1,311 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { + CollectionGroup, + DocumentData, + QueryPartition, +} from '@google-cloud/firestore'; + +import {afterEach, beforeEach, describe, it} from 'mocha'; +import {expect, use} from 'chai'; +import * as chaiAsPromised from 'chai-as-promised'; +import * as extend from 'extend'; + +import {google} from '../protos/firestore_v1_proto_api'; +import {DocumentReference, Firestore} from '../src'; +import {setTimeoutHandler} from '../src/backoff'; +import { + ApiOverride, + createInstance, + emptyQueryStream, + stream, + verifyInstance, +} from './util/helpers'; + +use(chaiAsPromised); + +import api = google.firestore.v1; + +const PROJECT_ID = 'test-project'; +const DATABASE_ROOT = `projects/${PROJECT_ID}/databases/(default)`; +const DOC1 = `${DATABASE_ROOT}/documents/coll/doc1`; +const DOC2 = `${DATABASE_ROOT}/documents/coll/doc2`; + +export function partitionQueryEquals( + actual: api.IPartitionQueryRequest | undefined, + partitionCount: number, +) { + expect(actual).to.not.be.undefined; + + const query: api.IPartitionQueryRequest = { + parent: DATABASE_ROOT + '/documents', + structuredQuery: { + from: [ + { + allDescendants: true, + collectionId: 'collectionId', + }, + ], + orderBy: [ + { + direction: 'ASCENDING', + field: { + fieldPath: '__name__', + }, + }, + ], + }, + partitionCount, + }; + + // 'extend' removes undefined fields in the request object. The backend + // ignores these fields, but we need to manually strip them before we compare + // the expected and the actual request. + actual = extend(true, {}, actual); + expect(actual).to.deep.eq(query); +} + +describe('Partition Query', () => { + let firestore: Firestore; + + beforeEach(() => { + setTimeoutHandler(setImmediate); + return createInstance().then(firestoreInstance => { + firestore = firestoreInstance; + }); + }); + + afterEach(async () => { + await verifyInstance(firestore); + setTimeoutHandler(setTimeout); + }); + + async function getPartitions( + collectionGroup: CollectionGroup, + desiredPartitionsCount: number, + ): Promise[]> { + const partitions: QueryPartition[] = []; + for await (const partition of collectionGroup.getPartitions( + desiredPartitionsCount, + )) { + partitions.push(partition); + } + return partitions; + } + + function verifyPartition( + partition: FirebaseFirestore.QueryPartition, + startAt: string | null, + endBefore: string | null, + ) { + if (startAt) { + expect( + partition.startAt?.map(value => (value as DocumentReference).path), + ).to.have.members([startAt]); + } else { + expect(partition.startAt).to.be.undefined; + } + + if (endBefore) { + expect( + partition.endBefore?.map(value => (value as DocumentReference).path), + ).to.have.members([endBefore]); + } else { + expect(partition.endBefore).to.be.undefined; + } + } + + it('requests one less than desired partitions', () => { + const desiredPartitionsCount = 2; + const cursorValue = { + values: [{referenceValue: DOC1}], + }; + + const overrides: ApiOverride = { + partitionQueryStream: request => { + partitionQueryEquals( + request, + /* partitionCount= */ desiredPartitionsCount - 1, + ); + + return stream(cursorValue); + }, + }; + return createInstance(overrides).then(async firestore => { + const query = firestore.collectionGroup('collectionId'); + + const result = await getPartitions(query, desiredPartitionsCount); + expect(result.length).to.equal(2); + expect(result[0].startAt).to.be.undefined; + expect(result[0].endBefore).to.deep.equal(result[1].startAt); + expect(result[1].endBefore).to.be.undefined; + }); + }); + + it('does not issue RPC if only a single partition is requested', () => { + const desiredPartitionsCount = 1; + + return createInstance().then(async firestore => { + const query = firestore.collectionGroup('collectionId'); + + const result = await getPartitions(query, desiredPartitionsCount); + expect(result.length).to.equal(1); + expect(result[0].startAt).to.be.undefined; + expect(result[0].endBefore).to.be.undefined; + }); + }); + + it('validates partition count', () => { + return createInstance().then(firestore => { + const query = firestore.collectionGroup('collectionId'); + return expect(getPartitions(query, 0)).to.eventually.be.rejectedWith( + 'Value for argument "desiredPartitionCount" must be within [1, Infinity] inclusive, but was: 0', + ); + }); + }); + + it('converts partitions to queries', () => { + const desiredPartitionsCount = 3; + + const expectedStartAt: Array = [ + undefined, + {referenceValue: DOC1}, + {referenceValue: DOC2}, + ]; + const expectedEndBefore: Array = [ + {referenceValue: DOC1}, + {referenceValue: DOC2}, + undefined, + ]; + + const overrides: ApiOverride = { + partitionQueryStream: request => { + partitionQueryEquals( + request, + /* partitionCount= */ desiredPartitionsCount - 1, + ); + + return stream( + { + values: [{referenceValue: DOC1}], + }, + { + values: [{referenceValue: DOC2}], + }, + ); + }, + runQuery: request => { + const startAt = expectedStartAt.shift(); + if (startAt) { + expect(request!.structuredQuery!.startAt).to.deep.equal({ + before: true, + values: [startAt], + }); + } else { + expect(request!.structuredQuery!.startAt).to.be.undefined; + } + + const endBefore = expectedEndBefore.shift(); + if (endBefore) { + expect(request!.structuredQuery!.endAt).to.deep.equal({ + before: true, + values: [endBefore], + }); + } else { + expect(request!.structuredQuery!.endAt).to.be.undefined; + } + return emptyQueryStream(); + }, + }; + return createInstance(overrides).then(async firestore => { + const query = firestore.collectionGroup('collectionId'); + + const partitions = await getPartitions(query, desiredPartitionsCount); + expect(partitions.length).to.equal(3); + + for (const partition of partitions) { + await partition.toQuery().get(); + } + }); + }); + + it("doesn't truncate large numbers", () => { + // JavaScript by default truncates large numbers. If partition data were + // to include truncated numbers, using them as cursors could skip or + // duplicate results. Note that the backend API currently only returns + // DocumentReferences as partitions, but this may change in the future. + const bigIntValue = BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1); + const desiredPartitionsCount = 2; + + const overrides: ApiOverride = { + partitionQueryStream: request => { + partitionQueryEquals( + request, + /* partitionCount= */ desiredPartitionsCount - 1, + ); + + return stream({ + values: [{integerValue: bigIntValue.toString()}], + }); + }, + runQuery: request => { + expect( + request!.structuredQuery!.endAt!.values![0].integerValue, + ).to.equal(bigIntValue.toString()); + return emptyQueryStream(); + }, + }; + return createInstance(overrides).then(async firestore => { + const query = firestore.collectionGroup('collectionId'); + + const result = await getPartitions(query, desiredPartitionsCount); + expect(result.length).to.equal(2); + + // If the user uses the cursor directly, we follow the `useBigInt` + // setting. By default, we return a truncated number. + expect(result[0].endBefore![0]).to.be.a('number'); + expect(result[1].startAt![0]).to.be.a('number'); + return result[0].toQuery().get(); + }); + }); + + it('sorts partitions', () => { + const desiredPartitionsCount = 3; + + const overrides: ApiOverride = { + partitionQueryStream: () => { + return stream( + { + values: [{referenceValue: DOC2}], + }, + { + values: [{referenceValue: DOC1}], + }, + ); + }, + }; + + return createInstance(overrides).then(async firestore => { + const query = firestore.collectionGroup('collectionId'); + + const partitions = await getPartitions(query, desiredPartitionsCount); + expect(partitions.length).to.equal(3); + + verifyPartition(partitions[0], null, 'coll/doc1'); + verifyPartition(partitions[1], 'coll/doc1', 'coll/doc2'); + verifyPartition(partitions[2], 'coll/doc2', null); + }); + }); +}); diff --git a/handwritten/firestore/dev/test/path.ts b/handwritten/firestore/dev/test/path.ts new file mode 100644 index 00000000000..a42e9f6e99a --- /dev/null +++ b/handwritten/firestore/dev/test/path.ts @@ -0,0 +1,190 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {describe, it} from 'mocha'; +import {expect} from 'chai'; + +import {FieldPath, QualifiedResourcePath} from '../src/path'; +import {InvalidApiUsage} from './util/helpers'; + +const PROJECT_ID = 'test-project'; +const DATABASE_ROOT = `projects/${PROJECT_ID}/databases/(default)`; + +describe('ResourcePath', () => { + it('has id property', () => { + expect( + new QualifiedResourcePath(PROJECT_ID, '(default)', 'foo').id, + ).to.equal('foo'); + expect(new QualifiedResourcePath(PROJECT_ID, '(default)').id).to.be.null; + }); + + it('has append() method', () => { + let path = new QualifiedResourcePath(PROJECT_ID, '(default)'); + expect(path.formattedName).to.equal(`${DATABASE_ROOT}/documents`); + path = path.append('foo'); + expect(path.formattedName).to.equal(`${DATABASE_ROOT}/documents/foo`); + }); + + it('has parent() method', () => { + let path = new QualifiedResourcePath(PROJECT_ID, '(default)', 'foo'); + expect(path.formattedName).to.equal(`${DATABASE_ROOT}/documents/foo`); + path = path.parent()!; + expect(path.formattedName).to.equal(`${DATABASE_ROOT}/documents`); + expect(path.parent()).to.be.null; + }); + + it('parses strings', () => { + // parse reference to db root + let path = QualifiedResourcePath.fromSlashSeparatedString(DATABASE_ROOT); + expect(path.formattedName).to.equal(`${DATABASE_ROOT}/documents`); + expect(path.isCollection).to.equal(false); + expect(path.isDocument).to.equal(false); + + // parse reference to db root with `/documents` + path = QualifiedResourcePath.fromSlashSeparatedString( + `${DATABASE_ROOT}/documents`, + ); + expect(path.formattedName).to.equal(`${DATABASE_ROOT}/documents`); + expect(path.isCollection).to.equal(false); + expect(path.isDocument).to.equal(false); + + // parse reference to collection + path = QualifiedResourcePath.fromSlashSeparatedString( + `${DATABASE_ROOT}/documents/foo`, + ); + expect(path.formattedName).to.equal(`${DATABASE_ROOT}/documents/foo`); + expect(path.isCollection).to.equal(true); + expect(path.isDocument).to.equal(false); + + // parse reference to document + path = QualifiedResourcePath.fromSlashSeparatedString( + `${DATABASE_ROOT}/documents/foo/bar`, + ); + expect(path.formattedName).to.equal(`${DATABASE_ROOT}/documents/foo/bar`); + expect(path.isCollection).to.equal(false); + expect(path.isDocument).to.equal(true); + + // parse reference to nested collection + path = QualifiedResourcePath.fromSlashSeparatedString( + `${DATABASE_ROOT}/documents/foo/bar/baz`, + ); + expect(path.formattedName).to.equal( + `${DATABASE_ROOT}/documents/foo/bar/baz`, + ); + expect(path.isCollection).to.equal(true); + expect(path.isDocument).to.equal(false); + + expect(() => { + path = QualifiedResourcePath.fromSlashSeparatedString( + 'projects/project/databases', + ); + }).to.throw("Resource name 'projects/project/databases' is not valid"); + }); + + it('does not parse invalid paths', () => { + const invalidPaths: string[] = [ + 'projects/PPP/databases/DDD/wrong', + 'projects/PPP/databases/DDD//', + 'projects/PPP/databases/DDD/documentsBAD', + 'projects/PPP/databases/DDD/documents//', + 'projects/PPP/databases/DDD/documents/ok//ok', + 'projects/PPP/databases//DDD/documents', + 'projects/PPP/databases/DDD/documents/', + 'projects/PPP/databases//documents', + 'projects//databases/DDD/documents', + ]; + + invalidPaths.forEach(invalidPath => { + expect(() => { + QualifiedResourcePath.fromSlashSeparatedString(invalidPath); + }).to.throw(`Resource name '${invalidPath}' is not valid`); + }); + }); + + it('accepts newlines', () => { + const path = QualifiedResourcePath.fromSlashSeparatedString( + `${DATABASE_ROOT}/documents/foo\nbar`, + ); + expect(path.formattedName).to.equal(`${DATABASE_ROOT}/documents/foo\nbar`); + }); +}); + +describe('FieldPath', () => { + it('encodes field names', () => { + const components = [ + ['foo'], + ['foo', 'bar'], + ['.', '`'], + ['\\'], + ['\\\\'], + ['``'], + ]; + + const results = [ + 'foo', + 'foo.bar', + '`.`.`\\``', + '`\\\\`', + '`\\\\\\\\`', + '`\\`\\``', + ]; + + for (let i = 0; i < components.length; ++i) { + expect(new FieldPath(...components[i]).toString()).to.equal(results[i]); + } + }); + + it("doesn't accept empty path", () => { + expect(() => { + new FieldPath(); + }).to.throw('Function "FieldPath()" requires at least 1 argument.'); + }); + + it('only accepts strings', () => { + expect(() => { + new FieldPath('foo', 'bar', 0 as InvalidApiUsage); + }).to.throw('Element at index 2 is not a valid string.'); + }); + + it('has append() method', () => { + let path = new FieldPath('foo'); + path = path.append('bar'); + expect(path.formattedName).to.equal('foo.bar'); + }); + + it('has parent() method', () => { + let path = new FieldPath('foo', 'bar'); + path = path.parent()!; + expect(path.formattedName).to.equal('foo'); + }); + + it('escapes special characters', () => { + const path = new FieldPath('f.o.o'); + expect(path.formattedName).to.equal('`f.o.o`'); + }); + + it("doesn't allow empty components", () => { + expect(() => { + new FieldPath('foo', ''); + }).to.throw('Element at index 1 should not be an empty string.'); + }); + + it('has isEqual() method', () => { + const path = new FieldPath('a'); + const equals = new FieldPath('a'); + const notEquals = new FieldPath('a', 'b', 'a'); + expect(path.isEqual(equals)).to.be.true; + expect(path.isEqual(notEquals)).to.be.false; + }); +}); diff --git a/handwritten/firestore/dev/test/pipelines/pipeline.ts b/handwritten/firestore/dev/test/pipelines/pipeline.ts new file mode 100644 index 00000000000..e67514a3342 --- /dev/null +++ b/handwritten/firestore/dev/test/pipelines/pipeline.ts @@ -0,0 +1,429 @@ +/** + * @license + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {expect} from 'chai'; +import * as sinon from 'sinon'; +import {createInstance, stream} from '../util/helpers'; +import {google} from '../../protos/firestore_v1_proto_api'; +import {Timestamp, Pipelines, Firestore} from '../../src'; +import IExecutePipelineRequest = google.firestore.v1.IExecutePipelineRequest; +import IExecutePipelineResponse = google.firestore.v1.IExecutePipelineResponse; +import Pipeline = Pipelines.Pipeline; +import field = Pipelines.field; +import sum = Pipelines.sum; +import descending = Pipelines.descending; +import IValue = google.firestore.v1.IValue; + +const FIRST_CALL = 0; +const EXECUTE_PIPELINE_REQUEST = 0; + +describe('execute(Pipeline|PipelineExecuteOptions)', () => { + it('returns execution time with empty results', async () => { + const executeTime = Timestamp.now(); + const results: IExecutePipelineResponse[] = [ + { + executionTime: executeTime.toProto().timestampValue, + results: [], + }, + ]; + + const firestore = await createInstance({ + executePipeline: () => stream(...results), + }); + + const pipelineSnapshot = await firestore + .pipeline() + .collection('foo') + .execute(); + + expect(pipelineSnapshot.results.length).to.equal(0); + + expect(pipelineSnapshot.executionTime.toProto()).to.deep.equal( + executeTime.toProto(), + ); + }); + + it('serializes the pipeline', async () => { + const spy = sinon.fake.returns(stream()); + const firestore = await createInstance({ + executePipeline: spy, + }); + + await firestore.pipeline().collection('foo').execute(); + + const executePipelineRequest: IExecutePipelineRequest = { + database: 'projects/test-project/databases/(default)', + structuredPipeline: { + options: {}, + pipeline: { + stages: [ + { + args: [ + { + referenceValue: '/foo', + }, + ], + name: 'collection', + options: {}, + }, + ], + }, + }, + }; + expect(spy.args[FIRST_CALL][EXECUTE_PIPELINE_REQUEST]).to.deep.equal( + executePipelineRequest, + ); + }); + + it('serializes the pipeline options', async () => { + const spy = sinon.fake.returns(stream()); + const firestore = await createInstance({ + executePipeline: spy, + }); + + await firestore + .pipeline() + .collection('foo') + .execute({ + indexMode: 'recommended', + explainOptions: { + mode: 'analyze', + }, + }); + + const executePipelineRequest: IExecutePipelineRequest = { + database: 'projects/test-project/databases/(default)', + structuredPipeline: { + options: { + index_mode: { + stringValue: 'recommended', + }, + explain_options: { + mapValue: { + fields: { + mode: { + stringValue: 'analyze', + }, + }, + }, + }, + }, + pipeline: { + stages: [ + { + args: [ + { + referenceValue: '/foo', + }, + ], + name: 'collection', + options: {}, + }, + ], + }, + }, + }; + expect(spy.args[FIRST_CALL][EXECUTE_PIPELINE_REQUEST]).to.deep.equal( + executePipelineRequest, + ); + }); + + it('serializes the pipeline raw options', async () => { + const spy = sinon.fake.returns(stream()); + const firestore = await createInstance({ + executePipeline: spy, + }); + + await firestore + .pipeline() + .collection('foo') + .execute({ + rawOptions: { + foo: 'bar', + }, + }); + + const executePipelineRequest: IExecutePipelineRequest = { + database: 'projects/test-project/databases/(default)', + structuredPipeline: { + options: { + foo: { + stringValue: 'bar', + }, + }, + pipeline: { + stages: [ + { + args: [ + { + referenceValue: '/foo', + }, + ], + name: 'collection', + options: {}, + }, + ], + }, + }, + }; + expect(spy.args[FIRST_CALL][EXECUTE_PIPELINE_REQUEST]).to.deep.equal( + executePipelineRequest, + ); + }); +}); + +describe('stage option serialization', () => { + // Default rawOptions + const rawOptions: Record = { + foo: 'bar1', + }; + // Default expected serialized options + const expectedSerializedOptions: Record = { + foo: { + stringValue: 'bar1', + }, + }; + + const testDefinitions: Array<{ + name: string; + pipeline: (firestore: Firestore) => Pipeline; + stageIndex?: number; + expectedOptions?: Record; + }> = [ + { + name: 'collection stage', + pipeline: firestore => + firestore.pipeline().collection({ + collection: 'foo', + rawOptions, + forceIndex: 'foo-index', + }), + expectedOptions: { + ...expectedSerializedOptions, + force_index: { + stringValue: 'foo-index', + }, + }, + }, + { + name: 'collection group stage', + pipeline: firestore => + firestore.pipeline().collectionGroup({ + collectionId: 'foo', + rawOptions, + forceIndex: 'bar-index', + }), + expectedOptions: { + ...expectedSerializedOptions, + force_index: { + stringValue: 'bar-index', + }, + }, + }, + { + name: 'documents stage', + pipeline: firestore => + firestore.pipeline().documents({ + docs: ['foo/bar'], + rawOptions, + }), + }, + { + name: 'database stage', + pipeline: firestore => + firestore.pipeline().database({ + rawOptions, + }), + }, + { + name: 'distinct stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .distinct({ + groups: ['foo'], + rawOptions, + }), + stageIndex: 1, + }, + { + name: 'findNearest stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .findNearest({ + field: 'foo', + vectorValue: [0], + distanceMeasure: 'euclidean', + rawOptions, + }), + stageIndex: 1, + }, + { + name: 'select stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .select({ + selections: ['foo'], + rawOptions, + }), + stageIndex: 1, + }, + { + name: 'unnest stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .unnest({ + selectable: field('foo'), + rawOptions, + }), + stageIndex: 1, + }, + { + name: 'addFields stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .addFields({ + fields: [field('foo')], + rawOptions, + }), + stageIndex: 1, + }, + { + name: 'aggregate stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .aggregate({ + accumulators: [sum('foo').as('fooSum')], + rawOptions, + }), + stageIndex: 1, + }, + { + name: 'limit stage', + pipeline: firestore => + firestore.pipeline().database().limit({ + limit: 1, + rawOptions, + }), + stageIndex: 1, + }, + { + name: 'offset stage', + pipeline: firestore => + firestore.pipeline().database().offset({ + offset: 1, + rawOptions, + }), + stageIndex: 1, + }, + { + name: 'removeFields stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .removeFields({ + fields: ['foo'], + rawOptions, + }), + stageIndex: 1, + }, + { + name: 'replaceWith stage', + pipeline: firestore => + firestore.pipeline().database().replaceWith({ + map: 'foo', + rawOptions, + }), + stageIndex: 1, + }, + { + name: 'sample stage', + pipeline: firestore => + firestore.pipeline().database().sample({ + documents: 100, + rawOptions, + }), + stageIndex: 1, + }, + { + name: 'sample stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .sort({ + orderings: [descending('foo')], + rawOptions, + }), + stageIndex: 1, + }, + { + name: 'union stage', + pipeline: firestore => + firestore.pipeline().database().union({ + other: firestore.pipeline().database(), + rawOptions, + }), + stageIndex: 1, + }, + { + name: 'where stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .where({ + condition: field('foo').equal(1), + rawOptions, + }), + stageIndex: 1, + }, + ]; + + testDefinitions.forEach(testDefinition => { + it(testDefinition.name, async () => { + const spy = sinon.fake.returns(stream()); + const firestore = await createInstance({ + executePipeline: spy, + }); + + await testDefinition.pipeline(firestore).execute(); + + const expectedOptions = testDefinition.expectedOptions + ? testDefinition.expectedOptions + : expectedSerializedOptions; + + expect( + spy.args[FIRST_CALL][EXECUTE_PIPELINE_REQUEST]['structuredPipeline'][ + 'pipeline' + ]['stages'][testDefinition.stageIndex ?? 0]['options'], + ).to.deep.equal(expectedOptions); + }); + }); +}); diff --git a/handwritten/firestore/dev/test/pool.ts b/handwritten/firestore/dev/test/pool.ts new file mode 100644 index 00000000000..3a7b188a560 --- /dev/null +++ b/handwritten/firestore/dev/test/pool.ts @@ -0,0 +1,679 @@ +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {describe, it} from 'mocha'; +import {expect, use} from 'chai'; +import {GoogleError} from 'google-gax'; +import * as chaiAsPromised from 'chai-as-promised'; + +import {ClientPool, CLIENT_TERMINATED_ERROR_MSG} from '../src/pool'; +import {Deferred} from '../src/util'; + +use(chaiAsPromised); + +const REQUEST_TAG = 'tag'; +const USE_REST = false; +const USE_GRPC = true; + +function deferredPromises(count: number): Array> { + const deferred: Array> = []; + for (let i = 0; i < count; ++i) { + deferred.push(new Deferred()); + } + return deferred; +} + +function assertOpCount( + pool: ClientPool, + grpcClientOpCount: number, + restClientOpCount: number, +): void { + let actualGrpcClientOpCount = 0; + let actualRestClientOpCount = 0; + + pool._activeClients.forEach(clientConfig => { + if (clientConfig.grpcEnabled) { + actualGrpcClientOpCount += clientConfig.activeRequestCount; + } else { + actualRestClientOpCount += clientConfig.activeRequestCount; + } + }); + + expect(actualGrpcClientOpCount).to.equal(grpcClientOpCount); + expect(actualRestClientOpCount).to.equal(restClientOpCount); +} + +describe('Client pool', () => { + it('creates new instances as needed', () => { + const clientPool = new ClientPool<{}>(3, 0, () => { + return {}; + }); + + expect(clientPool.size).to.equal(0); + + const operationPromises = deferredPromises(4); + + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[0].promise, + ); + expect(clientPool.size).to.equal(1); + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[1].promise, + ); + expect(clientPool.size).to.equal(1); + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[2].promise, + ); + expect(clientPool.size).to.equal(1); + + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[3].promise, + ); + expect(clientPool.size).to.equal(2); + }); + + it('re-uses instances with remaining capacity', async () => { + const clientPool = new ClientPool<{}>(2, 0, () => { + return {}; + }); + + expect(clientPool.size).to.equal(0); + + const operationPromises = deferredPromises(5); + + const completionPromise = clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[0].promise, + ); + expect(clientPool.size).to.equal(1); + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[1].promise, + ); + expect(clientPool.size).to.equal(1); + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[2].promise, + ); + expect(clientPool.size).to.equal(2); + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[3].promise, + ); + expect(clientPool.size).to.equal(2); + + operationPromises[0].resolve(); + + await completionPromise; + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[4].promise, + ); + expect(clientPool.size).to.equal(2); + }); + + it('re-uses idle instances', async () => { + let instanceCount = 0; + const clientPool = new ClientPool<{}>(1, 1, () => { + ++instanceCount; + return {}; + }); + + const operationPromises = deferredPromises(2); + + let completionPromise = clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[0].promise, + ); + expect(clientPool.size).to.equal(1); + operationPromises[0].resolve(); + await completionPromise; + + completionPromise = clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[1].promise, + ); + expect(clientPool.size).to.equal(1); + operationPromises[1].resolve(); + await completionPromise; + + expect(instanceCount).to.equal(1); + }); + + it('does not re-use rest instance for grpc call', async () => { + const clientPool = new ClientPool<{}>(10, 1, () => { + return {}; + }); + + const operationPromises = deferredPromises(2); + + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[0].promise, + ); + void clientPool.run( + REQUEST_TAG, + USE_GRPC, + () => operationPromises[1].promise, + ); + expect(clientPool.size).to.equal(2); + assertOpCount(clientPool, 1, 1); + + operationPromises[0].resolve(); + operationPromises[1].resolve(); + }); + + it('re-uses grpc instance for rest calls', async () => { + const clientPool = new ClientPool<{}>(10, 1, () => { + return {}; + }); + + const operationPromises = deferredPromises(2); + + void clientPool.run( + REQUEST_TAG, + USE_GRPC, + () => operationPromises[0].promise, + ); + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[1].promise, + ); + expect(clientPool.size).to.equal(1); + assertOpCount(clientPool, 2, 0); + + operationPromises[0].resolve(); + operationPromises[1].resolve(); + }); + + it('does not re-use rest instance after beginning the transition to grpc', async () => { + const clientPool = new ClientPool<{}>(10, 1, () => { + return {}; + }); + + const operationPromises = deferredPromises(3); + + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[0].promise, + ); + void clientPool.run( + REQUEST_TAG, + USE_GRPC, + () => operationPromises[1].promise, + ); + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[2].promise, + ); + + expect(clientPool.size).to.equal(2); + assertOpCount(clientPool, 2, 1); + + operationPromises[0].resolve(); + operationPromises[1].resolve(); + operationPromises[2].resolve(); + }); + + it('does not re-use rest instance after beginning the transition to grpc - rest operation resolved', async () => { + const clientPool = new ClientPool<{}>(10, 1, () => { + return {}; + }); + + const operationPromises = deferredPromises(3); + + const restOperation = clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[0].promise, + ); + void clientPool.run( + REQUEST_TAG, + USE_GRPC, + () => operationPromises[1].promise, + ); + + // resolve rest operation + operationPromises[0].resolve(); + await restOperation; + expect(clientPool.opCount).to.equal(1); + + // Run new rest operation + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[2].promise, + ); + + // Assert client pool status + expect(clientPool.size).to.equal(1); + assertOpCount(clientPool, 2, 0); + + operationPromises[1].resolve(); + operationPromises[2].resolve(); + }); + + it('does not re-use rest instance after beginning the transition to grpc - grpc client full', async () => { + const operationLimit = 10; + const clientPool = new ClientPool<{}>(operationLimit, 1, () => { + return {}; + }); + + const restPromises = deferredPromises(operationLimit); + const grpcPromises = deferredPromises(1); + + // First operation use GRPC + void clientPool.run(REQUEST_TAG, USE_GRPC, () => grpcPromises[0].promise); + + // Next X operations can use rest, this will fill the first + // client and create a new client. + // The new client should use GRPC since we have transitioned. + restPromises.forEach(restPromise => { + void clientPool.run(REQUEST_TAG, USE_REST, () => restPromise.promise); + }); + expect(clientPool.opCount).to.equal(11); + expect(clientPool.size).to.equal(2); + assertOpCount(clientPool, 11, 0); + + grpcPromises.forEach(grpcPromise => grpcPromise.resolve()); + restPromises.forEach(restPromise => restPromise.resolve()); + }); + + it('does not re-use rest instance after beginning the transition to grpc - multiple rest clients', async () => { + const operationLimit = 10; + const clientPool = new ClientPool<{}>(operationLimit, 1, () => { + return {}; + }); + + const restPromises = deferredPromises(15); + const grpcPromises = deferredPromises(5); + + // First 15 operations can use rest, this will fill the first + // client and create a new client. + restPromises.forEach(restPromise => { + void clientPool.run(REQUEST_TAG, USE_REST, () => restPromise.promise); + }); + expect(clientPool.opCount).to.equal(15); + expect(clientPool.size).to.equal(2); + assertOpCount(clientPool, 0, 15); + + // Next 5 operations alternate between gRPC and REST, this will create a new client using gRPC + let transport = USE_GRPC; + grpcPromises.forEach(grpcPromise => { + void clientPool.run(REQUEST_TAG, transport, () => grpcPromise.promise); + transport = !transport; + }); + expect(clientPool.opCount).to.equal(20); + expect(clientPool.size).to.equal(3); + assertOpCount(clientPool, 5, 15); + + grpcPromises.forEach(grpcPromise => grpcPromise.resolve()); + restPromises.forEach(restPromise => restPromise.resolve()); + }); + + it('does not re-use rest instance after beginning the transition to grpc - grpc client RST_STREAM', async () => { + const clientPool = new ClientPool<{}>(10, 1, () => { + return {}; + }); + + const operationPromises = deferredPromises(1); + + const grpcOperation = clientPool.run(REQUEST_TAG, USE_GRPC, () => + Promise.reject( + new GoogleError('13 INTERNAL: Received RST_STREAM with code 2'), + ), + ); + + await grpcOperation.catch(e => e); + + // Run new rest operation + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[0].promise, + ); + + // Assert client pool status + expect(clientPool.size).to.equal(1); + assertOpCount(clientPool, 1, 0); + + operationPromises[0].resolve(); + }); + + it('bin packs operations', async () => { + let clientCount = 0; + const clientPool = new ClientPool<{count: number}>(2, 0, () => { + return {count: ++clientCount}; + }); + + expect(clientPool.size).to.equal(0); + + // Create 5 operations, which should schedule 2 operations on the first + // client, 2 on the second and 1 on the third. + const operationPromises = deferredPromises(7); + void clientPool.run(REQUEST_TAG, USE_REST, client => { + expect(client.count).to.be.equal(1); + return operationPromises[0].promise; + }); + void clientPool.run(REQUEST_TAG, USE_REST, client => { + expect(client.count).to.be.equal(1); + return operationPromises[1].promise; + }); + const thirdOperation = clientPool.run(REQUEST_TAG, USE_REST, client => { + expect(client.count).to.be.equal(2); + return operationPromises[2].promise; + }); + void clientPool.run(REQUEST_TAG, USE_REST, client => { + expect(client.count).to.be.equal(2); + return operationPromises[3].promise; + }); + void clientPool.run(REQUEST_TAG, USE_REST, client => { + expect(client.count).to.be.equal(3); + return operationPromises[4].promise; + }); + + // Free one slot on the second client. + operationPromises[2].resolve(); + await thirdOperation; + + // A newly scheduled operation should use the first client that has a free + // slot. + void clientPool.run(REQUEST_TAG, USE_REST, async client => { + expect(client.count).to.be.equal(2); + }); + }); + + it('garbage collects after success', async () => { + const clientPool = new ClientPool<{}>(2, 0, () => { + return {}; + }); + + expect(clientPool.size).to.equal(0); + + const operationPromises = deferredPromises(4); + const completionPromises: Array> = []; + + completionPromises.push( + clientPool.run(REQUEST_TAG, USE_REST, () => operationPromises[0].promise), + ); + expect(clientPool.size).to.equal(1); + completionPromises.push( + clientPool.run(REQUEST_TAG, USE_REST, () => operationPromises[1].promise), + ); + expect(clientPool.size).to.equal(1); + completionPromises.push( + clientPool.run(REQUEST_TAG, USE_REST, () => operationPromises[2].promise), + ); + expect(clientPool.size).to.equal(2); + completionPromises.push( + clientPool.run(REQUEST_TAG, USE_REST, () => operationPromises[3].promise), + ); + expect(clientPool.size).to.equal(2); + + operationPromises.forEach(deferred => deferred.resolve()); + + await Promise.all(completionPromises); + expect(clientPool.size).to.equal(0); + }); + + it('garbage collects after error', async () => { + const clientPool = new ClientPool<{}>(2, 0, () => { + return {}; + }); + + expect(clientPool.size).to.equal(0); + + const operationPromises = deferredPromises(4); + const completionPromises: Array> = []; + + completionPromises.push( + clientPool.run(REQUEST_TAG, USE_REST, () => operationPromises[0].promise), + ); + expect(clientPool.size).to.equal(1); + completionPromises.push( + clientPool.run(REQUEST_TAG, USE_REST, () => operationPromises[1].promise), + ); + expect(clientPool.size).to.equal(1); + completionPromises.push( + clientPool.run(REQUEST_TAG, USE_REST, () => operationPromises[2].promise), + ); + expect(clientPool.size).to.equal(2); + completionPromises.push( + clientPool.run(REQUEST_TAG, USE_REST, () => operationPromises[3].promise), + ); + expect(clientPool.size).to.equal(2); + + operationPromises.forEach(deferred => deferred.reject(new Error())); + + await Promise.all(completionPromises.map(p => p.catch(() => {}))); + expect(clientPool.size).to.equal(0); + }); + + it('garbage collection calls destructor', () => { + const garbageCollect = new Deferred(); + + const clientPool = new ClientPool<{}>( + 1, + 0, + () => ({}), + () => Promise.resolve(garbageCollect.resolve()), + ); + + const operationPromises = deferredPromises(2); + + // Create two pending operations that each spawn their own client + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[0].promise, + ); + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[1].promise, + ); + + operationPromises.forEach(deferred => deferred.resolve()); + + return garbageCollect.promise; + }); + + it('forwards success', () => { + const clientPool = new ClientPool<{}>(1, 0, () => { + return {}; + }); + + const op = clientPool.run(REQUEST_TAG, USE_REST, () => + Promise.resolve('Success'), + ); + return expect(op).to.become('Success'); + }); + + it('forwards failure', () => { + const clientPool = new ClientPool<{}>(1, 0, () => { + return {}; + }); + + const op = clientPool.run(REQUEST_TAG, USE_REST, () => + Promise.reject('Generated error'), + ); + return expect(op).to.eventually.be.rejectedWith('Generated error'); + }); + + it('does not re-use clients after RST_STREAM', async () => { + let instanceCount = 0; + const clientPool = new ClientPool<{}>(1, 1, () => { + ++instanceCount; + return {}; + }); + + const op = clientPool.run(REQUEST_TAG, USE_REST, () => + Promise.reject( + new GoogleError('13 INTERNAL: Received RST_STREAM with code 2'), + ), + ); + await op.catch(() => {}); + + await clientPool.run(REQUEST_TAG, USE_REST, async () => {}); + + expect(instanceCount).to.equal(2); + }); + + it('garbage collects after RST_STREAM', async () => { + const clientPool = new ClientPool<{}>(1, 1, () => { + return {}; + }); + + const op = clientPool.run(REQUEST_TAG, USE_REST, () => + Promise.reject( + new GoogleError('13 INTERNAL: Received RST_STREAM with code 2'), + ), + ); + await op.catch(() => {}); + + expect(clientPool.size).to.equal(0); + }); + + it('garbage collects rest clients after GRPC', async () => { + const clientPool = new ClientPool<{}>(10, 1, () => { + return {}; + }); + + await clientPool.run(REQUEST_TAG, USE_REST, () => Promise.resolve()); + await clientPool.run(REQUEST_TAG, USE_GRPC, () => Promise.resolve()); + + expect(clientPool.size).to.equal(1); + }); + + it('keeps pool of idle clients', async () => { + const clientPool = new ClientPool<{}>( + /* concurrentOperationLimit= */ 1, + /* maxIdleClients= */ 3, + () => { + return {}; + }, + ); + + const operationPromises = deferredPromises(4); + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[0].promise, + ); + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[1].promise, + ); + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[2].promise, + ); + const lastOp = clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[3].promise, + ); + expect(clientPool.size).to.equal(4); + + // Resolve all pending operations. Note that one client is removed, while + // 3 are kept for further usage. + operationPromises.forEach(deferred => deferred.resolve()); + await lastOp; + expect(clientPool.size).to.equal(3); + }); + + it('default setting keeps at least one idle client', async () => { + const clientPool = new ClientPool<{}>( + 1, + /* maxIdleClients= git c*/ 1, + () => { + return {}; + }, + ); + + const operationPromises = deferredPromises(2); + void clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[0].promise, + ); + const completionPromise = clientPool.run( + REQUEST_TAG, + USE_REST, + () => operationPromises[1].promise, + ); + expect(clientPool.size).to.equal(2); + + operationPromises[0].resolve(); + operationPromises[1].resolve(); + await completionPromise; + expect(clientPool.size).to.equal(1); + }); + + it('rejects subsequent operations after being terminated', async () => { + const clientPool = new ClientPool<{}>(1, 0, () => { + return {}; + }); + + await clientPool.terminate(); + await expect( + clientPool.run(REQUEST_TAG, USE_REST, () => + Promise.reject('Call to run() should have failed'), + ), + ).to.be.rejectedWith(CLIENT_TERMINATED_ERROR_MSG); + }); + + it('waits for existing operations to complete before releasing clients', async () => { + const clientPool = new ClientPool<{}>(1, 0, () => { + return {}; + }); + const deferred = new Deferred(); + let terminated = false; + + // Run operation that completes after terminate() is called. + void clientPool.run(REQUEST_TAG, USE_REST, () => { + return deferred.promise; + }); + const terminateOp = clientPool.terminate().then(() => { + terminated = true; + }); + + expect(terminated).to.be.false; + // Mark the mock operation as "complete". + deferred.resolve(); + await terminateOp; + expect(terminated).to.be.true; + }); +}); diff --git a/handwritten/firestore/dev/test/query.ts b/handwritten/firestore/dev/test/query.ts new file mode 100644 index 00000000000..b3ee1595bee --- /dev/null +++ b/handwritten/firestore/dev/test/query.ts @@ -0,0 +1,3694 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {DocumentData} from '@google-cloud/firestore'; + +import {describe, it, beforeEach, afterEach} from 'mocha'; +import {expect, use} from 'chai'; +import * as chaiAsPromised from 'chai-as-promised'; +import * as extend from 'extend'; +import * as assert from 'assert'; + +import {firestore, google} from '../protos/firestore_v1_proto_api'; +import { + DocumentReference, + FieldPath, + FieldValue, + Firestore, + Query, + QueryDocumentSnapshot, + setLogFunction, + Timestamp, +} from '../src'; +import {setTimeoutHandler} from '../src/backoff'; +import {DocumentSnapshot, DocumentSnapshotBuilder} from '../src/document'; +import {QualifiedResourcePath} from '../src/path'; +import { + ApiOverride, + collect, + createInstance, + document, + emptyQueryStream, + InvalidApiUsage, + Post, + postConverter, + requestEquals, + response, + set, + stream, + streamWithoutEnd, + verifyInstance, + writeResult, +} from './util/helpers'; + +import {GoogleError, Status} from 'google-gax'; +import api = google.firestore.v1; +import protobuf = google.protobuf; +import {Filter} from '../src/filter'; + +const PROJECT_ID = 'test-project'; +const DATABASE_ROOT = `projects/${PROJECT_ID}/databases/(default)`; + +// Change the argument to 'console.log' to enable debug output. +setLogFunction(null); + +use(chaiAsPromised); + +async function snapshot( + relativePath: string, + data: DocumentData, +): Promise { + const firestore = await createInstance(); + const path = QualifiedResourcePath.fromSlashSeparatedString( + `${DATABASE_ROOT}/documents/${relativePath}`, + ); + const ref = new DocumentReference(firestore, path); + const snapshot = new DocumentSnapshotBuilder(ref); + snapshot.fieldsProto = firestore['_serializer']!.encodeFields(data); + snapshot.readTime = Timestamp.fromMillis(0); + snapshot.createTime = Timestamp.fromMillis(0); + snapshot.updateTime = Timestamp.fromMillis(0); + return snapshot.build(); +} + +function where(filter: api.StructuredQuery.IFilter): api.IStructuredQuery { + return { + where: filter, + }; +} + +export function fieldFiltersQuery( + fieldPath: string, + op: api.StructuredQuery.FieldFilter.Operator, + value: string | api.IValue, + ...fieldPathOpAndValues: Array< + string | api.StructuredQuery.FieldFilter.Operator | string | api.IValue + > +): api.IStructuredQuery { + return { + where: fieldFilters(fieldPath, op, value, ...fieldPathOpAndValues), + }; +} + +export function fieldFilters( + fieldPath: string, + op: api.StructuredQuery.FieldFilter.Operator, + value: string | api.IValue, + ...fieldPathOpAndValues: Array< + string | api.StructuredQuery.FieldFilter.Operator | string | api.IValue + > +): api.StructuredQuery.IFilter { + const filters: api.StructuredQuery.IFilter[] = []; + + fieldPathOpAndValues = [fieldPath, op, value, ...fieldPathOpAndValues]; + + for (let i = 0; i < fieldPathOpAndValues.length; i += 3) { + fieldPath = fieldPathOpAndValues[i] as string; + op = fieldPathOpAndValues[ + i + 1 + ] as api.StructuredQuery.FieldFilter.Operator; + value = fieldPathOpAndValues[i + 2] as string | api.IValue; + + const filter: api.StructuredQuery.IFieldFilter = { + field: { + fieldPath, + }, + op, + }; + + if (typeof value === 'string') { + filter.value = {stringValue: value}; + } else { + filter.value = value; + } + + filters.push({fieldFilter: filter}); + } + + if (filters.length === 1) { + return { + fieldFilter: filters[0].fieldFilter, + }; + } else { + return { + compositeFilter: { + op: 'AND', + filters, + }, + }; + } +} + +export function fieldFilter( + fieldPath: string, + op: api.StructuredQuery.FieldFilter.Operator, + value: string | api.IValue, +): api.StructuredQuery.IFilter { + return fieldFilters(fieldPath, op, value); +} + +export function compositeFilter( + op: api.StructuredQuery.CompositeFilter.Operator, + ...filters: api.StructuredQuery.IFilter[] +): api.StructuredQuery.IFilter { + return { + compositeFilter: { + op: op, + filters, + }, + }; +} + +export function orFilter( + op: api.StructuredQuery.CompositeFilter.Operator, + ...filters: api.StructuredQuery.IFilter[] +): api.StructuredQuery.IFilter { + return compositeFilter('OR', ...filters); +} + +export function andFilter( + op: api.StructuredQuery.CompositeFilter.Operator, + ...filters: api.StructuredQuery.IFilter[] +): api.StructuredQuery.IFilter { + return compositeFilter('AND', ...filters); +} + +function unaryFiltersQuery( + fieldPath: string, + equals: 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL', + ...fieldPathsAndEquals: string[] +): api.IStructuredQuery { + return { + where: unaryFilters(fieldPath, equals, ...fieldPathsAndEquals), + }; +} + +function unaryFilters( + fieldPath: string, + equals: 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL', + ...fieldPathsAndEquals: string[] +): api.StructuredQuery.IFilter { + const filters: api.StructuredQuery.IFilter[] = []; + + fieldPathsAndEquals.unshift(fieldPath, equals); + + for (let i = 0; i < fieldPathsAndEquals.length; i += 2) { + const fieldPath = fieldPathsAndEquals[i]; + const equals = fieldPathsAndEquals[i + 1]; + + expect(equals).to.be.oneOf([ + 'IS_NAN', + 'IS_NULL', + 'IS_NOT_NAN', + 'IS_NOT_NULL', + ]); + + filters.push({ + unaryFilter: { + field: { + fieldPath, + }, + op: equals as 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL', + }, + }); + } + + if (filters.length === 1) { + return { + unaryFilter: filters[0].unaryFilter, + }; + } else { + return { + compositeFilter: { + op: 'AND', + filters, + }, + }; + } +} + +export function orderBy( + fieldPath: string, + direction: api.StructuredQuery.Direction, + ...fieldPathAndOrderBys: Array +): api.IStructuredQuery { + const orderBy: api.StructuredQuery.IOrder[] = []; + + fieldPathAndOrderBys.unshift(fieldPath, direction); + + for (let i = 0; i < fieldPathAndOrderBys.length; i += 2) { + const fieldPath = fieldPathAndOrderBys[i] as string; + const direction = fieldPathAndOrderBys[ + i + 1 + ] as api.StructuredQuery.Direction; + orderBy.push({ + field: { + fieldPath, + }, + direction, + }); + } + + return {orderBy}; +} + +export function limit(n: number): api.IStructuredQuery { + return { + limit: { + value: n, + }, + }; +} + +function offset(n: number): api.IStructuredQuery { + return { + offset: n, + }; +} + +export function allDescendants(kindless = false): api.IStructuredQuery { + if (kindless) { + return {from: [{allDescendants: true}]}; + } + return {from: [{collectionId: 'collectionId', allDescendants: true}]}; +} + +export function select(...fields: string[]): api.IStructuredQuery { + const select: api.StructuredQuery.IProjection = { + fields: [], + }; + + for (const field of fields) { + select.fields!.push({fieldPath: field}); + } + + return {select}; +} + +export function startAt( + before: boolean, + ...values: Array +): api.IStructuredQuery { + const cursor: api.ICursor = { + values: [], + }; + + if (before) { + cursor.before = true; + } + + for (const value of values) { + if (typeof value === 'string') { + cursor.values!.push({ + stringValue: value, + }); + } else { + cursor.values!.push(value); + } + } + + return {startAt: cursor}; +} + +function endAt( + before: boolean, + ...values: Array +): api.IStructuredQuery { + const cursor: api.ICursor = { + values: [], + }; + + if (before) { + cursor.before = true; + } + + for (const value of values) { + if (typeof value === 'string') { + cursor.values!.push({ + stringValue: value, + }); + } else { + cursor.values!.push(value); + } + } + + return {endAt: cursor}; +} + +/** + * Returns the timestamp value for the provided readTimes, or the default + * readTime value used in tests if no values are provided. + */ +export function readTime( + seconds?: number, + nanos?: number, +): protobuf.ITimestamp { + if (seconds === undefined && nanos === undefined) { + return {seconds: '5', nanos: 6}; + } + return {seconds: String(seconds), nanos: nanos}; +} + +export function queryEqualsWithParent( + actual: api.IRunQueryRequest | undefined, + parent: string, + ...protoComponents: api.IStructuredQuery[] +): void { + expect(actual).to.not.be.undefined; + + if (parent !== '') { + parent = '/' + parent; + } + + const query: api.IRunQueryRequest = { + parent: DATABASE_ROOT + '/documents' + parent, + structuredQuery: {}, + }; + + for (const protoComponent of protoComponents) { + extend(true, query.structuredQuery, protoComponent); + } + + // We add the `from` selector here in order to avoid setting collectionId on + // kindless queries. + if (query.structuredQuery!.from === undefined) { + query.structuredQuery!.from = [ + { + collectionId: 'collectionId', + }, + ]; + } + + // 'extend' removes undefined fields in the request object. The backend + // ignores these fields, but we need to manually strip them before we compare + // the expected and the actual request. + actual = extend(true, {}, actual); + expect(actual).to.deep.eq(query); +} + +export function queryEquals( + actual: api.IRunQueryRequest | undefined, + ...protoComponents: api.IStructuredQuery[] +): void { + queryEqualsWithParent(actual, /* parent= */ '', ...protoComponents); +} + +function bundledQueryEquals( + actual: firestore.IBundledQuery | undefined, + limitType: firestore.BundledQuery.LimitType | undefined, + ...protoComponents: api.IStructuredQuery[] +) { + expect(actual).to.not.be.undefined; + + const query: firestore.IBundledQuery = { + parent: DATABASE_ROOT + '/documents', + structuredQuery: { + from: [ + { + collectionId: 'collectionId', + }, + ], + }, + limitType, + }; + + for (const protoComponent of protoComponents) { + extend(true, query.structuredQuery, protoComponent); + } + + // 'extend' removes undefined fields in the request object. The backend + // ignores these fields, but we need to manually strip them before we compare + // the expected and the actual request. + actual = extend(true, {}, actual); + expect(actual).to.deep.eq(query); +} + +export function result( + documentId: string, + setDone?: boolean, +): api.IRunQueryResponse { + if (setDone) { + return { + document: document(documentId), + readTime: {seconds: 5, nanos: 6}, + done: setDone, + }; + } else { + return {document: document(documentId), readTime: {seconds: 5, nanos: 6}}; + } +} + +export function heartbeat(count: number): api.IRunQueryResponse { + return { + document: null, + readTime: {seconds: 5, nanos: 6}, + skippedResults: count, + }; +} + +describe('query interface', () => { + let firestore: Firestore; + + beforeEach(async () => { + setTimeoutHandler(setImmediate); + firestore = await createInstance(); + }); + + afterEach(async () => { + await verifyInstance(firestore); + setTimeoutHandler(setTimeout); + }); + + it('has isEqual() method', () => { + const queryA = firestore.collection('collectionId'); + const queryB = firestore.collection('collectionId'); + + const queryEquals = (equals: Query[], notEquals: Query[]) => { + for (let i = 0; i < equals.length; ++i) { + for (const equal of equals) { + expect(equals[i].isEqual(equal)).to.be.true; + expect(equal.isEqual(equals[i])).to.be.true; + } + + for (const notEqual of notEquals) { + expect(equals[i].isEqual(notEqual)).to.be.false; + expect(notEqual.isEqual(equals[i])).to.be.false; + } + } + }; + + queryEquals( + [queryA.where('a', '==', '1'), queryB.where('a', '==', '1')], + [queryA.where('a', '=' as InvalidApiUsage, 1)], + ); + + queryEquals( + [ + queryA.where('a', '==', '1').where('b', '==', 2), + queryB.where('a', '==', '1').where('b', '==', 2), + ], + [], + ); + + queryEquals( + [ + queryA.orderBy('__name__'), + queryA.orderBy('__name__', 'asc'), + queryB.orderBy('__name__', 'ASC' as InvalidApiUsage), + queryB.orderBy(FieldPath.documentId()), + ], + [queryA.orderBy('foo'), queryB.orderBy(FieldPath.documentId(), 'desc')], + ); + + queryEquals( + [queryA.limit(0), queryB.limit(0).limit(0)], + [queryA, queryB.limit(10)], + ); + + queryEquals( + [queryA.offset(0), queryB.offset(0).offset(0)], + [queryA, queryB.offset(10)], + ); + + queryEquals( + [queryA.orderBy('foo').startAt('a'), queryB.orderBy('foo').startAt('a')], + [ + queryA.orderBy('foo').startAfter('a'), + queryB.orderBy('foo').endAt('a'), + queryA.orderBy('foo').endBefore('a'), + queryB.orderBy('foo').startAt('b'), + queryA.orderBy('bar').startAt('a'), + ], + ); + + queryEquals( + [ + queryA.orderBy('foo').startAfter('a'), + queryB.orderBy('foo').startAfter('a'), + ], + [ + queryA.orderBy('foo').startAfter('b'), + queryB.orderBy('bar').startAfter('a'), + ], + ); + + queryEquals( + [ + queryA.orderBy('foo').endBefore('a'), + queryB.orderBy('foo').endBefore('a'), + ], + [ + queryA.orderBy('foo').endBefore('b'), + queryB.orderBy('bar').endBefore('a'), + ], + ); + + queryEquals( + [queryA.orderBy('foo').endAt('a'), queryB.orderBy('foo').endAt('a')], + [queryA.orderBy('foo').endAt('b'), queryB.orderBy('bar').endAt('a')], + ); + + queryEquals( + [ + queryA.orderBy('foo').orderBy('__name__').startAt('b', 'c'), + queryB.orderBy('foo').orderBy('__name__').startAt('b', 'c'), + ], + [], + ); + }); + + it('accepts all variations', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + fieldFiltersQuery('foo', 'EQUAL', 'bar'), + orderBy('foo', 'ASCENDING'), + limit(10), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.where('foo', '==', 'bar'); + query = query.orderBy('foo'); + query = query.limit(10); + const results = await query.get(); + expect(results.query).to.equal(query); + expect(results.size).to.equal(0); + expect(results.empty).to.be.true; + }); + + it('supports empty gets', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request); + return stream({readTime: {seconds: 5, nanos: 6}}); + }, + }; + + firestore = await createInstance(overrides); + const query = firestore.collection('collectionId'); + const results = await query.get(); + expect(results.size).to.equal(0); + expect(results.empty).to.be.true; + expect(results.readTime.isEqual(new Timestamp(5, 6))).to.be.true; + }); + + it('retries on stream failure', async () => { + let attempts = 0; + const overrides: ApiOverride = { + runQuery: () => { + ++attempts; + throw new Error('Expected error'); + }, + }; + + firestore = await createInstance(overrides); + const query = firestore.collection('collectionId'); + await expect(query.get()).to.eventually.be.rejected; + expect(attempts).to.equal(5); + }); + + it('supports empty streams', done => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request); + return stream({readTime: {seconds: 5, nanos: 6}}); + }, + }; + + void createInstance(overrides).then(firestoreInstance => { + firestore = firestoreInstance; + const query = firestore.collection('collectionId'); + query + .stream() + .on('data', () => { + done(Error('Unexpected document')); + }) + .on('end', () => { + done(); + }); + }); + }); + + it('returns results', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request); + return stream(result('first'), result('second')); + }, + }; + + firestore = await createInstance(overrides); + const query = firestore.collection('collectionId'); + const results = await query.get(); + expect(results.size).to.equal(2); + expect(results.empty).to.be.false; + expect(results.readTime.isEqual(new Timestamp(5, 6))).to.be.true; + expect(results.docs[0].id).to.equal('first'); + expect(results.docs[1].id).to.equal('second'); + expect(results.docChanges()).to.have.length(2); + + let count = 0; + + results.forEach(doc => { + expect(doc instanceof DocumentSnapshot).to.be.true; + expect(doc.createTime.isEqual(new Timestamp(1, 2))).to.be.true; + expect(doc.updateTime.isEqual(new Timestamp(3, 4))).to.be.true; + expect(doc.readTime.isEqual(new Timestamp(5, 6))).to.be.true; + ++count; + }); + + expect(2).to.equal(count); + }); + + // Test Logical Termination on get() + it('successful return without ending the stream on get()', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request); + return streamWithoutEnd(result('first'), result('second', true)); + }, + }; + + let counter = 0; + firestore = await createInstance(overrides); + const query = firestore.collection('collectionId'); + const results = await query.get(); + expect(++counter).to.equal(1); + expect(results.size).to.equal(2); + expect(results.empty).to.be.false; + expect(results.readTime.isEqual(new Timestamp(5, 6))).to.be.true; + expect(results.docs[0].id).to.equal('first'); + expect(results.docs[1].id).to.equal('second'); + expect(results.docChanges()).to.have.length(2); + }); + + it('handles stream exception at initialization', async () => { + let attempts = 0; + const query = firestore.collection('collectionId'); + + query._queryUtil._stream = () => { + ++attempts; + throw new Error('Expected error'); + }; + + await expect(query.get()).to.eventually.be.rejectedWith('Expected error'); + expect(attempts).to.equal(1); + }); + + it('handles stream exception during initialization', async () => { + let attempts = 0; + + const overrides: ApiOverride = { + runQuery: () => { + ++attempts; + return stream(new Error('Expected error')); + }, + }; + + firestore = await createInstance(overrides); + await expect( + firestore.collection('collectionId').get(), + ).to.eventually.be.rejectedWith('Expected error'); + expect(attempts).to.equal(5); + }); + + it('handles stream exception after initialization (with get())', async () => { + const responses = [ + () => stream(result('first'), new Error('Expected error')), + () => stream(result('second')), + ]; + const overrides: ApiOverride = { + runQuery: () => responses.shift()!(), + }; + + firestore = await createInstance(overrides); + const snap = await firestore.collection('collectionId').get(); + expect(snap.size).to.equal(2); + expect(snap.docs[0].id).to.equal('first'); + expect(snap.docs[1].id).to.equal('second'); + }); + + it('handles stream exception after initialization and heartbeat', async () => { + const deadlineExceededErr = new GoogleError(); + deadlineExceededErr.code = Status.DEADLINE_EXCEEDED; + deadlineExceededErr.message = 'DEADLINE_EXCEEDED error message'; + + let attempts = 0; + + const overrides: ApiOverride = { + runQuery: () => { + ++attempts; + + // A heartbeat message will initialize the stream, but it is not + // a document, so it does not represent progress made on the stream. + return stream(heartbeat(1000), deadlineExceededErr); + }, + }; + + firestore = await createInstance(overrides); + await expect( + firestore.collection('collectionId').get(), + ).to.eventually.be.rejectedWith('DEADLINE_EXCEEDED error message'); + // The heartbeat initialized the stream before there was a stream + // exception, so we only expect a single attempt at streaming. + expect(attempts).to.equal(1); + }); + + async function handlesRetryableExceptionUntilProgressStops( + withHeartbeat: boolean, + ): Promise { + let attempts = 0; + + // count of stream initializations that are successful + // and make progress (a document is received before error) + const initializationsWithProgress = 10; + + // Receiving these error codes on a stream after the stream has received document data + // should result in the stream retrying indefinitely. + const retryableErrorCodes = [ + Status.DEADLINE_EXCEEDED, + Status.UNAVAILABLE, + Status.INTERNAL, + Status.UNAVAILABLE, + ]; + + const overrides: ApiOverride = { + runQuery: x => { + ++attempts; + + // Validate that runQuery is called with cursor of the lastReceivedDocument + // for all attempts except but the first. + if (attempts > 1) { + const docPath = + x?.structuredQuery?.startAt?.values?.[0].referenceValue || ''; + const docId = docPath.substring(docPath.lastIndexOf('/')); + expect(docId).to.equal( + `/id-${Math.min(initializationsWithProgress, attempts - 1)}`, + ); + expect(x?.structuredQuery?.orderBy?.length).to.equal(1); + expect(x?.structuredQuery?.orderBy?.[0].field?.fieldPath).to.equal( + '__name__', + ); + } + + const streamElements = []; + + // A heartbeat is a message that may be received on a stream while + // a query is running. If the test is configured `withHeartbeat = true` + // then the fake stream will include a heartbeat before the first + // document. This heartbeat message has the side effect of initializing + // the stream, but it does not represent progress of streaming the results. + // Testing with and without heartbeats allows us to evaluate different + // retry logic in the SDK. + if (withHeartbeat) { + streamElements.push(heartbeat(1000)); + } + + // For the first X initializations, the stream will make progress + // receiving documents in the result set. + // For the X+1 attempt, the stream will not make progress before + // the error. If a stream gets an error without progress, the + // retry policy will close the stream. + if (attempts <= initializationsWithProgress) { + streamElements.push(result(`id-${attempts}`)); + } + + // Create an error with one of the retryable error codes + const googleError = new GoogleError(); + googleError.code = + retryableErrorCodes[attempts % retryableErrorCodes.length]; + googleError.message = 'test error message'; + streamElements.push(googleError); + + return stream(...streamElements); + }, + }; + + firestore = await createInstance(overrides); + const query = firestore.collection('collectionId'); + query._queryUtil._hasRetryTimedOut = () => false; + await expect(query.get()).to.eventually.be.rejectedWith( + 'test error message', + ); + + // Assert that runQuery was retried the expected number + // of times based on the test configuration. + // + // If the test is running with heartbeat messages, then + // the test will always validate retry logic for an + // initialized stream. + // + // If the test is running without heartbeat messages, + // then the test will validate retry logic for both + // initialized and uninitialized streams. Specifically, + // the last retry will fail with an uninitialized stream. + const initilizationRetries = withHeartbeat ? 1 : 5; + expect(attempts).to.equal( + initializationsWithProgress + initilizationRetries, + ); + } + + it('handles retryable exception until progress stops with heartbeat', async () => { + await handlesRetryableExceptionUntilProgressStops(true); + }); + + it('handles retryable exception until progress stops without heartbeat', async () => { + await handlesRetryableExceptionUntilProgressStops(false); + }); + + it('handles retryable exception with progress until timeout', async () => { + let attempts = 0; + + const overrides: ApiOverride = { + runQuery: () => { + ++attempts; + + const streamElements = []; + streamElements.push(result(`id-${attempts}`)); + + // Create an error with a retryable error code + const googleError = new GoogleError(); + googleError.code = Status.DEADLINE_EXCEEDED; + googleError.message = 'test error message'; + streamElements.push(googleError); + + return stream(...streamElements); + }, + }; + + firestore = await createInstance(overrides); + const query = firestore.collection('collectionId'); + // Fake our timeout check to fail after 10 retry attempts + query._queryUtil._hasRetryTimedOut = (methodName, startTime) => { + expect(methodName).to.equal('runQuery'); + expect(startTime).to.be.lessThanOrEqual(Date.now()); + return attempts >= 10; + }; + + await expect(query.get()).to.eventually.be.rejectedWith( + 'test error message', + ); + expect(attempts).to.equal(10); + }); + + it('handles non-retryable after recieving data (with get())', async () => { + let attempts = 0; + + const overrides: ApiOverride = { + runQuery: () => { + ++attempts; + + const streamElements = []; + streamElements.push(result(`id-${attempts}`)); + + // Create an error with one of the retryable error codes + const googleError = new GoogleError(); + googleError.code = Status.UNKNOWN; + googleError.message = 'test error message'; + streamElements.push(googleError); + + return stream(...streamElements); + }, + }; + + firestore = await createInstance(overrides); + await expect( + firestore.collection('collectionId').get(), + ).to.eventually.be.rejectedWith('test error message'); + expect(attempts).to.equal(1); + }); + + it('handles stream exception after initialization (with stream())', done => { + const responses = [ + () => stream(result('first'), new Error('Expected error')), + () => stream(result('second')), + ]; + const overrides: ApiOverride = { + runQuery: () => responses.shift()!(), + }; + + void createInstance(overrides).then(firestoreInstance => { + firestore = firestoreInstance; + const result = firestore.collection('collectionId').stream(); + + let resultCount = 0; + result.on('data', doc => { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++resultCount; + }); + result.on('end', () => { + expect(resultCount).to.equal(2); + done(); + }); + }); + }); + + it('streams results', done => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request); + return stream(result('first'), result('second')); + }, + }; + + void createInstance(overrides).then(firestoreInstance => { + firestore = firestoreInstance; + const query = firestore.collection('collectionId'); + let received = 0; + + query + .stream() + .on('data', doc => { + expect(doc).to.be.an.instanceOf(DocumentSnapshot); + ++received; + }) + .on('end', () => { + expect(received).to.equal(2); + done(); + }); + }); + }); + + // Test Logical Termination on stream() + it('successful return without ending the stream on stream()', done => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request); + return streamWithoutEnd(result('first'), result('second', true)); + }, + }; + + let endCounter = 0; + void createInstance(overrides).then(firestore => { + const query = firestore.collection('collectionId'); + let received = 0; + + query + .stream() + .on('data', doc => { + expect(doc).to.be.an.instanceOf(DocumentSnapshot); + ++received; + }) + .on('end', () => { + expect(received).to.equal(2); + ++endCounter; + setImmediate(() => { + expect(endCounter).to.equal(1); + done(); + }); + }); + }); + }); + + it('for Query.withConverter()', async () => { + const doc = document('documentId', 'author', 'author', 'title', 'post'); + const overrides: ApiOverride = { + commit: request => { + const expectedRequest = set({ + document: doc, + }); + requestEquals(request, expectedRequest); + return response(writeResult(1)); + }, + runQuery: request => { + queryEquals(request, fieldFiltersQuery('title', 'EQUAL', 'post')); + return stream({document: doc, readTime: {seconds: 5, nanos: 6}}); + }, + }; + + return createInstance(overrides).then(async firestoreInstance => { + firestore = firestoreInstance; + await firestore + .collection('collectionId') + .doc('documentId') + .set({title: 'post', author: 'author'}); + const posts = await firestore + .collection('collectionId') + .where('title', '==', 'post') + .withConverter(postConverter) + .get(); + expect(posts.size).to.equal(1); + expect(posts.docs[0].data().toString()).to.equal('post, by author'); + }); + }); + + it('propagates withConverter() through QueryOptions', async () => { + const doc = document('documentId', 'author', 'author', 'title', 'post'); + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, fieldFiltersQuery('title', 'EQUAL', 'post')); + return stream({document: doc, readTime: {seconds: 5, nanos: 6}}); + }, + }; + + return createInstance(overrides).then(async firestoreInstance => { + firestore = firestoreInstance; + const coll = firestore + .collection('collectionId') + .withConverter(postConverter); + + // Verify that the converter is carried through. + const posts = await coll.where('title', '==', 'post').get(); + expect(posts.size).to.equal(1); + expect(posts.docs[0].data().toString()).to.equal('post, by author'); + }); + }); + + it('withConverter(null) applies the default converter', async () => { + const doc = document('documentId', 'author', 'author', 'title', 'post'); + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, fieldFiltersQuery('title', 'EQUAL', 'post')); + return stream({document: doc, readTime: {seconds: 5, nanos: 6}}); + }, + }; + + return createInstance(overrides).then(async firestoreInstance => { + firestore = firestoreInstance; + const coll = await firestore + .collection('collectionId') + .withConverter(postConverter) + .withConverter(null); + + const posts = await coll.where('title', '==', 'post').get(); + expect(posts.size).to.equal(1); + expect(posts.docs[0].data()).to.not.be.instanceOf(Post); + }); + }); + + it('supports OR query with cursor', () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + where( + compositeFilter( + 'OR', + fieldFilter('a', 'GREATER_THAN', {integerValue: 10}), + unaryFilters('b', 'IS_NOT_NULL'), + ), + ), + limit(3), + orderBy('a', 'ASCENDING'), + startAt(true, {integerValue: 1}), + ); + return emptyQueryStream(); + }, + }; + + return createInstance(overrides).then(async firestoreInstance => { + firestore = firestoreInstance; + let query: Query = firestore.collection('collectionId'); + query = query + .where( + Filter.or(Filter.where('a', '>', 10), Filter.where('b', '!=', null)), + ) + .orderBy('a') + .startAt(1) + .limit(3); + await query.get(); + }); + }); +}); + +describe('where() interface', () => { + let firestore: Firestore; + + beforeEach(async () => { + firestore = await createInstance(); + }); + + afterEach(() => verifyInstance(firestore)); + + it('generates proto', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, fieldFiltersQuery('foo', 'EQUAL', 'bar')); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.where('foo', '==', 'bar'); + await query.get(); + }); + + it('concatenates all accepted filters', async () => { + const arrValue: api.IValue = { + arrayValue: { + values: [ + { + stringValue: 'barArray', + }, + ], + }, + }; + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + fieldFiltersQuery( + 'fooSmaller', + 'LESS_THAN', + 'barSmaller', + 'fooSmallerOrEquals', + 'LESS_THAN_OR_EQUAL', + 'barSmallerOrEquals', + 'fooEquals', + 'EQUAL', + 'barEquals', + 'fooEqualsLong', + 'EQUAL', + 'barEqualsLong', + 'fooGreaterOrEquals', + 'GREATER_THAN_OR_EQUAL', + 'barGreaterOrEquals', + 'fooGreater', + 'GREATER_THAN', + 'barGreater', + 'fooContains', + 'ARRAY_CONTAINS', + 'barContains', + 'fooIn', + 'IN', + arrValue, + 'fooContainsAny', + 'ARRAY_CONTAINS_ANY', + arrValue, + 'fooNotEqual', + 'NOT_EQUAL', + 'barEqualsLong', + 'fooNotIn', + 'NOT_IN', + arrValue, + ), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.where('fooSmaller', '<', 'barSmaller'); + query = query.where('fooSmallerOrEquals', '<=', 'barSmallerOrEquals'); + query = query.where('fooEquals', '=' as InvalidApiUsage, 'barEquals'); + query = query.where('fooEqualsLong', '==', 'barEqualsLong'); + query = query.where('fooGreaterOrEquals', '>=', 'barGreaterOrEquals'); + query = query.where('fooGreater', '>', 'barGreater'); + query = query.where('fooContains', 'array-contains', 'barContains'); + query = query.where('fooIn', 'in', ['barArray']); + query = query.where('fooContainsAny', 'array-contains-any', ['barArray']); + query = query.where('fooNotEqual', '!=', 'barEqualsLong'); + query = query.where('fooNotIn', 'not-in', ['barArray']); + await query.get(); + }); + + it('accepts object', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + fieldFiltersQuery('foo', 'EQUAL', { + mapValue: { + fields: { + foo: {stringValue: 'bar'}, + }, + }, + }), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.where('foo', '==', {foo: 'bar'}); + await query.get(); + }); + + it('supports field path objects for field paths', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + fieldFiltersQuery( + 'foo.bar', + 'EQUAL', + 'foobar', + 'bar.foo', + 'EQUAL', + 'foobar', + ), + ); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.where('foo.bar', '==', 'foobar'); + query = query.where(new FieldPath('bar', 'foo'), '==', 'foobar'); + await query.get(); + }); + + it('supports strings for FieldPath.documentId()', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + fieldFiltersQuery('__name__', 'EQUAL', { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/foo', + }), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.where(FieldPath.documentId(), '==', 'foo'); + await query.get(); + }); + + it('supports reference array for IN queries', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + fieldFiltersQuery('__name__', 'IN', { + arrayValue: { + values: [ + { + referenceValue: `projects/${PROJECT_ID}/databases/(default)/documents/collectionId/foo`, + }, + { + referenceValue: `projects/${PROJECT_ID}/databases/(default)/documents/collectionId/bar`, + }, + ], + }, + }), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const collection = firestore.collection('collectionId'); + const query = collection.where(FieldPath.documentId(), 'in', [ + 'foo', + collection.doc('bar'), + ]); + await query.get(); + }); + + it('Fields of IN queries are not used in implicit order by', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + fieldFiltersQuery('foo', 'IN', { + arrayValue: { + values: [ + { + stringValue: 'bar', + }, + ], + }, + }), + orderBy('__name__', 'ASCENDING'), + startAt(true, { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc1', + }), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const collection = firestore.collection('collectionId'); + const query = collection + .where('foo', 'in', ['bar']) + .startAt(await snapshot('collectionId/doc1', {})); + await query.get(); + }); + + it('validates references for in/not-in queries', () => { + const query = firestore.collection('collectionId'); + + expect(() => { + query.where(FieldPath.documentId(), 'in', ['foo', 42]); + }).to.throw( + 'The corresponding value for FieldPath.documentId() must be a string or a DocumentReference, but was "42".', + ); + + expect(() => { + query.where(FieldPath.documentId(), 'in', 42); + }).to.throw( + "Invalid Query. A non-empty array is required for 'in' filters.", + ); + + expect(() => { + query.where(FieldPath.documentId(), 'in', []); + }).to.throw( + "Invalid Query. A non-empty array is required for 'in' filters.", + ); + + expect(() => { + query.where(FieldPath.documentId(), 'not-in', ['foo', 42]); + }).to.throw( + 'The corresponding value for FieldPath.documentId() must be a string or a DocumentReference, but was "42".', + ); + + expect(() => { + query.where(FieldPath.documentId(), 'not-in', 42); + }).to.throw( + "Invalid Query. A non-empty array is required for 'not-in' filters.", + ); + + expect(() => { + query.where(FieldPath.documentId(), 'not-in', []); + }).to.throw( + "Invalid Query. A non-empty array is required for 'not-in' filters.", + ); + }); + + it('validates query operator for FieldPath.document()', () => { + const query = firestore.collection('collectionId'); + + expect(() => { + query.where(FieldPath.documentId(), 'array-contains', query.doc()); + }).to.throw( + "Invalid Query. You can't perform 'array-contains' queries on FieldPath.documentId().", + ); + + expect(() => { + query.where(FieldPath.documentId(), 'array-contains-any', query.doc()); + }).to.throw( + "Invalid Query. You can't perform 'array-contains-any' queries on FieldPath.documentId().", + ); + }); + + it('rejects custom objects for field paths', async () => { + expect(() => { + let query: Query = firestore.collection('collectionId'); + query = query.where({} as InvalidApiUsage, '==', 'bar'); + void query.get(); + }).to.throw( + 'Value for argument "fieldPath" is not a valid field path. Paths can only be specified as strings or via a FieldPath object.', + ); + + class FieldPath {} + expect(() => { + let query: Query = firestore.collection('collectionId'); + query = query.where(new FieldPath() as InvalidApiUsage, '==', 'bar'); + void query.get(); + }).to.throw( + 'Detected an object of type "FieldPath" that doesn\'t match the expected instance.', + ); + }); + + it('rejects field paths as value', async () => { + expect(() => { + let query: Query = firestore.collection('collectionId'); + query = query.where('foo', '==', new FieldPath('bar')); + void query.get(); + }).to.throw( + 'Value for argument "value" is not a valid query constraint. Cannot use object of type "FieldPath" as a Firestore value.', + ); + }); + + it('rejects field delete as value', async () => { + expect(() => { + let query: Query = firestore.collection('collectionId'); + query = query.where('foo', '==', FieldValue.delete()); + void query.get(); + }).to.throw( + 'FieldValue.delete() must appear at the top-level and can only be used in update() or set() with {merge:true}.', + ); + }); + + it('rejects custom classes as value', () => { + class Foo {} + class FieldPath {} + class FieldValue {} + class GeoPoint {} + class DocumentReference {} + + const query = firestore.collection('collectionId'); + + expect(() => { + void query.where('foo', '==', new Foo()).get(); + }).to.throw( + 'Value for argument "value" is not a valid Firestore document. Couldn\'t serialize object of type "Foo". Firestore doesn\'t support JavaScript objects with custom prototypes (i.e. objects that were created via the "new" operator).', + ); + + expect(() => { + void query.where('foo', '==', new FieldPath()).get(); + }).to.throw( + 'Detected an object of type "FieldPath" that doesn\'t match the expected instance.', + ); + + expect(() => { + void query.where('foo', '==', new FieldValue()).get(); + }).to.throw( + 'Detected an object of type "FieldValue" that doesn\'t match the expected instance.', + ); + + expect(() => { + void query.where('foo', '==', new DocumentReference()).get(); + }).to.throw( + 'Detected an object of type "DocumentReference" that doesn\'t match the expected instance.', + ); + + expect(() => { + void query.where('foo', '==', new GeoPoint()).get(); + }).to.throw( + 'Detected an object of type "GeoPoint" that doesn\'t match the expected instance.', + ); + }); + + it('supports unary filters', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + unaryFiltersQuery('foo', 'IS_NAN', 'bar', 'IS_NULL'), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.where('foo', '==', NaN); + query = query.where('bar', '==', null); + await query.get(); + }); + + it('supports unary filters', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + unaryFiltersQuery('foo', 'IS_NOT_NAN', 'bar', 'IS_NOT_NULL'), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.where('foo', '!=', NaN); + query = query.where('bar', '!=', null); + await query.get(); + }); + + it('rejects invalid NaN filter', () => { + expect(() => { + let query: Query = firestore.collection('collectionId'); + query = query.where('foo', '>', NaN); + return query.get(); + }).to.throw( + "Invalid query. You can only perform '==' and '!=' comparisons on NaN.", + ); + }); + + it('rejects invalid Null filter', () => { + expect(() => { + let query: Query = firestore.collection('collectionId'); + query = query.where('foo', '>', null); + return query.get(); + }).to.throw( + "Invalid query. You can only perform '==' and '!=' comparisons on Null.", + ); + }); + + it('verifies field path', () => { + let query: Query = firestore.collection('collectionId'); + expect(() => { + query = query.where('foo.', '==', 'foobar'); + }).to.throw( + 'Value for argument "fieldPath" is not a valid field path. Paths must not start or end with ".".', + ); + }); + + it('verifies operator', () => { + let query: Query = firestore.collection('collectionId'); + expect(() => { + query = query.where('foo', '@' as InvalidApiUsage, 'foobar'); + }).to.throw( + 'Value for argument "opStr" is invalid. Acceptable values are: <, <=, ==, !=, >, >=, array-contains, in, not-in, array-contains-any', + ); + }); + + it('supports composite filters - outer OR', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + where( + compositeFilter( + 'OR', + fieldFilter('a', 'EQUAL', {integerValue: 10}), + compositeFilter( + 'AND', + fieldFilter('b', 'EQUAL', {integerValue: 20}), + fieldFilter('c', 'EQUAL', {integerValue: 30}), + compositeFilter( + 'OR', + fieldFilter('d', 'EQUAL', {integerValue: 40}), + fieldFilter('e', 'GREATER_THAN', {integerValue: 50}), + ), + unaryFilters('f', 'IS_NAN'), + ), + ), + ), + ); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.where( + Filter.or( + Filter.where('a', '==', 10), + Filter.and( + Filter.where('b', '==', 20), + Filter.where('c', '==', 30), + Filter.or(Filter.where('d', '==', 40), Filter.where('e', '>', 50)), + Filter.or(Filter.where('f', '==', NaN)), + Filter.and(Filter.or()), + ), + ), + ); + await query.get(); + }); + + it('supports composite filters - outer AND', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + where( + compositeFilter( + 'AND', + fieldFilter('a', 'EQUAL', {integerValue: 10}), + compositeFilter( + 'OR', + fieldFilter('b', 'EQUAL', {integerValue: 20}), + fieldFilter('c', 'EQUAL', {integerValue: 30}), + compositeFilter( + 'AND', + fieldFilter('d', 'EQUAL', {integerValue: 40}), + fieldFilter('e', 'GREATER_THAN', {integerValue: 50}), + ), + unaryFilters('f', 'IS_NAN'), + ), + ), + ), + ); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.where( + Filter.and( + Filter.where('a', '==', 10), + Filter.or( + Filter.where('b', '==', 20), + Filter.where('c', '==', 30), + Filter.and(Filter.where('d', '==', 40), Filter.where('e', '>', 50)), + Filter.and(Filter.where('f', '==', NaN)), + Filter.or(Filter.and()), + ), + ), + ); + await query.get(); + }); + + it('supports implicit AND filters', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + where( + compositeFilter( + 'AND', + fieldFilter('a', 'EQUAL', {integerValue: 10}), + fieldFilter('b', 'EQUAL', {integerValue: 20}), + fieldFilter('c', 'EQUAL', {integerValue: 30}), + fieldFilter('d', 'EQUAL', {integerValue: 40}), + fieldFilter('e', 'GREATER_THAN', {integerValue: 50}), + unaryFilters('f', 'IS_NAN'), + ), + ), + ); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query + .where('a', '==', 10) + .where('b', '==', 20) + .where('c', '==', 30) + .where('d', '==', 40) + .where('e', '>', 50) + .where('f', '==', NaN); + await query.get(); + }); + + it('supports single filter composite filters', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + where(fieldFilter('a', 'GREATER_THAN', {integerValue: 10})), + ); + return emptyQueryStream(); + }, + }; + + const filters = [ + Filter.and(Filter.where('a', '>', 10)), + Filter.or(Filter.where('a', '>', 10)), + Filter.or(Filter.and(Filter.or(Filter.and(Filter.where('a', '>', 10))))), + ]; + + for (const filter of filters) { + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.where(filter); + await query.get(); + } + }); +}); + +describe('orderBy() interface', () => { + let firestore: Firestore; + + beforeEach(async () => { + firestore = await createInstance(); + }); + + afterEach(() => verifyInstance(firestore)); + + it('accepts empty string', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, orderBy('foo', 'ASCENDING')); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo'); + await query.get(); + }); + + it('accepts asc', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, orderBy('foo', 'ASCENDING')); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo', 'asc'); + await query.get(); + }); + + it('accepts desc', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, orderBy('foo', 'DESCENDING')); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo', 'desc'); + await query.get(); + }); + + it('verifies order', () => { + let query: Query = firestore.collection('collectionId'); + expect(() => { + query = query.orderBy('foo', 'foo' as InvalidApiUsage); + }).to.throw( + 'Value for argument "directionStr" is invalid. Acceptable values are: asc, desc', + ); + }); + + it('accepts field path', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('foo.bar', 'ASCENDING', 'bar.foo', 'ASCENDING'), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo.bar'); + query = query.orderBy(new FieldPath('bar', 'foo')); + await query.get(); + }); + + it('verifies field path', () => { + let query: Query = firestore.collection('collectionId'); + expect(() => { + query = query.orderBy('foo.'); + }).to.throw( + 'Value for argument "fieldPath" is not a valid field path. Paths must not start or end with ".".', + ); + }); + + it('rejects call after cursor', async () => { + let query: Query = firestore.collection('collectionId'); + + const doc = await snapshot('collectionId/doc', {foo: 'bar'}); + expect(() => { + query = query.orderBy('foo').startAt('foo').orderBy('foo'); + }).to.throw( + 'Cannot specify an orderBy() constraint after calling startAt(), startAfter(), endBefore() or endAt().', + ); + + expect(() => { + query = query + .where('foo', '>', 'bar') + .startAt(doc) + .where('foo', '>', 'bar'); + }).to.throw( + 'Cannot specify a where() filter after calling startAt(), startAfter(), endBefore() or endAt().', + ); + + expect(() => { + query = query.orderBy('foo').endAt('foo').orderBy('foo'); + }).to.throw( + 'Cannot specify an orderBy() constraint after calling startAt(), startAfter(), endBefore() or endAt().', + ); + + expect(() => { + query = query + .where('foo', '>', 'bar') + .endAt(doc) + .where('foo', '>', 'bar'); + }).to.throw( + 'Cannot specify a where() filter after calling startAt(), startAfter(), endBefore() or endAt().', + ); + }); + + it('concatenates orders', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy( + 'foo', + 'ASCENDING', + 'bar', + 'DESCENDING', + 'foobar', + 'ASCENDING', + ), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query + .orderBy('foo', 'asc') + .orderBy('bar', 'desc') + .orderBy('foobar'); + await query.get(); + }); +}); + +describe('limit() interface', () => { + let firestore: Firestore; + + beforeEach(async () => { + firestore = await createInstance(); + }); + + afterEach(() => verifyInstance(firestore)); + + it('generates proto', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, limit(10)); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.limit(10); + await query.get(); + }); + + it('expects number', () => { + const query = firestore.collection('collectionId'); + expect(() => query.limit(Infinity)).to.throw( + 'Value for argument "limit" is not a valid integer.', + ); + }); + + it('uses latest limit', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, limit(3)); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.limit(1).limit(2).limit(3); + await query.get(); + }); +}); + +describe('limitToLast() interface', () => { + let firestore: Firestore; + + beforeEach(async () => { + firestore = await createInstance(); + }); + + afterEach(() => verifyInstance(firestore)); + + it('reverses order constraints', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, orderBy('foo', 'DESCENDING'), limit(10)); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').limitToLast(10); + await query.get(); + }); + + it('reverses cursors', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('foo', 'DESCENDING'), + startAt(true, 'end'), + endAt(false, 'start'), + limit(10), + ); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').startAt('start').endAt('end').limitToLast(10); + await query.get(); + }); + + it('reverses results', () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, orderBy('foo', 'DESCENDING'), limit(2)); + return stream(result('second'), result('first')); + }, + }; + + return createInstance(overrides).then(async firestoreInstance => { + firestore = firestoreInstance; + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').limitToLast(2); + const result = await query.get(); + expect(result.docs[0].id).to.equal('first'); + expect(result.docs[1].id).to.equal('second'); + }); + }); + + it('expects number', () => { + const query = firestore.collection('collectionId'); + expect(() => query.limitToLast(Infinity)).to.throw( + 'Value for argument "limitToLast" is not a valid integer.', + ); + }); + + it('requires at least one ordering constraints', () => { + const query = firestore.collection('collectionId'); + const result = query.limitToLast(1).get(); + return expect(result).to.eventually.be.rejectedWith( + 'limitToLast() queries require specifying at least one orderBy() clause.', + ); + }); + + it('rejects Query.stream()', () => { + const query = firestore.collection('collectionId'); + expect(() => query.limitToLast(1).stream()).to.throw( + 'Query results for queries that include limitToLast() constraints cannot be streamed. Use Query.get() instead.', + ); + }); + + it('uses latest limitToLast', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, orderBy('foo', 'DESCENDING'), limit(3)); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').limitToLast(1).limitToLast(2).limitToLast(3); + await query.get(); + }); + + it('converts to bundled query without order reversing', async () => { + const firestore = await createInstance(); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').limitToLast(10); + const bundledQuery = query._toBundledQuery(); + bundledQueryEquals( + bundledQuery, + 'LAST', + orderBy('foo', 'ASCENDING'), + limit(10), + ); + }); + + it('converts to bundled query without cursor flipping', async () => { + const firestore = await createInstance(); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').startAt('start').endAt('end').limitToLast(10); + const bundledQuery = query._toBundledQuery(); + bundledQueryEquals( + bundledQuery, + 'LAST', + orderBy('foo', 'ASCENDING'), + limit(10), + startAt(true, 'start'), + endAt(false, 'end'), + ); + }); + + it('converts to bundled query without order reversing', async () => { + const firestore = await createInstance(); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').limitToLast(10); + const bundledQuery = query._toBundledQuery(); + bundledQueryEquals( + bundledQuery, + 'LAST', + orderBy('foo', 'ASCENDING'), + limit(10), + ); + }); + + it('converts to bundled query without cursor flipping', async () => { + const firestore = await createInstance(); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').startAt('start').endAt('end').limitToLast(10); + const bundledQuery = query._toBundledQuery(); + bundledQueryEquals( + bundledQuery, + 'LAST', + orderBy('foo', 'ASCENDING'), + limit(10), + startAt(true, 'start'), + endAt(false, 'end'), + ); + }); +}); + +describe('offset() interface', () => { + let firestore: Firestore; + + beforeEach(async () => { + firestore = await createInstance(); + }); + + afterEach(() => verifyInstance(firestore)); + + it('generates proto', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, offset(10)); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.offset(10); + await query.get(); + }); + + it('expects number', () => { + const query = firestore.collection('collectionId'); + expect(() => query.offset(Infinity)).to.throw( + 'Value for argument "offset" is not a valid integer.', + ); + }); + + it('uses latest offset', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, offset(3)); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.offset(1).offset(2).offset(3); + await query.get(); + }); +}); + +describe('select() interface', () => { + let firestore: Firestore; + + beforeEach(async () => { + firestore = await createInstance(); + }); + + afterEach(() => verifyInstance(firestore)); + + it('generates proto', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, select('a', 'b.c')); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const collection = firestore.collection('collectionId'); + const query = collection.select('a', new FieldPath('b', 'c')); + + await query.get(); + await collection.select('a', 'b.c').get(); + }); + + it('validates field path', () => { + const query = firestore.collection('collectionId'); + expect(() => query.select(1 as InvalidApiUsage)).to.throw( + 'Element at index 0 is not a valid field path. Paths can only be specified as strings or via a FieldPath object.', + ); + + expect(() => query.select('.')).to.throw( + 'Element at index 0 is not a valid field path. Paths must not start or end with ".".', + ); + }); + + it('uses latest field mask', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, select('bar')); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.select('foo').select('bar'); + await query.get(); + }); + + it('implicitly adds FieldPath.documentId()', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, select('__name__')); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.select(); + await query.get(); + }); +}); + +describe('startAt() interface', () => { + let firestore: Firestore; + + beforeEach(async () => { + firestore = await createInstance(); + }); + + afterEach(() => verifyInstance(firestore)); + + it('accepts fields', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('foo', 'ASCENDING', 'bar', 'ASCENDING'), + startAt(true, 'foo', 'bar'), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').orderBy('bar').startAt('foo', 'bar'); + await query.get(); + }); + + it('accepts FieldPath.documentId()', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('__name__', 'ASCENDING'), + startAt(true, { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', {foo: 'bar'}); + const query = firestore.collection('collectionId'); + + await Promise.all([ + query.orderBy(FieldPath.documentId()).startAt(doc.id).get(), + query.orderBy(FieldPath.documentId()).startAt(doc.ref).get(), + ]); + }); + + it('validates value for FieldPath.documentId()', () => { + const query = firestore.collection('coll/doc/coll'); + + expect(() => { + query.orderBy(FieldPath.documentId()).startAt(42); + }).to.throw( + 'The corresponding value for FieldPath.documentId() must be a string or a DocumentReference, but was "42".', + ); + + expect(() => { + query + .orderBy(FieldPath.documentId()) + .startAt(firestore.doc('coll/doc/other/doc')); + }).to.throw( + '"coll/doc/other/doc" is not part of the query result set and cannot be used as a query boundary.', + ); + + expect(() => { + query + .orderBy(FieldPath.documentId()) + .startAt(firestore.doc('coll/doc/coll_suffix/doc')); + }).to.throw( + '"coll/doc/coll_suffix/doc" is not part of the query result set and cannot be used as a query boundary.', + ); + + expect(() => { + query.orderBy(FieldPath.documentId()).startAt(firestore.doc('coll/doc')); + }).to.throw( + '"coll/doc" is not part of the query result set and cannot be used as a query boundary.', + ); + + expect(() => { + query + .orderBy(FieldPath.documentId()) + .startAt(firestore.doc('coll/doc/coll/doc/coll/doc')); + }).to.throw( + 'Only a direct child can be used as a query boundary. Found: "coll/doc/coll/doc/coll/doc".', + ); + + // Validate that we can't pass a reference to a collection. + expect(() => { + query.orderBy(FieldPath.documentId()).startAt('doc/coll'); + }).to.throw( + 'When querying a collection and ordering by FieldPath.documentId(), ' + + 'the corresponding value must be a plain document ID, but ' + + "'doc/coll' contains a slash.", + ); + }); + + it('requires at least one value', () => { + const query = firestore.collection('coll/doc/coll'); + + expect(() => { + query.startAt(); + }).to.throw('Function "Query.startAt()" requires at least 1 argument.'); + }); + + it('can specify document snapshot', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('__name__', 'ASCENDING'), + startAt(true, { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', {}); + const query = firestore.collection('collectionId').startAt(doc); + await query.get(); + }); + + it("doesn't append documentId() twice", async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('__name__', 'ASCENDING'), + startAt(true, { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', {}); + const query = firestore + .collection('collectionId') + .orderBy(FieldPath.documentId()) + .startAt(doc); + await query.get(); + }); + + it('appends orderBy for DocumentReference cursors', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('__name__', 'ASCENDING'), + startAt(true, { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', {foo: 'bar'}); + let query: Query = firestore.collection('collectionId'); + query = query.startAt(doc); + await query.get(); + }); + + it('can extract implicit direction for document snapshot', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('foo', 'ASCENDING', '__name__', 'ASCENDING'), + startAt(true, 'bar', { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', {foo: 'bar'}); + let query: Query = firestore.collection('collectionId').orderBy('foo'); + query = query.startAt(doc); + await query.get(); + }); + + it('can extract explicit direction for document snapshot', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('foo', 'DESCENDING', '__name__', 'DESCENDING'), + startAt(true, 'bar', { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', {foo: 'bar'}); + let query: Query = firestore + .collection('collectionId') + .orderBy('foo', 'desc'); + query = query.startAt(doc); + await query.get(); + }); + + it('can specify document snapshot with inequality filter', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('c', 'ASCENDING', '__name__', 'ASCENDING'), + startAt(true, 'c', { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }), + fieldFiltersQuery( + 'a', + 'EQUAL', + 'a', + 'b', + 'ARRAY_CONTAINS', + 'b', + 'c', + 'GREATER_THAN_OR_EQUAL', + 'c', + 'd', + 'EQUAL', + 'd', + ), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', {c: 'c'}); + const query = firestore + .collection('collectionId') + .where('a', '==', 'a') + .where('b', 'array-contains', 'b') + .where('c', '>=', 'c') + .where('d', '==', 'd') + .startAt(doc); + await query.get(); + }); + + it('ignores equality filter with document snapshot cursor', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('__name__', 'ASCENDING'), + startAt(true, { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }), + fieldFiltersQuery('foo', 'EQUAL', 'bar'), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', {foo: 'bar'}); + const query = firestore + .collection('collectionId') + .where('foo', '==', 'bar') + .startAt(doc); + await query.get(); + }); + + describe('inequality fields are implicitly ordered lexicographically for cursors', () => { + it('upper and lower case characters', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy( + 'A', + 'ASCENDING', + 'a', + 'ASCENDING', + 'aa', + 'ASCENDING', + 'b', + 'ASCENDING', + '__name__', + 'ASCENDING', + ), + startAt(true, 'A', 'a', 'aa', 'b', { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }), + fieldFiltersQuery( + 'a', + 'LESS_THAN', + 'value', + 'a', + 'GREATER_THAN_OR_EQUAL', + 'value', + 'aa', + 'GREATER_THAN', + 'value', + 'b', + 'GREATER_THAN', + 'value', + 'A', + 'GREATER_THAN', + 'value', + ), + ); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', { + a: 'a', + aa: 'aa', + b: 'b', + A: 'A', + }); + const query = firestore + .collection('collectionId') + .where('a', '<', 'value') + .where('a', '>=', 'value') + .where('aa', '>', 'value') + .where('b', '>', 'value') + .where('A', '>', 'value') + .startAt(doc); + await query.get(); + }); + + it('characters and numbers', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy( + '`1`', + 'ASCENDING', + '`19`', + 'ASCENDING', + '`2`', + 'ASCENDING', + 'a', + 'ASCENDING', + '__name__', + 'ASCENDING', + ), + startAt(true, '1', '19', '2', 'a', { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }), + fieldFiltersQuery( + 'a', + 'LESS_THAN', + 'value', + '`1`', + 'GREATER_THAN', + 'value', + '`19`', + 'GREATER_THAN', + 'value', + '`2`', + 'GREATER_THAN', + 'value', + ), + ); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', { + a: 'a', + 1: '1', + 19: '19', + 2: '2', + }); + const query = firestore + .collection('collectionId') + .where('a', '<', 'value') + .where('1', '>', 'value') + .where('19', '>', 'value') + .where('2', '>', 'value') + .startAt(doc); + await query.get(); + }); + + it('nested fields', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy( + 'a', + 'ASCENDING', + 'a.a', + 'ASCENDING', + 'aa', + 'ASCENDING', + '__name__', + 'ASCENDING', + ), + startAt( + true, + { + mapValue: { + fields: { + a: { + stringValue: 'a.a', + }, + }, + }, + }, + 'a.a', + 'aa', + { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }, + ), + fieldFiltersQuery( + 'a', + 'LESS_THAN', + 'value', + 'a.a', + 'GREATER_THAN', + 'value', + 'aa', + 'GREATER_THAN', + 'value', + ), + ); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', {a: {a: 'a.a'}, aa: 'aa'}); + const query = firestore + .collection('collectionId') + .where('a', '<', 'value') + .where('a.a', '>', 'value') + .where('aa', '>', 'value') + .startAt(doc); + await query.get(); + }); + + it('special characters', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy( + '_a', + 'ASCENDING', + 'a', + 'ASCENDING', + 'a.a', + 'ASCENDING', + '__name__', + 'ASCENDING', + ), + startAt( + true, + '_a', + { + mapValue: { + fields: { + a: { + stringValue: 'a.a', + }, + }, + }, + }, + 'a.a', + { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }, + ), + fieldFiltersQuery( + 'a', + 'LESS_THAN', + 'a', + '_a', + 'GREATER_THAN', + '_a', + 'a.a', + 'GREATER_THAN', + 'a.a', + ), + ); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', {a: {a: 'a.a'}, _a: '_a'}); + const query = firestore + .collection('collectionId') + .where('a', '<', 'a') + .where('_a', '>', '_a') + .where('a.a', '>', 'a.a') + .startAt(doc); + await query.get(); + }); + + it('field name with dot', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy( + 'a', + 'ASCENDING', + 'a.z', + 'ASCENDING', + '`a.a`', + 'ASCENDING', + '__name__', + 'ASCENDING', + ), + startAt( + true, + { + mapValue: { + fields: { + z: { + stringValue: 'a.z', + }, + }, + }, + }, + 'a.z', + 'a.a', + { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }, + ), + fieldFiltersQuery( + 'a', + 'LESS_THAN', + 'value', + '`a.a`', + 'GREATER_THAN', + 'value', + 'a.z', + 'GREATER_THAN', + 'value', + ), + ); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', { + a: {z: 'a.z'}, + 'a.a': 'a.a', + }); + const query = firestore + .collection('collectionId') + .where('a', '<', 'value') + .where(new FieldPath('a.a'), '>', 'value') // field name with dot + .where('a.z', '>', 'value') // nested field + .startAt(doc); + await query.get(); + }); + + it('composite filter', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy( + 'a', + 'ASCENDING', + 'b', + 'ASCENDING', + 'c', + 'ASCENDING', + 'd', + 'ASCENDING', + '__name__', + 'ASCENDING', + ), + startAt(true, 'a', 'b', 'c', 'd', { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }), + where( + compositeFilter( + 'AND', + fieldFilter('a', 'LESS_THAN', 'value'), + + compositeFilter( + 'AND', + compositeFilter( + 'OR', + fieldFilter('b', 'GREATER_THAN_OR_EQUAL', 'value'), + fieldFilter('c', 'LESS_THAN_OR_EQUAL', 'value'), + ), + compositeFilter( + 'OR', + fieldFilter('d', 'GREATER_THAN', 'value'), + fieldFilter('e', 'EQUAL', 'value'), + ), + ), + ), + ), + ); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', { + a: 'a', + b: 'b', + c: 'c', + d: 'd', + e: 'e', + }); + const query = firestore + .collection('collectionId') + .where('a', '<', 'value') + .where( + Filter.and( + Filter.or( + Filter.where('b', '>=', 'value'), + Filter.where('c', '<=', 'value'), + ), + Filter.or( + Filter.where('d', '>', 'value'), + Filter.where('e', '==', 'value'), + ), + ), + ) + .startAt(doc); + await query.get(); + }); + + it('explicit orderby', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy( + 'z', + 'ASCENDING', + 'a', + 'ASCENDING', + 'b', + 'ASCENDING', + '__name__', + 'ASCENDING', + ), + startAt(true, 'z', 'a', 'b', { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }), + fieldFiltersQuery( + 'b', + 'LESS_THAN', + 'value', + 'a', + 'GREATER_THAN', + 'value', + 'z', + 'GREATER_THAN', + 'value', + ), + ); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', { + a: 'a', + b: 'b', + z: 'z', + }); + const query = firestore + .collection('collectionId') + .where('b', '<', 'value') + .where('a', '>', 'value') + .where('z', '>', 'value') + .orderBy('z') + .startAt(doc); + await query.get(); + }); + + it('explicit order by direction', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy( + 'z', + 'DESCENDING', + 'a', + 'DESCENDING', + 'b', + 'DESCENDING', + '__name__', + 'DESCENDING', + ), + startAt(true, 'z', 'a', 'b', { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }), + fieldFiltersQuery( + 'b', + 'LESS_THAN', + 'value', + 'a', + 'GREATER_THAN', + 'value', + ), + ); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', { + a: 'a', + b: 'b', + z: 'z', + }); + const query = firestore + .collection('collectionId') + .where('b', '<', 'value') + .where('a', '>', 'value') + .orderBy('z', 'desc') + .startAt(doc); + await query.get(); + }); + + it('last explicit order by direction', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy( + 'z', + 'DESCENDING', + 'c', + 'ASCENDING', + 'a', + 'ASCENDING', + 'b', + 'ASCENDING', + '__name__', + 'ASCENDING', + ), + startAt(true, 'z', 'c', 'a', 'b', { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc', + }), + fieldFiltersQuery( + 'b', + 'LESS_THAN', + 'value', + 'a', + 'GREATER_THAN', + 'value', + ), + ); + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + const doc = await snapshot('collectionId/doc', { + a: 'a', + b: 'b', + c: 'c', + z: 'z', + }); + const query = firestore + .collection('collectionId') + .where('b', '<', 'value') + .where('a', '>', 'value') + .orderBy('z', 'desc') + .orderBy('c') + .startAt(doc); + await query.get(); + }); + }); + + it('validates field exists in document snapshot', async () => { + const query = firestore.collection('collectionId').orderBy('foo', 'desc'); + + const doc = await snapshot('collectionId/doc', {}); + expect(() => query.startAt(doc)).to.throw( + 'Field "foo" is missing in the provided DocumentSnapshot. Please provide a document that contains values for all specified orderBy() and where() constraints.', + ); + }); + + it('does not accept field deletes', () => { + const query = firestore.collection('collectionId').orderBy('foo'); + + expect(() => { + query.orderBy('foo').startAt('foo', FieldValue.delete()); + }).to.throw( + 'Element at index 1 is not a valid query constraint. FieldValue.delete() must appear at the top-level and can only be used in update() or set() with {merge:true}.', + ); + }); + + it('requires order by', () => { + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo'); + + expect(() => query.startAt('foo', 'bar')).to.throw( + 'Too many cursor values specified. The specified values must match the orderBy() constraints of the query.', + ); + }); + + it('can overspecify order by', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('foo', 'ASCENDING', 'bar', 'ASCENDING'), + startAt(true, 'foo'), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').orderBy('bar').startAt('foo'); + await query.get(); + }); + + it('validates input', () => { + const query = firestore.collection('collectionId'); + expect(() => query.startAt(123)).to.throw( + 'Too many cursor values specified. The specified values must match the orderBy() constraints of the query.', + ); + }); + + it('uses latest value', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, orderBy('foo', 'ASCENDING'), startAt(true, 'bar')); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').startAt('foo').startAt('bar'); + await query.get(); + }); +}); + +describe('startAfter() interface', () => { + let firestore: Firestore; + + beforeEach(async () => { + firestore = await createInstance(); + }); + + afterEach(() => verifyInstance(firestore)); + + it('accepts fields', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('foo', 'ASCENDING', 'bar', 'ASCENDING'), + startAt(false, 'foo', 'bar'), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').orderBy('bar').startAfter('foo', 'bar'); + await query.get(); + }); + + it('validates input', () => { + const query = firestore.collection('collectionId'); + expect(() => query.startAfter(123)).to.throw( + 'Too many cursor values specified. The specified values must match the orderBy() constraints of the query.', + ); + }); + + it('uses latest value', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('foo', 'ASCENDING'), + startAt(false, 'bar'), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').startAfter('foo').startAfter('bar'); + await query.get(); + }); +}); + +describe('endAt() interface', () => { + let firestore: Firestore; + + beforeEach(async () => { + firestore = await createInstance(); + }); + + afterEach(() => verifyInstance(firestore)); + + it('accepts fields', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('foo', 'ASCENDING', 'bar', 'ASCENDING'), + endAt(false, 'foo', 'bar'), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').orderBy('bar').endAt('foo', 'bar'); + await query.get(); + }); + + it('validates input', () => { + const query = firestore.collection('collectionId'); + expect(() => query.endAt(123)).to.throw( + 'Too many cursor values specified. The specified values must match the orderBy() constraints of the query.', + ); + }); + + it('uses latest value', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, orderBy('foo', 'ASCENDING'), endAt(false, 'bar')); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').endAt('foo').endAt('bar'); + await query.get(); + }); +}); + +describe('endBefore() interface', () => { + let firestore: Firestore; + + beforeEach(async () => { + firestore = await createInstance(); + }); + + afterEach(() => verifyInstance(firestore)); + + it('accepts fields', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + orderBy('foo', 'ASCENDING', 'bar', 'ASCENDING'), + endAt(true, 'foo', 'bar'), + ); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').orderBy('bar').endBefore('foo', 'bar'); + await query.get(); + }); + + it('validates input', () => { + const query = firestore.collection('collectionId'); + expect(() => query.endBefore(123)).to.throw( + 'Too many cursor values specified. The specified values must match the orderBy() constraints of the query.', + ); + }); + + it('uses latest value', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, orderBy('foo', 'ASCENDING'), endAt(true, 'bar')); + + return emptyQueryStream(); + }, + }; + + firestore = await createInstance(overrides); + let query: Query = firestore.collection('collectionId'); + query = query.orderBy('foo').endBefore('foo').endBefore('bar'); + await query.get(); + }); + + it('is immutable', async () => { + let expectedComponents = [limit(10)]; + + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, ...expectedComponents); + return emptyQueryStream(); + }, + }; + firestore = await createInstance(overrides); + const query = firestore.collection('collectionId').limit(10); + const adjustedQuery = query.orderBy('foo').endBefore('foo'); + + await query.get(); + expectedComponents = [ + limit(10), + orderBy('foo', 'ASCENDING'), + endAt(true, 'foo'), + ]; + + await adjustedQuery.get(); + }); +}); + +describe('collectionGroup queries', () => { + it('serialize correctly', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + allDescendants(), + fieldFiltersQuery('foo', 'EQUAL', 'bar'), + ); + return emptyQueryStream(); + }, + }; + const firestore = await createInstance(overrides); + const query = firestore + .collectionGroup('collectionId') + .where('foo', '==', 'bar'); + await query.get(); + }); + + it('rejects slashes', async () => { + const firestore = await createInstance(); + expect(() => firestore.collectionGroup('foo/bar')).to.throw( + "Invalid collectionId 'foo/bar'. Collection IDs must not contain '/'.", + ); + }); + + it('rejects slashes', async () => { + const firestore = await createInstance(); + const query = firestore.collectionGroup('collectionId'); + + expect(() => { + query.orderBy(FieldPath.documentId()).startAt('coll'); + }).to.throw( + 'When querying a collection group and ordering by ' + + 'FieldPath.documentId(), the corresponding value must result in a ' + + "valid document path, but 'coll' is not because it contains an odd " + + 'number of segments.', + ); + }); +}); + +describe('query resumption', () => { + let firestore: Firestore; + + beforeEach(async () => { + setTimeoutHandler(setImmediate); + firestore = await createInstance(); + }); + + afterEach(async () => { + await verifyInstance(firestore); + setTimeoutHandler(setTimeout); + }); + + // Return `numDocs` document responses, followed by an error response. + function* getDocResponsesFollowedByError( + documentIds: string[], + numDocs: number, + error: Error, + startAtEnd?: boolean, + ): Generator { + assert(numDocs <= documentIds.length); + const sliced = startAtEnd + ? documentIds.slice(-1 * numDocs) + : documentIds.slice(0, numDocs); + let runQueryResponses = sliced.map(documentId => result(documentId)); + if (startAtEnd) { + runQueryResponses = runQueryResponses.reverse(); + } + for (const runQueryResponse of runQueryResponses) { + yield runQueryResponse; + } + yield error; + } + + // Returns the documents from the given `documentIds` starting at the cursor + // determined by `startAt` (or `endAt`) in the request. It will continue to + // return documents until either the request `limit` is reached or `numDocs` + // (if provided) is reached. If an `error` is provided, it will return the + // given error after the docs are returned. + function* getDocResponsesForRequest( + request: api.IRunQueryRequest, + documentIds: string[], + options?: { + numDocs?: number; + error?: Error; + }, + ): Generator { + let begin: number | null | undefined; + let end: number | null | undefined; + let reverseOrder: boolean; + if (request.structuredQuery?.startAt) { + begin = getStartAtDocumentIndex(request, documentIds); + if (begin === null) { + throw new Error('the request should specify a valid startAt'); + } + if (request.structuredQuery.limit?.value) { + end = begin + request.structuredQuery.limit.value; + } else { + end = undefined; + } + reverseOrder = false; + } else if (request.structuredQuery?.endAt) { + end = getEndAtDocumentIndex(request, documentIds); + if (end === null) { + throw new Error('the request should specify a valid endAt'); + } + if (request.structuredQuery.limit?.value) { + begin = end - request.structuredQuery.limit.value; + } else { + begin = undefined; + } + reverseOrder = true; + } else { + throw new Error('the request does not specify a valid startAt or endAt'); + } + + const runQueryResponses = documentIds + .slice(begin, end) + .map(documentId => result(documentId)); + + let numDocsReturned = 0; + for (const runQueryResponse of reverseOrder + ? runQueryResponses.reverse() + : runQueryResponses) { + // If `numDocs` is provided, stop iterating when it is reached. + if (options?.numDocs && numDocsReturned === options.numDocs) { + break; + } + numDocsReturned++; + yield runQueryResponse; + } + + // If `error` is provided, emit it after all the docs. + if (options?.error) { + yield options.error; + } + } + + // Finds the index in `documentIds` of the document referred to in the + // "startAt" of the given request. Returns `null` if it cannot find one. + function getStartAtDocumentIndex( + request: api.IRunQueryRequest, + documentIds: string[], + ): number | null { + const startAt = request.structuredQuery?.startAt; + const startAtValue = startAt?.values?.[0]?.referenceValue; + const startAtBefore = startAt?.before; + if (typeof startAtValue !== 'string') { + return null; + } + const docId = startAtValue.split('/').pop()!; + const docIdIndex = documentIds.indexOf(docId); + if (docIdIndex < 0) { + return null; + } + return startAtBefore ? docIdIndex : docIdIndex + 1; + } + + // Finds the index in `documentIds` of the document referred to in the + // "endAt" of the given request. Returns `null` if it cannot find one. + function getEndAtDocumentIndex( + request: api.IRunQueryRequest, + documentIds: string[], + ): number | null { + const endAt = request.structuredQuery?.endAt; + const endAtValue = endAt?.values?.[0]?.referenceValue; + const endAtBefore = endAt?.before; + if (typeof endAtValue !== 'string') { + return null; + } + const docId = endAtValue.split('/').pop()!; + const docIdIndex = documentIds.indexOf(docId); + if (docIdIndex < 0) { + return null; + } + return endAtBefore ? docIdIndex : docIdIndex - 1; + } + + // Prevent regression of + // https://github.com/googleapis/nodejs-firestore/issues/1790 + it('results should not be double produced on retryable error with back pressure', async () => { + // Generate the IDs of the documents that will match the query. + const documentIds = Array.from(new Array(500), (_, index) => `doc${index}`); + + // Set up the mocked responses from Watch. + let requestNum = 0; + const overrides: ApiOverride = { + runQuery: request => { + requestNum++; + switch (requestNum) { + case 1: + // Return the first half of the documents, followed by a retryable error. + return stream( + ...getDocResponsesFollowedByError( + documentIds, + documentIds.length / 2, + new GoogleError('simulated retryable error'), + ), + ); + case 2: + // Return the remaining documents. + return stream(...getDocResponsesForRequest(request!, documentIds)); + default: + throw new Error(`should never get here (requestNum=${requestNum})`); + } + }, + }; + + // Create an async iterator to get the result set. + firestore = await createInstance(overrides); + const query = firestore.collection('collectionId'); + query._queryUtil._isPermanentRpcError = () => false; + const iterator = query + .stream() + [Symbol.asyncIterator]() as AsyncIterator; + const snapshots = await collect(iterator); + + // Verify that the async iterator returned the correct documents and, + // especially, does not have duplicate results. + const actualDocumentIds = snapshots.map(snapshot => snapshot.id); + expect(actualDocumentIds).to.eql(documentIds); + }); + + it('resuming queries with a cursor should respect the original query limit', async () => { + // Generate the IDs of the documents that will match the query. + const documentIds = Array.from(new Array(500), (_, index) => `doc${index}`); + + // Set up the mocked responses from Watch. + let requestNum = 0; + const overrides: ApiOverride = { + runQuery: request => { + requestNum++; + switch (requestNum) { + case 1: + return stream( + ...getDocResponsesFollowedByError( + documentIds, + documentIds.length / 2, + new GoogleError('simulated retryable error'), + ), + ); + case 2: + return stream(...getDocResponsesForRequest(request!, documentIds)); + default: + throw new Error(`should never get here (requestNum=${requestNum})`); + } + }, + }; + + // Create an async iterator to get the result set. + const limit = 300; + firestore = await createInstance(overrides); + const query = firestore.collection('collectionId').limit(limit); + query._queryUtil._isPermanentRpcError = () => false; + const iterator = query + .stream() + [Symbol.asyncIterator]() as AsyncIterator; + const snapshots = await collect(iterator); + + // Verify that we got the correct number of results, and the results match + // the documents we expect. + const actualDocumentIds = snapshots.map(snapshot => snapshot.id); + expect(actualDocumentIds.length).to.eql(limit); + expect(actualDocumentIds).to.eql(documentIds.slice(0, limit)); + }); + + it('resuming queries with a cursor should respect the original query limitToLast', async () => { + // Generate the IDs of the documents that will match the query. + const documentIds = Array.from(new Array(500), (_, index) => `doc${index}`); + + // Set up the mocked responses from Watch. + let requestNum = 0; + const overrides: ApiOverride = { + runQuery: request => { + requestNum++; + switch (requestNum) { + case 1: + return stream( + ...getDocResponsesFollowedByError( + documentIds, + documentIds.length / 2, + new GoogleError('simulated retryable error'), + /*startAtEnd*/ true, + ), + ); + case 2: + return stream(...getDocResponsesForRequest(request!, documentIds)); + default: + throw new Error(`should never get here (requestNum=${requestNum})`); + } + }, + }; + + // `stream()` cannot be called for `limitToLast` queries. We can, however, + // test using the `.get()` method which does some additional processing. + const limit = 300; + firestore = await createInstance(overrides); + const query = firestore + .collection('collectionId') + .orderBy(FieldPath.documentId()) + .limitToLast(limit); + query._queryUtil._isPermanentRpcError = () => false; + const snapshots = await query.get(); + + // Verify that we got the correct number of results, and the results match + // the documents we expect. + const actualDocumentIds = snapshots.docs.map(snapshot => snapshot.id); + expect(actualDocumentIds.length).to.eql(limit); + // slice(-limit) returns the last `limit` documents in the array. + expect(actualDocumentIds).to.eql(documentIds.slice(-limit)); + }); + + it('resuming queries with multiple failures should respect the original limit', async () => { + // Generate the IDs of the documents that will match the query. + const documentIds = Array.from(new Array(600), (_, index) => `doc${index}`); + + // Set up the mocked responses from Watch. + let requestNum = 0; + const overrides: ApiOverride = { + runQuery: request => { + requestNum++; + switch (requestNum) { + case 1: + // Get the first 60 documents followed by a retryable error. + return stream( + ...getDocResponsesFollowedByError( + documentIds, + documentIds.length / 10, + new GoogleError('simulated retryable error'), + ), + ); + case 2: + // Get the another 120 documents followed by a retryable error. + return stream( + ...getDocResponsesForRequest(request!, documentIds, { + numDocs: documentIds.length / 5, + error: new GoogleError('simulated retryable error'), + }), + ); + case 3: + // Get the rest of the documents. + return stream(...getDocResponsesForRequest(request!, documentIds)); + default: + throw new Error(`should never get here (requestNum=${requestNum})`); + } + }, + }; + + // Create an async iterator to get the result set. + const limit = 300; + firestore = await createInstance(overrides); + const query = firestore.collection('collectionId').limit(limit); + query._queryUtil._isPermanentRpcError = () => false; + const iterator = query + .stream() + [Symbol.asyncIterator]() as AsyncIterator; + const snapshots = await collect(iterator); + + // Verify that we got the correct number of results, and the results match + // the documents we expect. + const actualDocumentIds = snapshots.map(snapshot => snapshot.id); + expect(actualDocumentIds.length).to.eql(limit); + expect(actualDocumentIds).to.eql(documentIds.slice(0, limit)); + }); + + it('resuming queries with multiple failures should respect the original limitToLast', async () => { + // Generate the IDs of the documents that will match the query. + const documentIds = Array.from(new Array(600), (_, index) => `doc${index}`); + + // Set up the mocked responses from Watch. + let requestNum = 0; + const overrides: ApiOverride = { + runQuery: request => { + requestNum++; + switch (requestNum) { + case 1: + // Get the first 60 documents followed by a retryable error. + return stream( + ...getDocResponsesFollowedByError( + documentIds, + documentIds.length / 10, + new GoogleError('simulated retryable error'), + /*startAtEnd*/ true, + ), + ); + case 2: + // Get the another 120 documents followed by a retryable error. + return stream( + ...getDocResponsesForRequest(request!, documentIds, { + numDocs: documentIds.length / 5, + error: new GoogleError('simulated retryable error'), + }), + ); + case 3: + // Get the rest of the documents. + return stream(...getDocResponsesForRequest(request!, documentIds)); + default: + throw new Error(`should never get here (requestNum=${requestNum})`); + } + }, + }; + + // `stream()` cannot be called for `limitToLast` queries. We can, however, + // test using the `.get()` method which does some additional processing. + const limit = 300; + firestore = await createInstance(overrides); + const query = firestore + .collection('collectionId') + .orderBy(FieldPath.documentId()) + .limitToLast(limit); + query._queryUtil._isPermanentRpcError = () => false; + const snapshots = await query.get(); + + // Verify that we got the correct number of results, and the results match + // the documents we expect. + const actualDocumentIds = snapshots.docs.map(snapshot => snapshot.id); + expect(actualDocumentIds.length).to.eql(limit); + // slice(-limit) returns the last `limit` documents in the array. + expect(actualDocumentIds).to.eql(documentIds.slice(-limit)); + }); +}); diff --git a/handwritten/firestore/dev/test/rate-limiter.ts b/handwritten/firestore/dev/test/rate-limiter.ts new file mode 100644 index 00000000000..321f6dba752 --- /dev/null +++ b/handwritten/firestore/dev/test/rate-limiter.ts @@ -0,0 +1,116 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {describe, it, beforeEach} from 'mocha'; +import {expect} from 'chai'; + +import {RateLimiter} from '../src/rate-limiter'; + +describe('RateLimiter', () => { + let limiter: RateLimiter; + + beforeEach(() => { + limiter = new RateLimiter( + /* initialCapacity= */ 500, + /* multiplier= */ 1.5, + /* multiplierMillis= */ 5 * 60 * 1000, + /* maximumCapacity= */ 1000000, + /* startTime= */ new Date(0).getTime(), + ); + }); + + it('accepts and rejects requests based on capacity', () => { + expect(limiter.tryMakeRequest(250, new Date(0).getTime())).to.be.true; + expect(limiter.tryMakeRequest(250, new Date(0).getTime())).to.be.true; + + // Once tokens have been used, further requests should fail. + expect(limiter.tryMakeRequest(1, new Date(0).getTime())).to.be.false; + + // Tokens will only refill up to max capacity. + expect(limiter.tryMakeRequest(501, new Date(1 * 1000).getTime())).to.be + .false; + expect(limiter.tryMakeRequest(500, new Date(1 * 1000).getTime())).to.be + .true; + + // Tokens will refill incrementally based on the number of ms elapsed. + expect(limiter.tryMakeRequest(250, new Date(1 * 1000 + 499).getTime())).to + .be.false; + expect(limiter.tryMakeRequest(249, new Date(1 * 1000 + 500).getTime())).to + .be.true; + + // Scales with multiplier. + expect(limiter.tryMakeRequest(751, new Date((5 * 60 - 1) * 1000).getTime())) + .to.be.false; + expect(limiter.tryMakeRequest(751, new Date(5 * 60 * 1000).getTime())).to.be + .false; + expect(limiter.tryMakeRequest(750, new Date(5 * 60 * 1000).getTime())).to.be + .true; + + // Tokens will never exceed capacity. + expect(limiter.tryMakeRequest(751, new Date((5 * 60 + 3) * 1000).getTime())) + .to.be.false; + + // Rejects requests made before lastRefillTime + expect(() => + limiter.tryMakeRequest(751, new Date((5 * 60 + 2) * 1000).getTime()), + ).to.throw('Request time should not be before the last token refill time.'); + }); + + it('calculates the number of ms needed to place the next request', () => { + // Should return 0 if there are enough tokens for the request to be made. + let timestamp = new Date(0).getTime(); + expect(limiter.getNextRequestDelayMs(500, timestamp)).to.equal(0); + + // Should factor in remaining tokens when calculating the time. + expect(limiter.tryMakeRequest(250, timestamp)).to.be.true; + expect(limiter.getNextRequestDelayMs(500, timestamp)).to.equal(500); + + // Once tokens have been used, should calculate time before next request. + timestamp = new Date(1 * 1000).getTime(); + expect(limiter.tryMakeRequest(500, timestamp)).to.be.true; + expect(limiter.getNextRequestDelayMs(100, timestamp)).to.equal(200); + expect(limiter.getNextRequestDelayMs(250, timestamp)).to.equal(500); + expect(limiter.getNextRequestDelayMs(500, timestamp)).to.equal(1000); + expect(limiter.getNextRequestDelayMs(501, timestamp)).to.equal(-1); + + // Scales with multiplier. + timestamp = new Date(5 * 60 * 1000).getTime(); + expect(limiter.tryMakeRequest(750, timestamp)).to.be.true; + expect(limiter.getNextRequestDelayMs(250, timestamp)).to.equal(334); + expect(limiter.getNextRequestDelayMs(500, timestamp)).to.equal(667); + expect(limiter.getNextRequestDelayMs(750, timestamp)).to.equal(1000); + expect(limiter.getNextRequestDelayMs(751, timestamp)).to.equal(-1); + }); + + it('calculates the maximum number of operations correctly', async () => { + expect(limiter.calculateCapacity(new Date(0).getTime())).to.equal(500); + expect( + limiter.calculateCapacity(new Date(5 * 60 * 1000).getTime()), + ).to.equal(750); + expect( + limiter.calculateCapacity(new Date(10 * 60 * 1000).getTime()), + ).to.equal(1125); + expect( + limiter.calculateCapacity(new Date(15 * 60 * 1000).getTime()), + ).to.equal(1687); + expect( + limiter.calculateCapacity(new Date(90 * 60 * 1000).getTime()), + ).to.equal(738945); + + // Check that maximum rate limit is enforced. + expect( + limiter.calculateCapacity(new Date(1000 * 60 * 1000).getTime()), + ).to.equal(1000000); + }); +}); diff --git a/handwritten/firestore/dev/test/recursive-delete.ts b/handwritten/firestore/dev/test/recursive-delete.ts new file mode 100644 index 00000000000..14cf92ed5ef --- /dev/null +++ b/handwritten/firestore/dev/test/recursive-delete.ts @@ -0,0 +1,650 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +import {afterEach, beforeEach, describe, it} from 'mocha'; +import {fail} from 'assert'; +import {expect} from 'chai'; +import {GoogleError, Status} from 'google-gax'; +import sinon = require('sinon'); + +import {google} from '../protos/firestore_v1_proto_api'; + +import * as Firestore from '../src'; +import {setTimeoutHandler} from '../src/backoff'; +import { + ApiOverride, + createInstance, + postConverter, + response, + stream, + verifyInstance, +} from './util/helpers'; +import { + allDescendants, + fieldFiltersQuery, + limit, + orderBy, + queryEquals, + queryEqualsWithParent, + result, + select, + startAt as queryStartAt, +} from './query'; +import { + createRequest, + deleteOp, + failedResponse, + mergeResponses, + successResponse, +} from './bulk-writer'; +import {MAX_REQUEST_RETRIES} from '../src'; + +import api = google.firestore.v1; +import { + RECURSIVE_DELETE_MAX_PENDING_OPS, + REFERENCE_NAME_MIN_ID, +} from '../src/recursive-delete'; +import {Deferred} from '../src/util'; + +const PROJECT_ID = 'test-project'; +const DATABASE_ROOT = `projects/${PROJECT_ID}/databases/(default)`; + +describe('recursiveDelete() method:', () => { + // We store errors from batchWrite inside an error object since errors thrown + // in batchWrite do not affect the recursiveDelete promise. + let batchWriteError: Error | undefined; + let firestore: Firestore.Firestore; + + beforeEach(() => { + setTimeoutHandler(setImmediate); + }); + + afterEach(async () => { + await verifyInstance(firestore); + setTimeoutHandler(setTimeout); + expect(batchWriteError, 'batchWrite should not have errored').to.be + .undefined; + }); + + function instantiateInstance( + childrenDocs: Array, + deleteDocRef = '', + responses?: api.IBatchWriteResponse, + ): Promise { + const overrides: ApiOverride = { + runQuery: () => { + return stream(...childrenDocs.map(docId => result(docId))); + }, + batchWrite: request => { + const documents = childrenDocs; + if (deleteDocRef.length > 0) { + documents.push(deleteDocRef); + } + const expected = createRequest(documents.map(docId => deleteOp(docId))); + try { + expect(request.writes).to.deep.equal(expected.writes); + } catch (e) { + batchWriteError = e; + } + const returnedResponse = + responses ?? mergeResponses(documents.map(() => successResponse(1))); + + return response({ + writeResults: returnedResponse.writeResults, + status: returnedResponse.status, + }); + }, + }; + + return createInstance(overrides); + } + + describe('calls getAllDescendants() with correct StructuredQuery', () => { + function startAt(name: string): api.IValue { + return { + referenceValue: + DATABASE_ROOT + '/documents/' + name + '/' + REFERENCE_NAME_MIN_ID, + }; + } + + function endAt(name: string): api.IValue { + return { + referenceValue: + DATABASE_ROOT + + '/documents/' + + name + + String.fromCharCode(0) + + '/' + + REFERENCE_NAME_MIN_ID, + }; + } + + it('for root-level collections', async () => { + const overrides: ApiOverride = { + runQuery: req => { + queryEquals( + req, + select('__name__'), + allDescendants(/* kindless= */ true), + fieldFiltersQuery( + '__name__', + 'GREATER_THAN_OR_EQUAL', + startAt('root'), + '__name__', + 'LESS_THAN', + endAt('root'), + ), + limit(RECURSIVE_DELETE_MAX_PENDING_OPS), + ); + return stream(); + }, + }; + firestore = await createInstance(overrides); + return firestore.recursiveDelete(firestore.collection('root')); + }); + + it('for nested collections', async () => { + const overrides: ApiOverride = { + runQuery: req => { + queryEqualsWithParent( + req, + 'root/doc', + select('__name__'), + allDescendants(/* kindless= */ true), + fieldFiltersQuery( + '__name__', + 'GREATER_THAN_OR_EQUAL', + startAt('root/doc/nestedCol'), + '__name__', + 'LESS_THAN', + endAt('root/doc/nestedCol'), + ), + limit(RECURSIVE_DELETE_MAX_PENDING_OPS), + ); + return stream(); + }, + }; + firestore = await createInstance(overrides); + return firestore.recursiveDelete( + firestore.collection('root/doc/nestedCol'), + ); + }); + + it('documents', async () => { + const overrides: ApiOverride = { + runQuery: req => { + queryEqualsWithParent( + req, + 'root/doc', + select('__name__'), + allDescendants(/* kindless= */ true), + limit(RECURSIVE_DELETE_MAX_PENDING_OPS), + ); + return stream(); + }, + // Include dummy response for the deleted docRef. + batchWrite: () => response(successResponse(1)), + }; + firestore = await createInstance(overrides); + return firestore.recursiveDelete(firestore.doc('root/doc')); + }); + + it('creates retry query after stream exception with last received doc', async () => { + let callCount = 0; + const overrides: ApiOverride = { + runQuery: request => { + callCount++; + if (callCount === 1) { + return stream(result('doc1'), new Error('failed in test')); + } else { + queryEqualsWithParent( + request, + /* parent= */ '', + select('__name__'), + allDescendants(/* kindless= */ true), + orderBy('__name__', 'ASCENDING'), + queryStartAt(false, { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc1', + }), + fieldFiltersQuery( + '__name__', + 'GREATER_THAN_OR_EQUAL', + startAt('root'), + '__name__', + 'LESS_THAN', + endAt('root'), + ), + limit(RECURSIVE_DELETE_MAX_PENDING_OPS - 1), + ); + return stream(); + } + }, + batchWrite: () => response(successResponse(1)), + }; + + const firestore = await createInstance(overrides); + await firestore.recursiveDelete(firestore.collection('root')); + }); + + it('creates a second query with the correct startAfter', async () => { + // This test checks that the second query is created with the correct + // startAfter() once the RecursiveDelete instance is below the + // MIN_PENDING_OPS threshold to send the next batch. Use lower limits + // than the actual RecursiveDelete class in order to make this test run fast. + const maxPendingOps = 100; + const minPendingOps = 11; + const maxBatchSize = 10; + const cutoff = maxPendingOps - minPendingOps; + let numDeletesBuffered = 0; + + // This deferred promise is used to delay the BatchWriteResponses from + // returning in order to create the situation where the number of pending + // operations is less than `minPendingOps`. + const bufferDeferred = new Deferred(); + + // This deferred completes when the second query is run. + const secondQueryDeferred = new Deferred(); + + const nLengthArray = (n: number): number[] => Array.from(Array(n).keys()); + + const firstStream = nLengthArray(maxPendingOps).map((_, i) => + result('doc' + i), + ); + + const batchWriteResponse = mergeResponses( + nLengthArray(maxBatchSize).map(() => successResponse(1)), + ); + + // Use an array to store that the queryEquals() method succeeded, since + // thrown errors do not result in the recursiveDelete() method failing. + const called: number[] = []; + const overrides: ApiOverride = { + runQuery: request => { + if (called.length === 0) { + queryEquals( + request, + select('__name__'), + allDescendants(/* kindless= */ true), + fieldFiltersQuery( + '__name__', + 'GREATER_THAN_OR_EQUAL', + startAt('root'), + '__name__', + 'LESS_THAN', + endAt('root'), + ), + limit(maxPendingOps), + ); + called.push(1); + return stream(...firstStream); + } else if (called.length === 1) { + queryEquals( + request, + select('__name__'), + allDescendants(/* kindless= */ true), + orderBy('__name__', 'ASCENDING'), + fieldFiltersQuery( + '__name__', + 'GREATER_THAN_OR_EQUAL', + startAt('root'), + '__name__', + 'LESS_THAN', + endAt('root'), + ), + queryStartAt(false, { + referenceValue: + `projects/${PROJECT_ID}/databases/(default)/` + + 'documents/collectionId/doc' + + (maxPendingOps - 1), + }), + limit(maxPendingOps), + ); + called.push(2); + secondQueryDeferred.resolve(); + return stream(); + } else { + called.push(3); + return stream(); + } + }, + batchWrite: () => { + const returnedResponse = response({ + writeResults: batchWriteResponse.writeResults, + status: batchWriteResponse.status, + }); + if (numDeletesBuffered < cutoff) { + numDeletesBuffered += batchWriteResponse.writeResults!.length; + + // By waiting for `bufferFuture` to complete, we can guarantee that + // the writes complete after all documents are streamed. Without + // this future, the test can race and complete the writes before + // the stream is finished, which is a different scenario this test + // is not for. + return bufferDeferred.promise.then(() => returnedResponse); + } else { + // Once there are `cutoff` pending deletes, completing the future + // allows enough responses to be returned such that the number of + // pending deletes should be less than `minPendingOps`. This allows + // us to test that the second query is made. + bufferDeferred.resolve(); + return secondQueryDeferred.promise.then(() => returnedResponse); + } + }, + }; + const firestore = await createInstance(overrides); + + const bulkWriter = firestore.bulkWriter(); + bulkWriter._setMaxBatchSize(maxBatchSize); + await firestore._recursiveDelete( + firestore.collection('root'), + maxPendingOps, + minPendingOps, + bulkWriter, + ); + expect(called).to.deep.equal([1, 2]); + }); + }); + + describe('deletes', () => { + it('collection', async () => { + // The four documents are under the 'collectionId' collection, and is + // automatically prefixed by `instantiateInstance()`. + firestore = await instantiateInstance([ + 'anna', + 'bob', + 'bob/children/charlie', + 'bob/children/daniel', + ]); + await firestore.recursiveDelete(firestore.collection('collectionId')); + }); + + it('document along with reference', async () => { + firestore = await instantiateInstance( + ['bob/children/brian', 'bob/children/charlie', 'bob/children/daniel'], + 'bob', + ); + await firestore.recursiveDelete( + firestore.collection('collectionId').doc('bob'), + ); + }); + + it('promise is rejected with the last error code if writes fail', async () => { + firestore = await instantiateInstance( + ['bob/children/brian', 'bob/children/charlie', 'bob/children/daniel'], + 'bob', + mergeResponses([ + successResponse(1), + failedResponse(Status.CANCELLED), + failedResponse(Status.PERMISSION_DENIED), + successResponse(1), + ]), + ); + try { + await firestore.recursiveDelete( + firestore.collection('collectionId').doc('bob'), + ); + fail('recursiveDelete should have failed'); + } catch (err) { + expect(err.code).to.equal(Status.PERMISSION_DENIED); + expect(err.message).to.contain('2 deletes failed'); + } + }); + + it('promise is rejected if BulkWriter success handler fails', async () => { + firestore = await instantiateInstance(['bob/children/brian'], 'bob'); + + const bulkWriter = firestore.bulkWriter(); + bulkWriter.onWriteResult(() => { + throw new Error('User provided result callback failed'); + }); + + try { + await firestore.recursiveDelete( + firestore.collection('collectionId').doc('bob'), + bulkWriter, + ); + fail('recursiveDelete() should have failed'); + } catch (err) { + expect(err.message).to.contain('2 deletes failed'); + expect(err.stack).to.contain('User provided result callback failed'); + } + }); + + it('BulkWriter success handler provides the correct references and results', async () => { + firestore = await instantiateInstance( + ['bob/children/brian', 'bob/children/charlie'], + 'bob', + mergeResponses([ + successResponse(1), + successResponse(2), + successResponse(3), + ]), + ); + const results: number[] = []; + const refs: string[] = []; + const bulkWriter = firestore.bulkWriter(); + bulkWriter.onWriteResult((ref, result) => { + results.push(result.writeTime.seconds); + refs.push(ref.path); + }); + + await firestore.recursiveDelete( + firestore.collection('collectionId').doc('bob'), + bulkWriter, + ); + expect(results).to.deep.equal([1, 2, 3]); + expect(refs).to.deep.equal([ + 'collectionId/bob/children/brian', + 'collectionId/bob/children/charlie', + 'collectionId/bob', + ]); + }); + + it('BulkWriter error handler provides the correct information', async () => { + firestore = await instantiateInstance( + ['bob/children/brian', 'bob/children/charlie'], + 'bob', + mergeResponses([ + failedResponse(Status.PERMISSION_DENIED), + failedResponse(Status.UNAVAILABLE), + failedResponse(Status.INTERNAL), + ]), + ); + const codes: Status[] = []; + const refs: string[] = []; + const bulkWriter = firestore.bulkWriter(); + bulkWriter.onWriteError(err => { + codes.push(err.code as unknown as Status); + refs.push(err.documentRef.path); + return false; + }); + + try { + await firestore.recursiveDelete( + firestore.collection('collectionId').doc('bob'), + bulkWriter, + ); + fail('recursiveDelete() should have failed'); + } catch (err) { + expect(codes).to.deep.equal([ + Status.PERMISSION_DENIED, + Status.UNAVAILABLE, + Status.INTERNAL, + ]); + expect(refs).to.deep.equal([ + 'collectionId/bob/children/brian', + 'collectionId/bob/children/charlie', + 'collectionId/bob', + ]); + } + }); + + it('promise is rejected if provided reference was not deleted', async () => { + const overrides: ApiOverride = { + runQuery: () => stream(), + batchWrite: () => { + throw new GoogleError('batchWrite() failed in test'); + }, + }; + firestore = await createInstance(overrides); + try { + await firestore.recursiveDelete(firestore.doc('root/doc')); + } catch (err) { + expect(err.stack).to.contain('batchWrite() failed in test'); + } + }); + + it('retries stream errors', async () => { + let attempts = 0; + const overrides: ApiOverride = { + runQuery: () => { + attempts++; + throw new Error('runQuery() error in test'); + }, + batchWrite: () => response(successResponse(1)), + }; + firestore = await createInstance(overrides); + try { + await firestore.recursiveDelete(firestore.doc('coll/foo')); + fail('recursiveDelete() should have failed'); + } catch (err) { + expect(err.code).to.equal(Status.UNAVAILABLE); + expect(err.stack).to.contain('Failed to fetch children documents'); + expect(err.stack).to.contain('runQuery() error in test'); + expect(attempts).to.equal(MAX_REQUEST_RETRIES); + } + }); + + it('handles successful stream error retries', async () => { + let requestCounter = 0; + const streamItems = [ + [result('a'), result('b'), new Error('runQuery() error in test')], + [new Error('runQuery() error in test')], + [result('c'), new Error('runQuery() error in test')], + [result('d')], + ]; + + const overrides: ApiOverride = { + runQuery: () => { + const streamPromise = stream(...streamItems[requestCounter]); + requestCounter++; + return streamPromise; + }, + batchWrite: request => { + const expected = createRequest([ + deleteOp('a'), + deleteOp('b'), + deleteOp('c'), + deleteOp('d'), + ]); + try { + expect(request.writes).to.deep.equal(expected.writes); + } catch (e) { + batchWriteError = e; + } + return response( + mergeResponses(expected.writes!.map(() => successResponse(1))), + ); + }, + }; + firestore = await createInstance(overrides); + await firestore.recursiveDelete(firestore.collection('letters')); + }); + + it('handles multiple calls to recursiveDelete()', async () => { + let requestCounter = 0; + const docIds = ['a', 'b', 'c']; + const streamItems = docIds.map(docId => [result(docId)]); + const expected = docIds.map(docId => createRequest([deleteOp(docId)])); + const responses = docIds.map(() => successResponse(1)); + + const overrides: ApiOverride = { + runQuery: () => { + return stream(...streamItems[requestCounter]); + }, + batchWrite: request => { + try { + expect(request.writes).to.deep.equal( + expected[requestCounter]!.writes, + ); + } catch (e) { + batchWriteError = e; + } + const responsePromise = response(responses[requestCounter]); + requestCounter++; + return responsePromise; + }, + }; + firestore = await createInstance(overrides); + await firestore.recursiveDelete(firestore.collection('a')); + await firestore.recursiveDelete(firestore.collection('b')); + await firestore.recursiveDelete(firestore.collection('c')); + }); + + it('accepts references with converters', async () => { + const overrides: ApiOverride = { + runQuery: () => stream(), + // Include response for deleting the provided document reference. + batchWrite: () => response(successResponse(1)), + }; + firestore = await createInstance(overrides); + await firestore.recursiveDelete( + firestore.doc('root/doc').withConverter(postConverter), + ); + await firestore.recursiveDelete( + firestore.collection('root').withConverter(postConverter), + ); + }); + }); + + describe('BulkWriter instance', () => { + it('uses custom BulkWriter instance if provided', async () => { + firestore = await instantiateInstance(['a', 'b', 'c']); + let callbackCount = 0; + const bulkWriter = firestore.bulkWriter(); + bulkWriter.onWriteResult(() => { + callbackCount++; + }); + await firestore.recursiveDelete(firestore.collection('foo'), bulkWriter); + expect(callbackCount).to.equal(3); + }); + + it('default: uses the same BulkWriter instance across calls', async () => { + const overrides: ApiOverride = { + runQuery: () => stream(), + }; + firestore = await createInstance(overrides); + const spy = sinon.spy(firestore, 'bulkWriter'); + + await firestore.recursiveDelete(firestore.collection('foo')); + await firestore.recursiveDelete(firestore.collection('boo')); + await firestore.recursiveDelete(firestore.collection('moo')); + + // Only the first recursiveDelete() call should have called the + // constructor. Subsequent calls should have used the same bulkWriter. + expect(spy.callCount).to.equal(1); + }); + + it('throws error if BulkWriter instance is closed', async () => { + firestore = await createInstance(); + const bulkWriter = firestore.bulkWriter(); + await bulkWriter.close(); + await expect( + () => () => + firestore.recursiveDelete(firestore.collection('foo'), bulkWriter), + ).to.throw; + }); + }); +}); diff --git a/handwritten/firestore/dev/test/serializer.ts b/handwritten/firestore/dev/test/serializer.ts new file mode 100644 index 00000000000..46ed3639ba0 --- /dev/null +++ b/handwritten/firestore/dev/test/serializer.ts @@ -0,0 +1,302 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {it} from 'mocha'; +import {expect} from 'chai'; +import * as sinon from 'sinon'; +import {validateUserInput, Serializer} from '../src/serializer'; +import {DocumentReference, Firestore} from '../src'; +import {SinonStubbedInstance} from 'sinon'; + +describe('validateUserInput', () => { + it('validates the depth of nested objects and arrays - 20', () => { + // This nested object is 20 levels deep + const nestedObject = { + // depth 0 + links: [ + // depth 1 + { + // depth 2 + child: { + // depth 3 + links: [ + // depth 4 + { + // depth 5 + child: { + // depth 6 + links: [ + // depth 7 + { + // depth 8 + child: { + // depth 9 + links: [ + // depth 10 + { + // depth 11 + child: { + // depth 12 + links: [ + // depth 13 + { + // depth 14 + child: { + // depth 15 + links: [ + // depth 16 + { + // depth 17 + child: { + // depth 18 + uiData: { + // depth 19 + choicesFactors: { + // depth 20 + rarely: 1, + }, + }, + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + ], + }; + + validateUserInput('nestedObject', nestedObject, 'Firestore Object', { + allowDeletes: 'none', + allowTransforms: false, + allowUndefined: false, + }); + }); + + it('validates the depth of nested objects and arrays - 21', () => { + // This nested object is 21 levels deep + const nestedObject = { + // depth 0 + links: [ + // depth 1 + { + // depth 2 + child: { + // depth 3 + links: [ + // depth 4 + { + // depth 5 + child: { + // depth 6 + links: [ + // depth 7 + { + // depth 8 + child: { + // depth 9 + links: [ + // depth 10 + { + // depth 11 + child: { + // depth 12 + links: [ + // depth 13 + { + // depth 14 + child: { + // depth 15 + links: [ + // depth 16 + { + // depth 17 + child: { + // depth 18 + uiData: { + // depth 19 + choicesFactors: { + // depth 20 + rarely: { + // depth 21 + cat: true, + }, + }, + }, + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + ], + }; + + expect(() => + validateUserInput('nestedObject', nestedObject, 'Firestore Object', { + allowDeletes: 'none', + allowTransforms: false, + allowUndefined: false, + }), + ).to.throw(/Input object is deeper than 20 levels/i); + }); + + it('validates the depth of nested objects - 20', () => { + // This nested object is 20 levels deep + const nestedObject = { + a: { + b: { + c: { + d: { + e: { + f: { + g: { + h: { + i: { + j: { + k: { + l: {m: {n: {o: {p: {q: {r: {s: {t: {u: 1}}}}}}}}}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }; + + validateUserInput('nestedObject', nestedObject, 'Firestore Object', { + allowDeletes: 'none', + allowTransforms: false, + allowUndefined: false, + }); + }); + + it('validates the depth of nested objects and arrays - 21', () => { + // This nested object is 21 levels deep + const nestedObject = { + a: { + b: { + c: { + d: { + e: { + f: { + g: { + h: { + i: { + j: { + k: { + l: { + m: {n: {o: {p: {q: {r: {s: {t: {u: {v: 1}}}}}}}}}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }; + + expect(() => + validateUserInput('nestedObject', nestedObject, 'Firestore Object', { + allowDeletes: 'none', + allowTransforms: false, + allowUndefined: false, + }), + ).to.throw(/Input object is deeper than 20 levels/i); + }); +}); + +describe('serializer', () => { + const PROJECT_ID = 'test-project'; + const DATABASE_ROOT = `projects/${PROJECT_ID}/databases/(default)`; + + let serializer: Serializer | undefined; + let firestoreStub: SinonStubbedInstance | undefined; + + const mockResult = {}; + + beforeEach(() => { + firestoreStub = sinon.stub({ + doc: (_: string) => { + return mockResult; + }, + _settings: {}, + } as Firestore); + firestoreStub.doc.returns(mockResult as DocumentReference); + + serializer = new Serializer(firestoreStub); + }); + + describe('decodeValue', () => { + it('decodes reference to document', () => { + const result = serializer!.decodeValue({ + referenceValue: `${DATABASE_ROOT}/documents/foo/bar`, + }) as DocumentReference; + + expect(result).to.equal(mockResult); + expect(firestoreStub!.doc.calledOnceWith('foo/bar')).to.be.true; + }); + + it('throws when given a reference to collection', () => { + expect(() => { + serializer!.decodeValue({ + referenceValue: `${DATABASE_ROOT}/documents/foo`, + }) as DocumentReference; + }).to.throw( + 'The SDK does not currently support decoding referenceValues for collections or partitions.', + ); + }); + + it('throws when given a reference to db root', () => { + expect(() => { + serializer!.decodeValue({ + referenceValue: `${DATABASE_ROOT}/documents`, + }) as DocumentReference; + }).to.throw( + 'The SDK does not currently support decoding referenceValues for collections or partitions.', + ); + }); + }); +}); diff --git a/handwritten/firestore/dev/test/structured-pipeline.ts b/handwritten/firestore/dev/test/structured-pipeline.ts new file mode 100644 index 00000000000..de8becee364 --- /dev/null +++ b/handwritten/firestore/dev/test/structured-pipeline.ts @@ -0,0 +1,181 @@ +/** + * @license + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {expect} from 'chai'; +import * as sinon from 'sinon'; +import {ProtoSerializable, Serializer} from '../src/serializer'; +import {google} from '../protos/firestore_v1_proto_api'; +import IPipeline = google.firestore.v1.IPipeline; +import {StructuredPipeline} from '../src/pipelines/structured-pipeline'; +import {createInstance} from './util/helpers'; +import {Firestore} from '../src'; + +describe('StructuredPipeline', () => { + let db: Firestore | undefined; + beforeEach(async () => { + db = await createInstance(); + }); + + afterEach(async () => { + if (db) { + await db.terminate(); + db = undefined; + } + }); + + it('should serialize the pipeline argument', async () => { + const pipeline: ProtoSerializable = { + _toProto: sinon.fake.returns({} as IPipeline), + }; + const structuredPipeline = new StructuredPipeline(pipeline, {}, {}); + + const proto = structuredPipeline._toProto(new Serializer(db!)); + + expect(proto).to.deep.equal({ + pipeline: {}, + options: {}, + }); + + expect((pipeline._toProto as sinon.SinonSpy).calledOnce).to.be.true; + }); + + it('should support known options', () => { + const pipeline: ProtoSerializable = { + _toProto: sinon.fake.returns({} as IPipeline), + }; + const structuredPipeline = new StructuredPipeline( + pipeline, + { + indexMode: 'recommended', + explainOptions: { + mode: 'explain', + outputFormat: 'text', + }, + }, + {}, + ); + + const proto = structuredPipeline._toProto(new Serializer(db!)); + + expect(proto).deep.equal({ + pipeline: {}, + options: { + index_mode: { + stringValue: 'recommended', + }, + explain_options: { + mapValue: { + fields: { + mode: { + stringValue: 'explain', + }, + output_format: { + stringValue: 'text', + }, + }, + }, + }, + }, + }); + + expect((pipeline._toProto as sinon.SinonSpy).calledOnce).to.be.true; + }); + + it('should support unknown options', () => { + const pipeline: ProtoSerializable = { + _toProto: sinon.fake.returns({} as IPipeline), + }; + const structuredPipeline = new StructuredPipeline( + pipeline, + {}, + { + foo_bar: 'baz', + }, + ); + + const proto = structuredPipeline._toProto(new Serializer(db!)); + + expect(proto).to.deep.equal({ + pipeline: {}, + options: { + foo_bar: { + stringValue: 'baz', + }, + }, + }); + + expect((pipeline._toProto as sinon.SinonSpy).calledOnce).to.be.true; + }); + + it('should support unknown nested options', () => { + const pipeline: ProtoSerializable = { + _toProto: sinon.fake.returns({} as IPipeline), + }; + const structuredPipeline = new StructuredPipeline( + pipeline, + {}, + { + 'foo.bar': 'baz', + }, + ); + + const proto = structuredPipeline._toProto(new Serializer(db!)); + + expect(proto).to.deep.equal({ + pipeline: {}, + options: { + foo: { + mapValue: { + fields: { + bar: {stringValue: 'baz'}, + }, + }, + }, + }, + }); + + expect((pipeline._toProto as sinon.SinonSpy).calledOnce).to.be.true; + }); + + it('should support options override', () => { + const pipeline: ProtoSerializable = { + _toProto: sinon.fake.returns({} as IPipeline), + }; + const structuredPipeline = new StructuredPipeline( + pipeline, + { + indexMode: 'recommended', + }, + { + index_mode: 'baz', + }, + ); + + const proto = structuredPipeline._toProto(new Serializer(db!)); + + expect(proto).to.deep.equal({ + pipeline: {}, + options: { + index_mode: { + stringValue: 'baz', + }, + }, + }); + + expect((pipeline._toProto as sinon.SinonSpy).calledOnce).to.be.true; + }); +}); diff --git a/handwritten/firestore/dev/test/timestamp.ts b/handwritten/firestore/dev/test/timestamp.ts new file mode 100644 index 00000000000..abef3b64d59 --- /dev/null +++ b/handwritten/firestore/dev/test/timestamp.ts @@ -0,0 +1,224 @@ +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {describe, it} from 'mocha'; +import {expect} from 'chai'; +import * as through2 from 'through2'; + +import {google} from '../protos/firestore_v1_proto_api'; + +import * as Firestore from '../src/index'; +import { + ApiOverride, + createInstance as createInstanceHelper, + document, +} from '../test/util/helpers'; + +import api = google.firestore.v1; + +function createInstance(opts: {}, document: api.IDocument) { + const overrides: ApiOverride = { + batchGetDocuments: () => { + const stream = through2.obj(); + setImmediate(() => { + stream.push({found: document, readTime: {seconds: 5, nanos: 6}}); + stream.push(null); + }); + + return stream; + }, + }; + + return createInstanceHelper(overrides, opts); +} + +const DOCUMENT_WITH_TIMESTAMP = document('documentId', 'moonLanding', { + timestampValue: { + nanos: 123000123, + seconds: -14182920, + }, +}); + +const DOCUMENT_WITH_EMPTY_TIMESTAMP = document('documentId', 'moonLanding', { + timestampValue: {}, +}); + +describe('timestamps', () => { + it('returned by default', () => { + return createInstance({}, DOCUMENT_WITH_TIMESTAMP).then(firestore => { + const expected = new Firestore.Timestamp(-14182920, 123000123); + return firestore + .doc('collectionId/documentId') + .get() + .then(res => { + expect(res.data()!['moonLanding'].isEqual(expected)).to.be.true; + expect(res.get('moonLanding')!.isEqual(expected)).to.be.true; + }); + }); + }); + + it('retain seconds and nanoseconds', () => { + return createInstance({}, DOCUMENT_WITH_TIMESTAMP).then(firestore => { + return firestore + .doc('collectionId/documentId') + .get() + .then(res => { + const timestamp = res.get('moonLanding'); + expect(timestamp.seconds).to.equal(-14182920); + expect(timestamp.nanoseconds).to.equal(123000123); + }); + }); + }); + + it('convert to date', () => { + return createInstance({}, DOCUMENT_WITH_TIMESTAMP).then(firestore => { + return firestore + .doc('collectionId/documentId') + .get() + .then(res => { + const timestamp = res.get('moonLanding'); + expect(new Date(-14182920 * 1000 + 123).getTime()).to.equal( + timestamp.toDate().getTime(), + ); + }); + }); + }); + + it('convert to millis', () => { + return createInstance({}, DOCUMENT_WITH_TIMESTAMP).then(firestore => { + return firestore + .doc('collectionId/documentId') + .get() + .then(res => { + const timestamp = res.get('moonLanding'); + expect(-14182920 * 1000 + 123).to.equal(timestamp.toMillis()); + }); + }); + }); + + it('support missing values', () => { + return createInstance({}, DOCUMENT_WITH_EMPTY_TIMESTAMP).then(firestore => { + const expected = new Firestore.Timestamp(0, 0); + + return firestore + .doc('collectionId/documentId') + .get() + .then(res => { + expect(res.get('moonLanding').isEqual(expected)).to.be.true; + }); + }); + }); + + it('constructed using helper', () => { + expect(Firestore.Timestamp.now()).to.be.an.instanceOf(Firestore.Timestamp); + + let actual = Firestore.Timestamp.fromDate(new Date(123123)); + let expected = new Firestore.Timestamp(123, 123000000); + expect(actual.isEqual(expected)).to.be.true; + + actual = Firestore.Timestamp.fromMillis(123123); + expected = new Firestore.Timestamp(123, 123000000); + expect(actual.isEqual(expected)).to.be.true; + }); + + it('handles decimal inputs in fromMillis()', () => { + const actual = Firestore.Timestamp.fromMillis(1000.1); + const expected = new Firestore.Timestamp(1, 100000); + expect(actual.isEqual(expected)).to.be.true; + }); + + it('validates seconds', () => { + expect(() => new Firestore.Timestamp(0.1, 0)).to.throw( + 'Value for argument "seconds" is not a valid integer.', + ); + + expect(() => new Firestore.Timestamp(-62135596801, 0)).to.throw( + 'Value for argument "seconds" must be within [-62135596800, 253402300799] inclusive, but was: -62135596801', + ); + + expect(() => new Firestore.Timestamp(253402300800, 0)).to.throw( + 'Value for argument "seconds" must be within [-62135596800, 253402300799] inclusive, but was: 253402300800', + ); + }); + + it('validates nanoseconds', () => { + expect(() => new Firestore.Timestamp(0, 0.1)).to.throw( + 'Value for argument "nanoseconds" is not a valid integer.', + ); + + expect(() => new Firestore.Timestamp(0, -1)).to.throw( + 'Value for argument "nanoseconds" must be within [0, 999999999] inclusive, but was: -1', + ); + + expect(() => new Firestore.Timestamp(0, 1000000000)).to.throw( + 'Value for argument "nanoseconds" must be within [0, 999999999] inclusive, but was: 1000000000', + ); + }); + + it('valueOf', () => { + expect(new Firestore.Timestamp(-62135596677, 456).valueOf()).to.equal( + '000000000123.000000456', + ); + expect(new Firestore.Timestamp(-62135596800, 0).valueOf()).to.equal( + '000000000000.000000000', + ); + expect(new Firestore.Timestamp(253402300799, 1e9 - 1).valueOf()).to.equal( + '315537897599.999999999', + ); + }); + + it('arithmetic comparison of a Timestamp object to itself', () => { + const timestamp = new Firestore.Timestamp(1, 1); + expect(timestamp < timestamp).to.be.false; + expect(timestamp <= timestamp).to.be.true; + expect(timestamp > timestamp).to.be.false; + expect(timestamp >= timestamp).to.be.true; + }); + + it('arithmetic comparison of equivalent, but distinct, Timestamp objects', () => { + const t1 = new Firestore.Timestamp(1, 1); + const t2 = new Firestore.Timestamp(1, 1); + expect(t1 < t2).to.be.false; + expect(t1 <= t2).to.be.true; + expect(t1 > t2).to.be.false; + expect(t1 >= t2).to.be.true; + }); + + it('arithmetic comparison of Timestamp objects whose nanoseconds differ', () => { + const t1 = new Firestore.Timestamp(1, 1); + const t2 = new Firestore.Timestamp(1, 2); + expect(t1 < t2).to.be.true; + expect(t1 <= t2).to.be.true; + expect(t1 > t2).to.be.false; + expect(t1 >= t2).to.be.false; + }); + + it('arithmetic comparison of Timestamp objects whose seconds differ', () => { + const t1 = new Firestore.Timestamp(100, 0); + const t2 = new Firestore.Timestamp(200, 0); + expect(t1 < t2).to.be.true; + expect(t1 <= t2).to.be.true; + expect(t1 > t2).to.be.false; + expect(t1 >= t2).to.be.false; + }); + + it('arithmetic comparison of the smallest and largest Timestamp objects', () => { + const t1 = new Firestore.Timestamp(-62135596800, 0); + const t2 = new Firestore.Timestamp(253402300799, 999999999); + expect(t1 < t2).to.be.true; + expect(t1 <= t2).to.be.true; + expect(t1 > t2).to.be.false; + expect(t1 >= t2).to.be.false; + }); +}); diff --git a/handwritten/firestore/dev/test/tracing.ts b/handwritten/firestore/dev/test/tracing.ts new file mode 100644 index 00000000000..88928fb2e5a --- /dev/null +++ b/handwritten/firestore/dev/test/tracing.ts @@ -0,0 +1,188 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {describe, it} from 'mocha'; +import {createInstance} from './util/helpers'; +import {expect} from 'chai'; +import {DisabledTraceUtil} from '../src/telemetry/disabled-trace-util'; +import {EnabledTraceUtil} from '../src/telemetry/enabled-trace-util'; +import {NodeTracerProvider} from '@opentelemetry/sdk-trace-node'; +import {ProxyTracerProvider, trace} from '@opentelemetry/api'; + +describe('Firestore Tracing Controls', () => { + let originalEnvVarValue: string | undefined; + + beforeEach(() => { + // Remove any prior global OpenTelemetry registrations. + trace.disable(); + originalEnvVarValue = process.env.FIRESTORE_ENABLE_TRACING; + }); + + afterEach(() => { + if (originalEnvVarValue === undefined) { + delete process.env.FIRESTORE_ENABLE_TRACING; + } else { + process.env.FIRESTORE_ENABLE_TRACING = originalEnvVarValue; + } + }); + + it('default firestore settings, no env var', async () => { + const firestore = await createInstance(); + expect(firestore._traceUtil instanceof EnabledTraceUtil).to.be.true; + }); + + /// Tests to make sure environment variable can override settings. + + it('default firestore settings, env var disabled', async () => { + process.env.FIRESTORE_ENABLE_TRACING = 'OFF'; + const firestore = await createInstance(); + expect(firestore._traceUtil instanceof DisabledTraceUtil).to.be.true; + }); + + it('default firestore settings, env var enabled', async () => { + process.env.FIRESTORE_ENABLE_TRACING = 'ON'; + const firestore = await createInstance(); + expect(firestore._traceUtil instanceof EnabledTraceUtil).to.be.true; + }); + + it('no openTelemetry settings, no env var', async () => { + const firestore = await createInstance(undefined, { + openTelemetry: undefined, + }); + expect(firestore._traceUtil instanceof EnabledTraceUtil).to.be.true; + + const firestore2 = await createInstance(undefined, { + openTelemetry: { + tracerProvider: undefined, + }, + }); + expect(firestore2._traceUtil instanceof EnabledTraceUtil).to.be.true; + }); + + it('no openTelemetry settings, env var disabled', async () => { + process.env.FIRESTORE_ENABLE_TRACING = 'OFF'; + const firestore = await createInstance(undefined, { + openTelemetry: undefined, + }); + expect(firestore._traceUtil instanceof DisabledTraceUtil).to.be.true; + + const firestore2 = await createInstance(undefined, { + openTelemetry: { + tracerProvider: undefined, + }, + }); + expect(firestore2._traceUtil instanceof DisabledTraceUtil).to.be.true; + }); + + it('no openTelemetry settings, env var enabled', async () => { + process.env.FIRESTORE_ENABLE_TRACING = 'ON'; + const firestore = await createInstance(undefined, { + openTelemetry: undefined, + }); + expect(firestore._traceUtil instanceof EnabledTraceUtil).to.be.true; + + const firestore2 = await createInstance(undefined, { + openTelemetry: { + tracerProvider: undefined, + }, + }); + expect(firestore2._traceUtil instanceof EnabledTraceUtil).to.be.true; + }); + + it('valid tracerProvider, no env var', async () => { + const firestore = await createInstance(undefined, { + openTelemetry: { + tracerProvider: new NodeTracerProvider(), + }, + }); + expect(firestore._traceUtil instanceof EnabledTraceUtil).to.be.true; + }); + + it('valid tracerProvider, env var disabled', async () => { + process.env.FIRESTORE_ENABLE_TRACING = 'OFF'; + const firestore = await createInstance(undefined, { + openTelemetry: { + tracerProvider: new NodeTracerProvider(), + }, + }); + expect(firestore._traceUtil instanceof DisabledTraceUtil).to.be.true; + }); + + it('valid tracerProvider, env var enabled', async () => { + process.env.FIRESTORE_ENABLE_TRACING = 'ON'; + const firestore = await createInstance(undefined, { + openTelemetry: { + tracerProvider: new NodeTracerProvider(), + }, + }); + expect(firestore._traceUtil instanceof EnabledTraceUtil).to.be.true; + }); + + it('uses the tracerProvider passed to it', async () => { + const myTracerProvider = new NodeTracerProvider(); + + // Make another tracer provider the global tracer provider. + const globalTracerProvider = new NodeTracerProvider(); + globalTracerProvider.register(); + + const firestore = await createInstance(undefined, { + openTelemetry: { + tracerProvider: myTracerProvider, + }, + }); + + expect(firestore._traceUtil instanceof EnabledTraceUtil).to.be.true; + // Make sure the SDK uses the one that was given to it, not the global one. + expect( + (firestore._traceUtil as EnabledTraceUtil).tracerProvider === + myTracerProvider, + ).to.be.true; + expect( + (firestore._traceUtil as EnabledTraceUtil).tracerProvider !== + globalTracerProvider, + ).to.be.true; + }); + + it('uses the global tracerProvider if nothing was passed to it', async () => { + // Make another tracer provider the global tracer provider. + const globalTracerProvider = new NodeTracerProvider(); + globalTracerProvider.register(); + + const firestore = await createInstance(); + + expect(firestore._traceUtil instanceof EnabledTraceUtil).to.be.true; + const enabledTraceUtil: EnabledTraceUtil = + firestore._traceUtil as EnabledTraceUtil; + // Since a TracerProvider is not provided to the SDK directly, the SDK obtains + // the tracer provider from the global `TraceAPI`. The `TraceAPI` returns a + // `ProxyTracerProvider` instance. To check equality, we need to compare our + // `globalTracerProvider` with the proxy's delegate. + const tracerProviderUsed = enabledTraceUtil.tracerProvider; + const actual = (tracerProviderUsed as ProxyTracerProvider).getDelegate(); + expect(actual === globalTracerProvider).to.be.true; + }); + + it('Generates an error if the given tracerProvider is not valid', async () => { + try { + await createInstance(undefined, { + openTelemetry: {tracerProvider: 123}, + }); + } catch (e) { + expect( + e.toString() === + "The object provided for 'tracerProvider' does not conform to the TracerProvider interface.", + ); + } + }); +}); diff --git a/handwritten/firestore/dev/test/transaction.ts b/handwritten/firestore/dev/test/transaction.ts new file mode 100644 index 00000000000..175055ada1b --- /dev/null +++ b/handwritten/firestore/dev/test/transaction.ts @@ -0,0 +1,1217 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {describe, it} from 'mocha'; +import {expect, use} from 'chai'; +import * as chaiAsPromised from 'chai-as-promised'; +import * as extend from 'extend'; +import {GoogleError, Status} from 'google-gax'; +import {Duplex} from 'stream'; +import * as through2 from 'through2'; + +import * as proto from '../protos/firestore_v1_proto_api'; +import * as Firestore from '../src'; +import {DocumentReference, FieldPath, Timestamp, Transaction} from '../src'; +import {setTimeoutHandler} from '../src/backoff'; +import { + ApiOverride, + createInstance, + InvalidApiUsage, + response, + postConverter, + Post, + postConverterMerge, +} from './util/helpers'; + +import api = proto.google.firestore.v1; +import { + ReadOnlyTransactionOptions, + ReadWriteTransactionOptions, +} from '@google-cloud/firestore'; + +use(chaiAsPromised); + +const PROJECT_ID = 'test-project'; +const DATABASE_ROOT = `projects/${PROJECT_ID}/databases/(default)`; +const COLLECTION_ROOT = `${DATABASE_ROOT}/documents/collectionId`; +const DOCUMENT_ID = 'documentId'; +const DOCUMENT_NAME = `${COLLECTION_ROOT}/${DOCUMENT_ID}`; + +// Change the argument to 'console.log' to enable debug output. +Firestore.setLogFunction(null); + +/** Helper to create a transaction ID from either a string or a Uint8Array. */ +function transactionId(transaction: Uint8Array | string): Uint8Array { + if (typeof transaction === 'string') { + return Buffer.from(transaction); + } else { + return transaction; + } +} + +/** + * The format the transaction tests use to verify transaction behavior. The + * format defines an expected request and its expected response or error code. + */ +interface TransactionStep { + type: 'begin' | 'getDocument' | 'query' | 'commit' | 'rollback' | 'backoff'; + delay?: 'exponential' | 'max'; + request?: + | api.ICommitRequest + | api.IBeginTransactionRequest + | api.IRunQueryRequest; + error?: Error; + response?: api.ICommitResponse | api.IBeginTransactionResponse; + stream?: Duplex; +} + +function commit( + transaction: Uint8Array | string | undefined, + writes?: api.IWrite[], + error?: Error, +): TransactionStep { + const proto: api.ICommitRequest = { + database: DATABASE_ROOT, + }; + if (transaction) { + proto.transaction = transactionId(transaction); + } + + proto.writes = writes || []; + + const response: api.ICommitResponse = { + commitTime: { + nanos: 0, + seconds: 0, + }, + writeResults: [], + }; + + for (let i = 0; i < proto.writes!.length; ++i) { + response.writeResults!.push({ + updateTime: { + nanos: 0, + seconds: 0, + }, + }); + } + + return { + type: 'commit', + request: proto, + error, + response, + }; +} + +function rollback( + transaction: Uint8Array | string, + error?: Error, +): TransactionStep { + const proto = { + database: DATABASE_ROOT, + transaction: transactionId(transaction), + }; + + return { + type: 'rollback', + request: proto, + error, + response: {}, + }; +} + +function getAll( + docs: string[], + options?: { + fieldMask?: string[]; + transactionId?: Uint8Array | string; + newTransaction?: { + readOnly?: {readTime?: Timestamp}; + readWrite?: {prevTransactionId?: Uint8Array | string}; + }; + readTime?: Timestamp; + error?: Error; + }, +): TransactionStep { + const request: api.IBatchGetDocumentsRequest = { + database: DATABASE_ROOT, + documents: [], + }; + if (options?.transactionId) { + request.transaction = transactionId(options.transactionId); + } else if (options?.newTransaction?.readWrite) { + request.newTransaction = { + readWrite: options.newTransaction.readWrite.prevTransactionId + ? { + retryTransaction: transactionId( + options.newTransaction.readWrite.prevTransactionId, + ), + } + : {}, + }; + } else if (options?.newTransaction?.readOnly) { + request.newTransaction = { + readOnly: options.newTransaction.readOnly.readTime + ? { + readTime: + options?.newTransaction?.readOnly.readTime.toProto() + .timestampValue, + } + : {}, + }; + } + + if (options?.readTime) { + request.readTime = options.readTime.toProto().timestampValue; + } + if (options?.fieldMask) { + request.mask = {fieldPaths: options.fieldMask}; + } + + const stream = through2.obj(); + + if (options?.newTransaction) { + // Increment transaction ID (e.g. foo1 -> foo2) + // or otherwise send foo1 by default for new transactions + const transactionId = options.newTransaction.readWrite?.prevTransactionId + ? options.newTransaction.readWrite.prevTransactionId.slice(0, -1) + + String( + Number(options.newTransaction.readWrite.prevTransactionId.slice(-1)) + + 1, + ) + : 'foo1'; + setImmediate(() => { + stream.push({ + transaction: Buffer.from(transactionId), + }); + }); + } + + for (const doc of docs) { + const name = `${COLLECTION_ROOT}/${doc}`; + request.documents!.push(name); + + setImmediate(() => { + stream.push({ + found: { + name, + createTime: {seconds: 1, nanos: 2}, + updateTime: {seconds: 3, nanos: 4}, + }, + readTime: {seconds: 5, nanos: 6}, + }); + }); + } + + setImmediate(() => { + if (options?.error) { + stream.destroy(options.error); + } else { + stream.push(null); + } + }); + + return { + type: 'getDocument', + request, + error: options?.error, + stream, + }; +} + +function getDocument(options?: { + document?: string; + transactionId?: Uint8Array | string; + newTransaction?: { + readOnly?: {readTime?: Timestamp}; + readWrite?: {prevTransactionId?: Uint8Array | string}; + }; + readTime?: Timestamp; + error?: Error; +}): TransactionStep { + return getAll([options?.document || DOCUMENT_ID], options); +} + +function query(options?: { + transactionId?: Uint8Array | string; + newTransaction?: { + readOnly?: {readTime?: Timestamp}; + readWrite?: {prevTransactionId?: Uint8Array | string}; + }; + readTime?: Timestamp; + error?: Error; +}): TransactionStep { + const request: api.IRunQueryRequest = { + parent: `${DATABASE_ROOT}/documents`, + structuredQuery: { + from: [ + { + collectionId: 'collectionId', + }, + ], + where: { + fieldFilter: { + field: { + fieldPath: 'foo', + }, + op: 'EQUAL', + value: { + stringValue: 'bar', + }, + }, + }, + }, + }; + if (options?.transactionId) { + request.transaction = transactionId(options.transactionId); + } else if (options?.newTransaction?.readOnly) { + request.newTransaction = { + readOnly: options.newTransaction.readOnly.readTime + ? { + readTime: + options.newTransaction.readOnly.readTime.toProto().timestampValue, + } + : {}, + }; + } else if (options?.newTransaction?.readWrite) { + request.newTransaction = { + readWrite: options.newTransaction.readWrite.prevTransactionId + ? { + retryTransaction: transactionId( + options.newTransaction.readWrite.prevTransactionId, + ), + } + : {}, + }; + } + + if (options?.readTime) { + request.readTime = options.readTime.toProto().timestampValue; + } + + const stream = through2.obj(); + + if (options?.newTransaction) { + // Increment transaction ID (e.g. foo1 -> foo2) + // or otherwise send foo1 by default for new transactions + const transactionId = options.newTransaction.readWrite?.prevTransactionId + ? options.newTransaction.readWrite.prevTransactionId.slice(0, -1) + + String( + Number(options.newTransaction.readWrite.prevTransactionId.slice(-1)) + + 1, + ) + : 'foo1'; + setImmediate(() => { + stream.push({ + transaction: Buffer.from(transactionId), + }); + }); + } + + setImmediate(() => { + // Push a single result even for errored queries, as this avoids implicit + // stream retries. + stream.push({ + document: { + name: DOCUMENT_NAME, + createTime: {seconds: 1, nanos: 2}, + updateTime: {seconds: 3, nanos: 4}, + }, + readTime: {seconds: 5, nanos: 6}, + }); + + if (options?.error) { + stream.destroy(options.error); + } else { + stream.push(null); + } + }); + + return { + type: 'query', + request, + stream, + }; +} + +function backoff(maxDelay?: boolean): TransactionStep { + return { + type: 'backoff', + delay: maxDelay ? 'max' : 'exponential', + }; +} + +/** + * Asserts that the given transaction function issues the expected requests. + */ +function runTransaction( + transactionOptions: ReadWriteTransactionOptions | ReadOnlyTransactionOptions, + transactionCallback: ( + transaction: Transaction, + docRef: DocumentReference, + ) => Promise, + ...expectedRequests: TransactionStep[] +) { + const overrides: ApiOverride = { + beginTransaction: () => { + // Transactions are lazily started upon first read so the beginTransaction + // API should never be called + expect.fail('beginTransaction was called'); + }, + commit: (actual, options) => { + // Ensure that we do not specify custom retry behavior for transactional + // commits. + expect(options!.retry).to.be.undefined; + + const request = expectedRequests.shift()!; + expect(request.type).to.equal('commit'); + expect(actual).to.deep.eq(request.request); + if (request.error) { + return Promise.reject(request.error); + } else { + return response(request.response as api.ICommitResponse); + } + }, + rollback: actual => { + const request = expectedRequests.shift()!; + expect(request.type).to.equal('rollback'); + expect(actual).to.deep.eq(request.request); + if (request.error) { + return Promise.reject(request.error); + } else { + return response({}); + } + }, + batchGetDocuments: actual => { + const request = expectedRequests.shift()!; + expect(request.type).to.equal('getDocument'); + expect(actual).to.deep.eq(request.request); + return request.stream!; + }, + runQuery: actual => { + const request = expectedRequests.shift()!; + expect(request.type).to.equal('query'); + actual = extend(true, {}, actual); // Remove undefined properties + expect(actual).to.deep.eq(request.request); + return request.stream!; + }, + }; + + return createInstance(overrides).then(async firestore => { + try { + setTimeoutHandler((callback, timeout) => { + if (timeout > 0) { + const request = expectedRequests.shift()!; + expect(request.type).to.equal('backoff'); + if (request.delay === 'max') { + // Make sure that the delay is at least 30 seconds, which is based + // on the maximum delay of 60 seconds and a jitter factor of 50%. + expect(timeout).to.not.be.lessThan(30 * 1000); + } + } + callback(); + }); + + return await firestore.runTransaction(transaction => { + const docRef = firestore.doc('collectionId/documentId'); + return transactionCallback(transaction, docRef); + }, transactionOptions); + } finally { + setTimeoutHandler(setTimeout); + expect(expectedRequests.length).to.equal( + 0, + 'Missing requests: ' + expectedRequests.map(r => r.type).join(', '), + ); + } + }); +} + +describe('successful transactions', () => { + it('empty transaction', () => { + return runTransaction(/* transactionOptions= */ {}, () => { + return Promise.resolve(); + }); + }); + + it('returns value', () => { + return runTransaction(/* transactionOptions= */ {}, () => { + return Promise.resolve('bar'); + }).then(val => { + expect(val).to.equal('bar'); + }); + }); +}); + +describe('failed transactions', () => { + const retryBehavior: {[code: number]: boolean} = { + [Status.CANCELLED]: true, + [Status.UNKNOWN]: true, + [Status.INVALID_ARGUMENT]: false, + [Status.DEADLINE_EXCEEDED]: true, + [Status.NOT_FOUND]: false, + [Status.ALREADY_EXISTS]: false, + [Status.RESOURCE_EXHAUSTED]: true, + [Status.FAILED_PRECONDITION]: false, + [Status.ABORTED]: true, + [Status.OUT_OF_RANGE]: false, + [Status.UNIMPLEMENTED]: false, + [Status.INTERNAL]: true, + [Status.UNAVAILABLE]: true, + [Status.DATA_LOSS]: false, + [Status.UNAUTHENTICATED]: true, + }; + + it('retries commit based on error code', async () => { + // The transaction needs to perform a read or write otherwise it will be + // a no-op and will not retry + const transactionFunction = async ( + trans: Transaction, + ref: DocumentReference, + ) => { + await trans.get(ref); + }; + + for (const [errorCode, retry] of Object.entries(retryBehavior)) { + const serverError = new GoogleError('Test Error'); + serverError.code = Number(errorCode) as Status; + + if (retry) { + await runTransaction( + /* transactionOptions= */ {}, + transactionFunction, + getDocument({newTransaction: {readWrite: {}}}), + commit('foo1', undefined, serverError), + rollback('foo1'), + backoff(), + getDocument({ + newTransaction: {readWrite: {prevTransactionId: 'foo1'}}, + }), + commit('foo2'), + ); + } else { + await expect( + runTransaction( + /* transactionOptions= */ {}, + transactionFunction, + getDocument({newTransaction: {readWrite: {}}}), + commit('foo1', undefined, serverError), + rollback('foo1'), + ), + ).to.eventually.be.rejected; + } + } + }); + + it('retries commit for expired transaction', async () => { + // The transaction needs to perform a read or write otherwise it will be + // a no-op and will not retry + const transactionFunction = async ( + trans: Transaction, + ref: DocumentReference, + ) => { + await trans.get(ref); + }; + + const serverError = new GoogleError( + 'The referenced transaction has expired or is no longer valid.', + ); + serverError.code = Status.INVALID_ARGUMENT; + + await runTransaction( + /* transactionOptions= */ {}, + transactionFunction, + getDocument({newTransaction: {readWrite: {}}}), + commit('foo1', undefined, serverError), + rollback('foo1'), + backoff(), + getDocument({newTransaction: {readWrite: {prevTransactionId: 'foo1'}}}), + commit('foo2'), + ); + }); + + it('retries runQuery based on error code', async () => { + const transactionFunction = ( + transaction: Transaction, + docRef: DocumentReference, + ) => { + const query = docRef.parent.where('foo', '==', 'bar'); + return transaction.get(query); + }; + + for (const [errorCode, retry] of Object.entries(retryBehavior)) { + const serverError = new GoogleError('Test Error'); + serverError.code = Number(errorCode) as Status; + + if (retry) { + await runTransaction( + /* transactionOptions= */ {}, + transactionFunction, + query({newTransaction: {readWrite: {}}, error: serverError}), + // No rollback because the lazy-start operation failed + backoff(), + query({newTransaction: {readWrite: {}}}), + commit('foo1'), + ); + } else { + await expect( + runTransaction( + /* transactionOptions= */ {}, + transactionFunction, + query({newTransaction: {readWrite: {}}, error: serverError}), + // No rollback because the lazy-start operation failed + ), + ).to.eventually.be.rejected; + } + } + }); + + it('retries batchGetDocuments based on error code', async () => { + const transactionFunction = ( + transaction: Transaction, + docRef: DocumentReference, + ) => { + return transaction.get(docRef); + }; + + for (const [errorCode, retry] of Object.entries(retryBehavior)) { + const serverError = new GoogleError('Test Error'); + serverError.code = Number(errorCode) as Status; + + if (retry) { + await runTransaction( + /* transactionOptions= */ {}, + transactionFunction, + getDocument({newTransaction: {readWrite: {}}, error: serverError}), + // No rollback because the lazy-start operation failed + backoff(), + getDocument({newTransaction: {readWrite: {}}}), + commit('foo1'), + ); + } else { + await expect( + runTransaction( + /* transactionOptions= */ {}, + transactionFunction, + getDocument({newTransaction: {readWrite: {}}, error: serverError}), + // No rollback because the lazy-start operation failed + ), + ).to.eventually.be.rejected; + } + } + }); + + it('retries rollback based on error code', async () => { + const transactionFunction = async ( + trans: Transaction, + doc: DocumentReference, + ) => { + await trans.get(doc); + }; + + for (const [errorCode, retry] of Object.entries(retryBehavior)) { + const serverError = new GoogleError('Test Error'); + serverError.code = Number(errorCode) as Status; + + if (retry) { + await runTransaction( + /* transactionOptions= */ {}, + transactionFunction, + getDocument({newTransaction: {readWrite: {}}}), + commit('foo1', /* writes=*/ undefined, serverError), + rollback('foo1', serverError), + backoff(), + getDocument({ + newTransaction: {readWrite: {prevTransactionId: 'foo1'}}, + }), + commit('foo2'), + ); + } else { + await expect( + runTransaction( + /* transactionOptions= */ {}, + transactionFunction, + getDocument({newTransaction: {readWrite: {}}}), + commit('foo1', /* writes=*/ undefined, serverError), + rollback('foo1', serverError), + ), + ).to.eventually.be.rejected; + } + } + }); + + it('requires update function', () => { + const overrides: ApiOverride = { + beginTransaction: () => Promise.reject(), + }; + + return createInstance(overrides).then(firestore => { + expect(() => (firestore as InvalidApiUsage).runTransaction()).to.throw( + 'Value for argument "updateFunction" is not a valid function.', + ); + }); + }); + + it('requires valid retry number', () => { + const overrides: ApiOverride = { + beginTransaction: () => Promise.reject(), + }; + + return createInstance(overrides).then(firestore => { + expect(() => + firestore.runTransaction(() => Promise.resolve(), { + maxAttempts: 'foo' as InvalidApiUsage, + }), + ).to.throw( + 'Value for argument "transactionOptions.maxAttempts" is not a valid integer.', + ); + + expect(() => + firestore.runTransaction(() => Promise.resolve(), {maxAttempts: 0}), + ).to.throw( + 'Value for argument "transactionOptions.maxAttempts" must be within [1, Infinity] inclusive, but was: 0', + ); + }); + }); + + it('requires a promise', () => { + return expect( + runTransaction( + /* transactionOptions= */ {}, + (() => {}) as InvalidApiUsage, + ), + ).to.eventually.be.rejectedWith( + 'You must return a Promise in your transaction()-callback.', + ); + }); + + it('handles exception', () => { + return createInstance().then(firestore => { + firestore.requestStream = () => { + return Promise.reject(new Error('Expected exception')); + }; + + return expect( + firestore.runTransaction(async trans => { + // Need to perform a read or write otherwise transaction is a no-op + // with zero requests + await trans.get(firestore.doc('collectionId/documentId')); + }), + ).to.eventually.be.rejectedWith('Expected exception'); + }); + }); + + it("doesn't retry custom user exceptions in callback", () => { + return expect( + runTransaction(/* transactionOptions= */ {}, () => { + return Promise.reject('request exception'); + }), + ).to.eventually.be.rejectedWith('request exception'); + }); + + it('limits the retry attempts', () => { + const err = new GoogleError('Server disconnect'); + err.code = Status.UNAVAILABLE; + + return expect( + runTransaction( + /* transactionOptions= */ {}, + (trans, doc) => trans.get(doc), + getDocument({newTransaction: {readWrite: {}}}), + commit('foo1', [], err), + rollback('foo1'), + backoff(), + getDocument({newTransaction: {readWrite: {prevTransactionId: 'foo1'}}}), + commit('foo2', [], err), + rollback('foo2'), + backoff(), + getDocument({newTransaction: {readWrite: {prevTransactionId: 'foo2'}}}), + commit('foo3', [], err), + rollback('foo3'), + backoff(), + getDocument({newTransaction: {readWrite: {prevTransactionId: 'foo3'}}}), + commit('foo4', [], err), + rollback('foo4'), + backoff(), + getDocument({newTransaction: {readWrite: {prevTransactionId: 'foo4'}}}), + commit('foo5', [], new Error('Final exception')), + rollback('foo5'), + ), + ).to.eventually.be.rejectedWith('Final exception'); + }); + + it('uses maximum backoff for RESOURCE_EXHAUSTED', () => { + const err = new GoogleError('Server disconnect'); + err.code = Status.RESOURCE_EXHAUSTED; + + return runTransaction( + /* transactionOptions= */ {}, + (trans, doc) => trans.get(doc), + getDocument({newTransaction: {readWrite: {}}}), + commit('foo1', [], err), + rollback('foo1'), + backoff(/* maxDelay= */ true), + getDocument({newTransaction: {readWrite: {prevTransactionId: 'foo1'}}}), + commit('foo2'), + ); + }); +}); + +describe('transaction operations', () => { + it('support get with document ref', () => { + return runTransaction( + /* transactionOptions= */ {}, + (transaction, docRef) => { + return transaction.get(docRef).then(doc => { + expect(doc.id).to.equal('documentId'); + }); + }, + getDocument({newTransaction: {readWrite: {}}}), + commit('foo1'), + ); + }); + + it('requires a query or document for get', () => { + return runTransaction( + /* transactionOptions= */ {}, + (transaction: InvalidApiUsage) => { + expect(() => transaction.get()).to.throw( + 'Value for argument "refOrQuery" must be a DocumentReference, Query, or AggregateQuery.', + ); + + expect(() => transaction.get('foo')).to.throw( + 'Value for argument "refOrQuery" must be a DocumentReference, Query, or AggregateQuery.', + ); + + return Promise.resolve(); + }, + ); + }); + + it('enforce that gets come before writes', () => { + return expect( + runTransaction(/* transactionOptions= */ {}, (transaction, docRef) => { + transaction.set(docRef, {foo: 'bar'}); + return transaction.get(docRef); + }), + ).to.eventually.be.rejectedWith( + 'Firestore transactions require all reads to be executed before all writes.', + ); + }); + + it('enforce read-only cannot write', () => { + return expect( + runTransaction( + /* transactionOptions= */ {readOnly: true}, + async (transaction, docRef) => { + transaction.set(docRef, {foo: 'bar'}); + }, + ), + ).to.eventually.be.rejectedWith( + 'Firestore read-only transactions cannot execute writes.', + ); + }); + + it('enforce read-only with readTime cannot write', () => { + return expect( + runTransaction( + /* transactionOptions= */ { + readOnly: true, + readTime: Timestamp.fromMillis(3), + }, + async (transaction, docRef) => { + transaction.set(docRef, {foo: 'bar'}); + }, + ), + ).to.eventually.be.rejectedWith( + 'Firestore read-only transactions cannot execute writes.', + ); + }); + + it('support get with query', () => { + return runTransaction( + /* transactionOptions= */ {}, + (transaction, docRef) => { + const query = docRef.parent.where('foo', '==', 'bar'); + return transaction.get(query).then(results => { + expect(results.docs[0].id).to.equal('documentId'); + }); + }, + query({newTransaction: {readWrite: {}}}), + commit('foo1'), + ); + }); + + it('supports read-only transactions', () => { + return runTransaction( + {readOnly: true}, + (transaction, docRef) => transaction.get(docRef), + getDocument({newTransaction: {readOnly: {}}}), + ); + }); + + it('supports get read-only transactions with read time', () => { + return runTransaction( + { + readOnly: true, + readTime: Timestamp.fromMillis(1), + }, + (transaction, docRef) => transaction.get(docRef), + getDocument({readTime: Timestamp.fromMillis(1)}), + ); + }); + + it('support query read-only transactions with read time', () => { + return runTransaction( + { + readOnly: true, + readTime: Timestamp.fromMillis(2), + }, + (transaction, docRef) => { + const query = docRef.parent.where('foo', '==', 'bar'); + return transaction.get(query).then(results => { + expect(results.docs[0].id).to.equal('documentId'); + }); + }, + query({readTime: Timestamp.fromMillis(2)}), + ); + }); + + it('support getAll', () => { + return runTransaction( + /* transactionOptions= */ {}, + (transaction, docRef) => { + const firstDoc = docRef.parent.doc('firstDocument'); + const secondDoc = docRef.parent.doc('secondDocument'); + + return transaction.getAll(firstDoc, secondDoc).then(docs => { + expect(docs.length).to.equal(2); + expect(docs[0].id).to.equal('firstDocument'); + expect(docs[1].id).to.equal('secondDocument'); + }); + }, + getAll(['firstDocument', 'secondDocument'], { + newTransaction: {readWrite: {}}, + }), + commit('foo1'), + ); + }); + + it('support getAll with field mask', () => { + return runTransaction( + /* transactionOptions= */ {}, + (transaction, docRef) => { + const doc = docRef.parent.doc('doc'); + + return transaction.getAll(doc, { + fieldMask: ['a.b', new FieldPath('a.b')], + }); + }, + getAll(['doc'], { + newTransaction: {readWrite: {}}, + fieldMask: ['a.b', '`a.b`'], + }), + commit('foo1'), + ); + }); + + it('enforce that getAll come before writes', () => { + return expect( + runTransaction(/* transactionOptions= */ {}, (transaction, docRef) => { + transaction.set(docRef, {foo: 'bar'}); + return transaction.getAll(docRef); + }), + ).to.eventually.be.rejectedWith( + 'Firestore transactions require all reads to be executed before all writes.', + ); + }); + + it('subsequent reads use transaction ID from initial read for read-write transaction', () => { + return runTransaction( + /* transactionOptions= */ {}, + async (transaction, docRef) => { + const firstDoc = docRef.parent.doc('firstDocument'); + const secondDoc = docRef.parent.doc('secondDocument'); + const query = docRef.parent.where('foo', '==', 'bar'); + + // Reads in parallel + await Promise.all([ + transaction.get(firstDoc).then(doc => { + expect(doc.id).to.equal('firstDocument'); + }), + transaction.get(secondDoc).then(doc => { + expect(doc.id).to.equal('secondDocument'); + }), + transaction.get(query).then(results => { + expect(results.docs[0].id).to.equal('documentId'); + }), + ]); + + // Sequential reads + const thirdDoc = docRef.parent.doc('thirdDocument'); + const doc = await transaction.get(thirdDoc); + expect(doc.id).to.equal('thirdDocument'); + + await transaction.get(query).then(results => { + expect(results.docs[0].id).to.equal('documentId'); + }); + }, + getDocument({newTransaction: {readWrite: {}}, document: 'firstDocument'}), + getDocument({transactionId: 'foo1', document: 'secondDocument'}), + query({transactionId: 'foo1'}), + getDocument({transactionId: 'foo1', document: 'thirdDocument'}), + query({transactionId: 'foo1'}), + commit('foo1'), + ); + }); + + it('subsequent reads use transaction ID from initial read for read-only transaction', () => { + return runTransaction( + /* transactionOptions= */ {readOnly: true}, + async (transaction, docRef) => { + const firstDoc = docRef.parent.doc('firstDocument'); + const secondDoc = docRef.parent.doc('secondDocument'); + const query = docRef.parent.where('foo', '==', 'bar'); + + // Reads in parallel + await Promise.all([ + transaction.get(firstDoc).then(doc => { + expect(doc.id).to.equal('firstDocument'); + }), + transaction.get(secondDoc).then(doc => { + expect(doc.id).to.equal('secondDocument'); + }), + transaction.get(query).then(results => { + expect(results.docs[0].id).to.equal('documentId'); + }), + ]); + + // Sequential reads + const thirdDoc = docRef.parent.doc('thirdDocument'); + const doc = await transaction.get(thirdDoc); + expect(doc.id).to.equal('thirdDocument'); + + await transaction.get(query).then(results => { + expect(results.docs[0].id).to.equal('documentId'); + }); + }, + getDocument({newTransaction: {readOnly: {}}, document: 'firstDocument'}), + getDocument({transactionId: 'foo1', document: 'secondDocument'}), + query({transactionId: 'foo1'}), + getDocument({transactionId: 'foo1', document: 'thirdDocument'}), + query({transactionId: 'foo1'}), + ); + }); + + it('support create', () => { + const create = { + currentDocument: { + exists: false, + }, + update: { + fields: {}, + name: DOCUMENT_NAME, + }, + }; + + return runTransaction( + /* transactionOptions= */ {}, + (transaction, docRef) => { + transaction.create(docRef, {}); + return Promise.resolve(); + }, + commit(undefined, [create]), + ); + }); + + it('support update', () => { + const update = { + currentDocument: { + exists: true, + }, + update: { + fields: { + a: { + mapValue: { + fields: { + b: { + stringValue: 'c', + }, + }, + }, + }, + }, + name: DOCUMENT_NAME, + }, + updateMask: { + fieldPaths: ['a.b'], + }, + }; + + return runTransaction( + /* transactionOptions= */ {}, + (transaction, docRef) => { + transaction.update(docRef, {'a.b': 'c'}); + transaction.update(docRef, 'a.b', 'c'); + transaction.update(docRef, new Firestore.FieldPath('a', 'b'), 'c'); + return Promise.resolve(); + }, + commit(undefined, [update, update, update]), + ); + }); + + it('support set', () => { + const set = { + update: { + fields: { + 'a.b': { + stringValue: 'c', + }, + }, + name: DOCUMENT_NAME, + }, + }; + + return runTransaction( + /* transactionOptions= */ {}, + (transaction, docRef) => { + transaction.set(docRef, {'a.b': 'c'}); + return Promise.resolve(); + }, + commit(undefined, [set]), + ); + }); + + it('support set with merge', () => { + const set = { + update: { + fields: { + 'a.b': { + stringValue: 'c', + }, + }, + name: DOCUMENT_NAME, + }, + updateMask: { + fieldPaths: ['`a.b`'], + }, + }; + + return runTransaction( + /* transactionOptions= */ {}, + (transaction, docRef) => { + transaction.set(docRef, {'a.b': 'c'}, {merge: true}); + return Promise.resolve(); + }, + commit(undefined, [set]), + ); + }); + + it('support set with partials and merge', () => { + const set = { + update: { + fields: { + title: { + stringValue: 'story', + }, + }, + name: DOCUMENT_NAME, + }, + updateMask: { + fieldPaths: ['title'], + }, + }; + + return runTransaction( + /* transactionOptions= */ {}, + (transaction, docRef) => { + const postRef = docRef.withConverter(postConverterMerge); + transaction.set(postRef, {title: 'story'} as Partial, { + merge: true, + }); + return Promise.resolve(); + }, + commit(undefined, [set]), + ); + }); + + it('support set with partials and mergeFields', () => { + const set = { + update: { + fields: { + title: { + stringValue: 'story', + }, + }, + name: DOCUMENT_NAME, + }, + updateMask: { + fieldPaths: ['title'], + }, + }; + + return runTransaction( + /* transactionOptions= */ {}, + (transaction, docRef) => { + const postRef = docRef.withConverter(postConverter); + transaction.set( + postRef, + {title: 'story', author: 'person'} as Partial, + { + mergeFields: ['title'], + }, + ); + return Promise.resolve(); + }, + commit(undefined, [set]), + ); + }); + + it('support delete', () => { + const remove = { + delete: DOCUMENT_NAME, + }; + + return runTransaction( + /* transactionOptions= */ {}, + (transaction, docRef) => { + transaction.delete(docRef); + return Promise.resolve(); + }, + commit(undefined, [remove]), + ); + }); + + it('support multiple writes', () => { + const remove = { + delete: DOCUMENT_NAME, + }; + + const set = { + update: { + fields: {}, + name: DOCUMENT_NAME, + }, + }; + + return runTransaction( + /* transactionOptions= */ {}, + (transaction, docRef) => { + transaction.delete(docRef).set(docRef, {}); + return Promise.resolve(); + }, + commit(undefined, [remove, set]), + ); + }); +}); diff --git a/handwritten/firestore/dev/test/types.ts b/handwritten/firestore/dev/test/types.ts new file mode 100644 index 00000000000..92307ef9c47 --- /dev/null +++ b/handwritten/firestore/dev/test/types.ts @@ -0,0 +1,1125 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { + QueryDocumentSnapshot, + DocumentReference, + WithFieldValue, + DocumentData, + PartialWithFieldValue, + FirestoreDataConverter, + SetOptions, + UpdateData, + Firestore, +} from '@google-cloud/firestore'; +import {expect} from 'chai'; + +describe('FirestoreTypeConverter', () => { + it('converter has the minimal typing information', () => { + interface MyModelType { + stringProperty: string; + numberProperty: number; + } + const converter = { + toFirestore(obj: MyModelType) { + return {a: obj.stringProperty, b: obj.numberProperty}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot) { + return { + stringProperty: snapshot.data().a, + numberProperty: snapshot.data().b, + }; + }, + }; + neverCall>(async docRef => { + const newDocRef = docRef.withConverter(converter); + await newDocRef.set({stringProperty: 'foo', numberProperty: 42}); + await newDocRef.update({a: 'newFoo', b: 43}); + const snapshot = await newDocRef.get(); + return snapshot.data()!; + }); + }); + + it('converter has the minimal typing information plus return types', () => { + interface MyModelType { + stringProperty: string; + numberProperty: number; + } + const converter = { + toFirestore(obj: WithFieldValue): DocumentData { + return {a: obj.stringProperty, b: obj.numberProperty}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): MyModelType { + return { + stringProperty: snapshot.data().a, + numberProperty: snapshot.data().b, + }; + }, + }; + neverCall>(async docRef => { + const newDocRef = docRef.withConverter(converter); + await newDocRef.set({stringProperty: 'foo', numberProperty: 42}); + await newDocRef.update({a: 'newFoo', b: 43}); + const snapshot = await newDocRef.get(); + return snapshot.data()!; + }); + }); + + it("has the additional 'merge' version of toFirestore()", () => { + interface MyModelType { + stringProperty: string; + numberProperty: number; + } + const converter: FirestoreDataConverter = { + toFirestore( + modelObject: PartialWithFieldValue, + options?: SetOptions, + ): DocumentData { + if (options === undefined) { + return { + a: modelObject.stringProperty, + b: modelObject.numberProperty, + }; + } + const result: DocumentData = {}; + if ('stringProperty' in modelObject) { + result.a = modelObject.stringProperty; + } + if ('numberProperty' in modelObject) { + result.b = modelObject.numberProperty; + } + return result; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): MyModelType { + return { + stringProperty: snapshot.data().a, + numberProperty: snapshot.data().b, + }; + }, + }; + neverCall>(async docRef => { + const newDocRef = docRef.withConverter(converter); + await newDocRef.set({stringProperty: 'foo', numberProperty: 42}); + await newDocRef.update({a: 'newFoo', b: 43}); + const snapshot = await newDocRef.get(); + return snapshot.data()!; + }); + }); + + it('converter is explicitly typed as FirestoreDataConverter', () => { + interface MyModelType { + stringProperty: string; + numberProperty: number; + } + const converter: FirestoreDataConverter = { + toFirestore(obj: WithFieldValue) { + return {a: obj.stringProperty, b: obj.numberProperty}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot) { + return { + stringProperty: snapshot.data().a, + numberProperty: snapshot.data().b, + }; + }, + }; + neverCall>(async docRef => { + const newDocRef = docRef.withConverter(converter); + await newDocRef.set({stringProperty: 'foo', numberProperty: 42}); + await newDocRef.update({a: 'newFoo', b: 43}); + const snapshot = await newDocRef.get(); + return snapshot.data()!; + }); + }); + + it('converter is explicitly typed as FirestoreDataConverter', () => { + interface MyModelType { + stringProperty: string; + numberProperty: number; + } + interface MyDbType { + a: string; + b: number; + } + const converter: FirestoreDataConverter = { + toFirestore(obj: WithFieldValue) { + return {a: obj.stringProperty, b: obj.numberProperty}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot) { + return { + stringProperty: snapshot.data().a, + numberProperty: snapshot.data().b, + }; + }, + }; + neverCall>(async docRef => { + const newDocRef = docRef.withConverter(converter); + await newDocRef.set({stringProperty: 'foo', numberProperty: 42}); + await newDocRef.update({a: 'newFoo', b: 43}); + const snapshot = await newDocRef.get(); + return snapshot.data()!; + }); + }); + + it('DocumentReference.set() fails to compile if AppModelType argument is missing properties', () => + neverCall(async docRef => { + const converter = fakeConverter<{foo: string}, {}>(); + const docRefWithConverter = docRef.withConverter(converter); + // @ts-expect-error The `foo` property declared in AppModelType is missing. + await docRefWithConverter.set({}); + })); + + it('DocumentReference.set() fails to compile if AppModelType argument contains undeclared properties', () => + neverCall(async docRef => { + const converter = fakeConverter<{foo: string}, {bar: number}>(); + const docRefWithConverter = docRef.withConverter(converter); + // @ts-expect-error The `bar` property is not declared in AppModelType. + await docRefWithConverter.set({foo: 'foo', bar: 42}); + })); + + it('DocumentReference.set() fails to compile if AppModelType argument contains a property with an incorrect type', () => + neverCall(async docRef => { + const converter = fakeConverter<{foo: string}, {foo: number}>(); + const docRefWithConverter = docRef.withConverter(converter); + // @ts-expect-error The `foo` property is declared as `string` in + // AppModelType, but a `number` is specified. + await docRefWithConverter.set({foo: 42}); + })); + + it('DocumentReference.update() successfully compiles even if DbModelType argument is missing properties', () => + neverCall(async docRef => { + const converter = fakeConverter<{foo: string}, {bar: number}>(); + const docRefWithConverter = docRef.withConverter(converter); + await docRefWithConverter.update({}); + })); + + it('DocumentReference.update() fails to compile if DbModelType argument contains undeclared properties', () => + neverCall(async docRef => { + const converter = fakeConverter<{foo: string}, {bar: number}>(); + const docRefWithConverter = docRef.withConverter(converter); + // @ts-expect-error The `foo` property is not declared in DbModelType. + await docRefWithConverter.update({foo: 'foo', bar: 42}); + })); + + it('DocumentReference.update() fails to compile if DbModelType argument contains a property with an incorrect type', () => + neverCall(async docRef => { + const converter = fakeConverter<{foo: string}, {foo: number}>(); + const docRefWithConverter = docRef.withConverter(converter); + // @ts-expect-error The `foo` property is declared as `number` in + // DbModelType, but a `string` is specified. + await docRefWithConverter.update({foo: 'foo'}); + })); + + it('DocumentReference.get() returns AppModelType', () => + neverCall>(async docRef => { + const converter = fakeConverter<{foo: string}, {bar: number}>(); + const docRefWithConverter = docRef.withConverter(converter); + const snapshot = await docRefWithConverter.get(); + return snapshot.data()!; + })); +}); + +describe('WithFieldValue', () => { + it('does not affect functions on types', () => { + type SampleType = { + bar: string; + foo: () => void; + }; + /* eslint-disable @typescript-eslint/no-unused-vars */ + function test(x: WithFieldValue) { + // @ts-expect-error This should fail because x.bar is type `string | FieldValue` + const b: string = x.bar; + + // ASSERT: if WithFieldValue applies FieldValue | K[T] + // to methods on the type, then this line will not compile + const f: () => void = x.foo; + } + /* eslint-enable @typescript-eslint/no-unused-vars */ + }); +}); + +describe('PartialWithFieldValue', () => { + it('does not affect functions on types', () => { + type SampleType = { + bar: string; + foo: () => void; + }; + /* eslint-disable @typescript-eslint/no-unused-vars */ + function test(x: PartialWithFieldValue) { + // @ts-expect-error This should fail because x.bar is type `string | FieldValue` + const b: string = x.bar; + + // ASSERT: if WithFieldValue applies FieldValue | K[T] + // to methods on the type, then this line will not compile + const f: undefined | (() => void) = x.foo; + } + /* eslint-enable @typescript-eslint/no-unused-vars */ + }); +}); + +// A union type for testing +type MyUnionType = string | number; + +// An object type for testing +type MyObjectType = { + booleanProperty: boolean; + stringProperty: string; + numberProperty: number; + nullProperty: null; + undefinedProperty: undefined; + unionProperty: MyUnionType; + objectProperty: { + booleanProperty: boolean; + stringProperty: string; + }; +}; + +describe('UpdateData type', () => { + /* eslint-disable @typescript-eslint/no-unused-vars */ + interface MyServerType { + // primitive types + booleanProperty: boolean; + stringProperty: string; + numberProperty: number; + nullProperty: null; + undefinedProperty: undefined; + + // custom types + unionProperty: MyUnionType; + objectProperty: MyObjectType; + + // nested objects + nested: { + bar: { + barBooleanProperty: boolean; + barStringProperty: string; + barAnotherLayer: { + baralBooleanProperty: boolean; + baralStringProperty: string; + }; + }; + baz: { + bazBooleanProperty: boolean; + bazStringProperty: string; + bazAnotherLayer: { + bazalBooleanProperty: boolean; + bazalStringProperty: string; + }; + }; + }; + + // index signatures nested 1 layer deep + indexed: { + [name: string]: { + nameBooleanProperty: boolean; + nameNumberProperty: number; + }; + }; + + // property with dots in the name + 'property.with.dots': boolean; + } + + it('Supports properties with primitive types', () => { + let _: UpdateData; + _ = { + booleanProperty: true, + stringProperty: 'string', + numberProperty: 2, + nullProperty: null, + undefinedProperty: undefined, + }; + + _ = { + // @ts-expect-error Unsupported type + booleanProperty: 'string', + // @ts-expect-error Unsupported type + stringProperty: 1, + // @ts-expect-error Unsupported type + numberProperty: 'string', + // @ts-expect-error Unsupported type + nullProperty: 'string', + // @ts-expect-error Unsupported type + undefinedProperty: 'string', + }; + + expect(true).to.be.true; + }); + + it('Supports properties with custom types', () => { + let _: UpdateData; + _ = { + unionProperty: 'string', + objectProperty: { + booleanProperty: true, + stringProperty: 'string', + numberProperty: 2, + nullProperty: null, + undefinedProperty: undefined, + unionProperty: 1, + }, + }; + + _ = { + // @ts-expect-error Unsupported type + unionProperty: true, + + // @ts-expect-error Unsupported type + objectProperty: true, + }; + + _ = { + objectProperty: { + // @ts-expect-error Unsupported type + booleanProperty: 'string', + // @ts-expect-error Unsupported type + stringProperty: 1, + // @ts-expect-error Unsupported type + numberProperty: 'string', + // @ts-expect-error Unsupported type + nullProperty: 'string', + // @ts-expect-error Unsupported type + undefinedProperty: 'string', + }, + }; + + expect(true).to.be.true; + }); + + describe('given properties with dots', () => { + it('preserves the value type', () => { + let _: UpdateData; + + // Allows values of expected type + _ = { + 'property.with.dots': true, + }; + + // Errors on values of unexpected type + _ = { + // @ts-expect-error Unsupported type + 'property.with.dots': 1, + }; + + expect(true).to.be.true; + }); + + it('does not allow matching a sub-string|path', () => { + const _: UpdateData = { + // @ts-expect-error Unsupported name + 'property.with': true, + }; + + expect(true).to.be.true; + }); + }); + + describe('given nested objects without index properties', () => { + it('supports object replacement at each layer (with partial)', () => { + let _: UpdateData; + _ = { + nested: {}, + }; + + _ = { + nested: { + bar: {}, + baz: {}, + }, + }; + + _ = { + nested: { + bar: { + barBooleanProperty: true, + barStringProperty: 'string', + }, + baz: { + bazStringProperty: 'string', + }, + }, + }; + + _ = { + nested: { + bar: { + barBooleanProperty: true, + barStringProperty: 'string', + barAnotherLayer: { + baralBooleanProperty: false, + baralStringProperty: 'another string', + }, + }, + }, + }; + + expect(true).to.be.true; + }); + + it('errors for unexpected value types at each layer', () => { + let _: UpdateData; + _ = { + // @ts-expect-error Unsupported type + nested: true, + }; + + _ = { + nested: { + bar: { + // @ts-expect-error Unsupported type + barStringProperty: true, + // @ts-expect-error Unsupported type + barAnotherLayer: true, + x: true, + }, + baz: { + bazAnotherLayer: { + // @ts-expect-error Unsupported type + bazalBooleanProperty: 'string value', + }, + }, + }, + }; + + expect(true).to.be.true; + }); + + it('does not allow properties that were not on the original type', () => { + let _: UpdateData; + _ = { + // @ts-expect-error Unsupported name + unknown: true, + }; + + _ = { + nested: { + // @ts-expect-error Unsupported type + unknown: true, + }, + }; + + expect(true).to.be.true; + }); + + it('preserves value types for dot notation', () => { + let _: UpdateData; + + // 2 layers with dot notation + + // preserves type + _ = { + 'nested.bar': {}, + 'nested.baz': {}, + }; + + // preserves properties of nested objects referenced + // with dot notation + _ = { + 'nested.bar': { + barBooleanProperty: true, + barStringProperty: 'string', + barAnotherLayer: { + baralBooleanProperty: false, + baralStringProperty: 'string', + }, + }, + 'nested.baz': { + bazBooleanProperty: true, + }, + }; + + // preserves type - failure + _ = { + // @ts-expect-error Unsupported type + 'nested.bar': false, + // @ts-expect-error Unsupported type + 'nested.baz': 'string', + }; + + // preserves properties of nested objects - failure + _ = { + 'nested.bar': { + // @ts-expect-error Unsupported type + barBooleanProperty: 'string', + }, + }; + + // 3 layers with dot notation + + // preserves type + _ = { + 'nested.bar.barBooleanProperty': true, + 'nested.bar.barAnotherLayer': {}, + }; + + // preserves properties of nested objects + _ = { + 'nested.bar.barAnotherLayer': { + baralBooleanProperty: false, + baralStringProperty: 'string', + }, + }; + + // preserves type - failure + _ = { + // @ts-expect-error Unsupported type + 'nested.bar.barAnotherLayer': true, + // @ts-expect-error Unsupported type + 'nested.baz.bazAnotherLayer': 'string', + }; + + // preserves properties of nested objects - failure + _ = { + 'nested.bar.barAnotherLayer': { + // @ts-expect-error Unsupported type + baralBooleanProperty: 'string', + }, + }; + + expect(true).to.be.true; + }); + }); + + describe('given nested objects with index properties', () => { + it('supports object replacement at each layer (with partial)', () => { + let _: UpdateData; + _ = { + indexed: {}, + }; + + _ = { + indexed: { + bar: {}, + baz: {}, + }, + }; + + _ = { + indexed: { + bar: { + nameBooleanProperty: true, + }, + baz: { + nameNumberProperty: 1, + }, + }, + }; + + expect(true).to.be.true; + }); + + it('errors for unexpected value types at each layer', () => { + let _: UpdateData; + _ = { + // @ts-expect-error Unsupported type + indexed: true, + }; + + _ = { + indexed: { + anyRandomName: { + // @ts-expect-error Unsupported type + nameStringProperty: true, + }, + }, + }; + + expect(true).to.be.true; + }); + + it('does not allow properties that were not on the original type', () => { + const _: UpdateData = { + indexed: { + foo: { + // @ts-expect-error Unsupported name + unknown: 1, + }, + bar: { + nameNumberProperty: 2, + // @ts-expect-error Unsupported name + something: 'string val', + }, + }, + }; + + expect(true).to.be.true; + }); + + it('preserves value types for dot notation', () => { + let _: UpdateData; + + // 2 layers with dot notation + + // preserves type + _ = { + 'indexed.bar': {}, + 'indexed.baz': {}, + }; + + // preserves properties of nested objects referenced + // with dot notation + _ = { + 'indexed.bar': { + nameBooleanProperty: true, + nameNumberProperty: 1, + }, + 'indexed.baz': { + nameBooleanProperty: true, + }, + }; + + // preserves properties of nested objects referenced + // with dot notation + _ = { + // @ts-expect-error Unsupported type + 'indexed.bar': null, + }; + + expect(true).to.be.true; + }); + }); + + describe('given Record', () => { + it('supports primitive type for T', () => { + let _: UpdateData>; + + _ = { + numberProperty: 1, + }; + + _ = { + // @ts-expect-error Unsupported type + numberProperty: false, + }; + + expect(true).to.be.true; + }); + + it('supports object type for T', () => { + let _: UpdateData>>; + + _ = {}; + + _ = { + indexedProperty: {}, + }; + + _ = { + indexedProperty: { + numberProperty: 1, + booleanProperty: true, + }, + }; + + _ = { + indexedProperty: { + objectProperty: {}, + }, + }; + + _ = { + indexedProperty: { + objectProperty: { + booleanProperty: true, + }, + }, + }; + + _ = { + indexedProperty: { + stringProperty: 'string', + }, + }; + + _ = { + indexedProperty: { + numberProperty: 1, + booleanProperty: true, + stringProperty: 'string', + // @ts-expect-error Unsupported type + nullProperty: null, + undefinedProperty: undefined, + unionProperty: 1, + objectProperty: { + stringProperty: 'string', + booleanProperty: true, + }, + }, + }; + + // It allows any child property type + // when the property is indexed. + _ = { + indexedProperty: false, + }; + + // It allows any child property type + // when the property is indexed. + _ = { + indexedProperty: 'string', + }; + + // It prevents types that are not a + // child property type. + _ = { + // @ts-expect-error Unsupported type + indexedProperty: null, + }; + + // It allows dot notation to set nested properties + _ = { + 'indexedProperty.stringProperty': 'string', + }; + + // It allows dot notation to set nested properties, + // but only enforces types to any of the child properties + // of the indexed property. + _ = { + 'indexedProperty.stringProperty': true, + 'indexedProperty.booleanProperty': 'string', + // @ts-expect-error Unsupported type + 'indexedProperty.undefinedProperty': null, + }; + + // But still enforces property types + // when the child type is object + _ = { + objectProperty: { + // @ts-expect-error Unsupported type + numberProperty: false, + }, + }; + + _ = { + objectProperty: { + // @ts-expect-error Unsupported type + unknownProperty: false, + }, + }; + + expect(true).to.be.true; + }); + + it('supports object with nested index for T', () => { + let _: UpdateData< + Record< + string, + { + objectWithIndexProperty: { + [key: string]: boolean; + }; + deepObjectWithIndexProperty: { + [key: string]: { + stringProperty: string; + numberProperty: number; + }; + }; + } + > + >; + + _ = {}; + + _ = { + indexedProperty: {}, + }; + + _ = { + indexedProperty: { + objectWithIndexProperty: {}, + deepObjectWithIndexProperty: {}, + }, + }; + + _ = { + indexedProperty: { + objectWithIndexProperty: {}, + }, + }; + + _ = { + indexedProperty: { + objectWithIndexProperty: { + indexedProperty: true, + }, + }, + }; + + _ = { + indexedProperty: { + deepObjectWithIndexProperty: { + indexedProperty: {}, + }, + }, + }; + + _ = { + indexedProperty: { + deepObjectWithIndexProperty: { + indexedProperty: { + stringProperty: 'string', + }, + }, + }, + }; + + _ = { + indexedProperty: { + stringProperty: 'string', + }, + }; + + _ = { + indexedProperty: { + objectWithIndexProperty: { + indexedProperty: true, + }, + deepObjectWithIndexProperty: { + indexedProperty: { + stringProperty: 'string', + numberProperty: 1, + }, + }, + }, + }; + + // It allows any child property type + // when the property is indexed. + _ = { + indexedProperty: false, + }; + + // It allows any child property type + // when the property is indexed. + _ = { + indexedProperty: 'string', + }; + + // It prevents types that are not a + // child property type. + _ = { + // @ts-expect-error Unsupported type + indexedProperty: null, + }; + + // It allows dot notation to set nested properties + _ = { + 'indexedProperty.stringProperty': 'string', + }; + + // It allows dot notation to set nested properties, + // but only enforces types to any of the child properties + // of the indexed property. + _ = { + 'indexedProperty.stringProperty': true, + 'indexedProperty.booleanProperty': 'string', + // @ts-expect-error Unsupported type + 'indexedProperty.undefinedProperty': null, + }; + + // But still enforces property types + // when the child type is object + _ = { + indexedProperty: { + // @ts-expect-error Unsupported type + numberProperty: null, + }, + }; + + expect(true).to.be.true; + }); + }); + + // tests cover new scenarios that are fixed for index signatures + describe('UpdateData fixes', () => { + interface MyNestedIndexServerType { + booleanProperty: boolean; + + // index signatures nested 1 layer deep + indexed: { + [name: string]: { + booleanProperty: boolean; + numberProperty: number; + }; + }; + + // index signatures nested 2 layers deep + layer: { + indexed: { + [name: string]: { + booleanProperty: boolean; + numberProperty: number; + }; + }; + }; + } + + describe('given nested objects with index properties', () => { + it('supports object replacement at each layer (with partial)', () => { + const _: UpdateData = { + indexed: { + bar: {}, + baz: {}, + }, + }; + + expect(true).to.be.true; + }); + + it('allows dot notation for nested index types', () => { + let _: UpdateData; + + // the fix allows 3 layers of dot notation + + // allows the property + _ = { + 'indexed.bar.booleanProperty': true, + }; + + _ = { + 'indexed.bar.numberProperty': 1, + }; + + // does not enforce type on indexed properties + _ = { + 'indexed.bar.booleanProperty': 3, // not enforced since number is a child type of `indexed.[string]` + }; + + _ = { + 'indexed.bar.numberProperty': false, + }; + + _ = { + 'indexed.bar.unknown': true, + }; + + // string value is not allowed because string is not a child type of `indexed.[string]` + _ = { + // @ts-expect-error Unsupported type + 'indexed.bar.numberProperty': 'string', + }; + + expect(true).to.be.true; + }); + + it('allows dot notation for nested index types that are 2 layers deep', () => { + let _: UpdateData; + + // the fix allows 4 layers with dot notation + + // allows the property + _ = { + 'layer.indexed.bar.booleanProperty': true, + }; + + // allows the property, but does not enforce type + _ = { + 'layer.indexed.bar.booleanProperty': 4, + }; + + // Allows unknown properties in sub types + _ = { + 'layer.indexed.bar.unknownProperty': 4, + }; + + expect(true).to.be.true; + }); + }); + }); + + describe('Customer reports', () => { + it('fixes issues/1745#issuecomment-1289292949', () => { + type TestType = { + foo: { + [key: string]: { + bar: string; + }; + }; + }; + // The intent of the function below is to test TypeScript compile and not execute. + async function _(docRef: DocumentReference): Promise { + const key = 'aKey'; + void docRef.update({ + [`foo.${key}.bar`]: 'test', + }); + } + + expect(true).to.be.true; + }); + + it('fixes issues/1745#issuecomment-1804130587', () => { + type TType = { + prop: Record; + }; + const update: UpdateData = {}; + const value: {[key: string]: {id: string}} = { + key: {id: ''}, + }; + + update.prop = value; + + expect(true).to.be.true; + }); + + it('fixes issues/1890', () => { + interface MyDoc { + nestedA: Record; + nestedB: Record; + } + + function _(db: Firestore, docRef: DocumentReference) { + const goodKey = 'nestedA.test'; + const badKey = 'nestedA.' + 'test'; + + void db.runTransaction(async t => { + t.update(docRef, { + [goodKey]: 3, + }); + }); + + void db.runTransaction(async t => { + t.update(docRef, { + [badKey]: 3, + }); + }); + } + + expect(true).to.be.true; + }); + }); + + /* eslint-enable @typescript-eslint/no-unused-vars */ +}); + +/** + * Does nothing; however, this function can be useful in tests that only check + * the compile-time behavior of the TypeScript compiler. For example, a test + * that ensures that a certain statement successfully compiles could pass the + * code block to this function to exercise the compiler but the code will not + * actually be executed at runtime. + */ +function neverCall(_: (docRef: DocumentReference) => T): void { + _; // Trick eslint into thinking that `_` is used. +} + +/** + * Does nothing; this function does not actually exist but is merely _declared_ + * to exist. This facilitates creating variables typed as FirestoreDataConverter + * with the given type parameters at compile time. This can be useful in tests + * that only check compile-time behavior of the TypeScript compiler but don't + * actually get executed at runtime. + */ +declare function fakeConverter< + AppModelType, + DbModelType extends DocumentData, +>(): FirestoreDataConverter; diff --git a/handwritten/firestore/dev/test/util.ts b/handwritten/firestore/dev/test/util.ts new file mode 100644 index 00000000000..d29557045d8 --- /dev/null +++ b/handwritten/firestore/dev/test/util.ts @@ -0,0 +1,104 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {describe, it} from 'mocha'; +import {expect} from 'chai'; +import {isPlainObject, tryGetPreferRestEnvironmentVariable} from '../src/util'; +import * as sinon from 'sinon'; + +describe('isPlainObject()', () => { + it('allows Object.create()', () => { + expect(isPlainObject(Object.create({}))).to.be.true; + expect(isPlainObject(Object.create(Object.prototype))).to.be.true; + expect(isPlainObject(Object.create(null))).to.be.true; + }); + + it(' allows plain types', () => { + expect(isPlainObject({foo: 'bar'})).to.be.true; + expect(isPlainObject({})).to.be.true; + }); + + it('rejects custom types', () => { + class Foo {} + expect(isPlainObject(new Foo())).to.be.false; + expect(isPlainObject(Object.create(new Foo()))).to.be.false; + }); + + describe('tryGetPreferRestEnvironmentVariable', () => { + const sandbox = sinon.createSandbox(); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let warnSpy: any; + let originalValue: string | undefined; + + beforeEach(() => { + warnSpy = sandbox.spy(console, 'warn'); + originalValue = process.env.FIRESTORE_PREFER_REST; + }); + + afterEach(() => { + sandbox.restore(); + if (originalValue === undefined) { + delete process.env.FIRESTORE_PREFER_REST; + } else { + process.env.FIRESTORE_PREFER_REST = originalValue; + } + }); + + it('reads true', async () => { + process.env.FIRESTORE_PREFER_REST = 'true'; + expect(tryGetPreferRestEnvironmentVariable()).to.be.true; + }); + + it('reads 1', async () => { + process.env.FIRESTORE_PREFER_REST = '1'; + expect(tryGetPreferRestEnvironmentVariable()).to.be.true; + }); + + it('reads false', async () => { + process.env.FIRESTORE_PREFER_REST = 'false'; + expect(tryGetPreferRestEnvironmentVariable()).to.be.false; + }); + + it('reads 0', async () => { + process.env.FIRESTORE_PREFER_REST = '0'; + expect(tryGetPreferRestEnvironmentVariable()).to.be.false; + }); + + it('ignores case', async () => { + process.env.FIRESTORE_PREFER_REST = 'True'; + expect(tryGetPreferRestEnvironmentVariable()).to.be.true; + }); + + it('trims whitespace', async () => { + process.env.FIRESTORE_PREFER_REST = ' true '; + expect(tryGetPreferRestEnvironmentVariable()).to.be.true; + }); + + it('returns undefined when the environment variable is not set', async () => { + delete process.env.FIRESTORE_PREFER_REST; + expect(tryGetPreferRestEnvironmentVariable()).to.be.undefined; + expect(warnSpy.calledOnce).to.be.false; + }); + + it('returns undefined and warns when the environment variable is set to an unsupported value', async () => { + process.env.FIRESTORE_PREFER_REST = 'enable'; + expect(tryGetPreferRestEnvironmentVariable()).to.be.undefined; + expect(warnSpy.calledOnce).to.be.true; + expect(warnSpy.getCall(0).args[0]).to.match( + /unsupported value.*FIRESTORE_PREFER_REST/, + ); + }); + }); +}); diff --git a/handwritten/firestore/dev/test/util/helpers.ts b/handwritten/firestore/dev/test/util/helpers.ts new file mode 100644 index 00000000000..8a50a055b2f --- /dev/null +++ b/handwritten/firestore/dev/test/util/helpers.ts @@ -0,0 +1,476 @@ +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { + DocumentData, + Settings, + SetOptions, + PartialWithFieldValue, +} from '@google-cloud/firestore'; + +import {expect} from 'chai'; +import * as extend from 'extend'; +import {JSONStreamIterator} from 'length-prefixed-json-stream'; +import {Duplex, PassThrough} from 'stream'; +import * as through2 from 'through2'; +import {firestore} from '../../protos/firestore_v1_proto_api'; +import type {grpc} from 'google-gax'; +import * as proto from '../../protos/firestore_v1_proto_api'; +import * as v1 from '../../src/v1'; +import {Firestore, QueryDocumentSnapshot} from '../../src'; +import {ClientPool} from '../../src/pool'; +import {GapicClient} from '../../src/types'; + +import api = proto.google.firestore.v1; + +let SSL_CREDENTIALS: grpc.ChannelCredentials | null = null; +if (!isPreferRest()) { + const grpc = require('google-gax').grpc; + SSL_CREDENTIALS = grpc.credentials.createInsecure(); +} + +export const PROJECT_ID = 'test-project'; +export const DATABASE_ROOT = `projects/${PROJECT_ID}/databases/(default)`; +export const COLLECTION_ROOT = `${DATABASE_ROOT}/documents/collectionId`; +export const DOCUMENT_NAME = `${COLLECTION_ROOT}/documentId`; + +// Allow invalid API usage to test error handling. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type InvalidApiUsage = any; + +/** Defines the request handlers used by Firestore. */ +export type ApiOverride = Partial; + +/** + * Creates a new Firestore instance for testing. Request handlers can be + * overridden by providing `apiOverrides`. + * + * @param apiOverrides An object with request handlers to override. + * @param firestoreSettings Firestore Settings to configure the client. + * @returns A Promise that resolves with the new Firestore client. + */ +export function createInstance( + apiOverrides?: ApiOverride, + firestoreSettings?: Settings, +): Promise { + const initializationOptions = { + ...{projectId: PROJECT_ID, sslCreds: SSL_CREDENTIALS!}, + ...firestoreSettings, + }; + + const firestore = new Firestore(); + firestore.settings(initializationOptions); + + firestore['_clientPool'] = new ClientPool( + /* concurrentRequestLimit= */ 1, + /* maxIdleClients= */ 0, + () => + ({ + ...new v1.FirestoreClient(initializationOptions), + ...apiOverrides, + }) as any, // eslint-disable-line @typescript-eslint/no-explicit-any + ); + + return Promise.resolve(firestore); +} + +/** + * Verifies that all streams have been properly shutdown at the end of a test + * run. + */ +export function verifyInstance(firestore: Firestore): Promise { + // Allow the setTimeout() call in _initializeStream to run before + // verifying that all operations have finished executing. + return new Promise((resolve, reject) => { + if (firestore['_clientPool'].opCount === 0) { + resolve(); + } else { + setTimeout(() => { + const opCount = firestore['_clientPool'].opCount; + if (opCount === 0) { + resolve(); + } else { + reject( + new Error( + `Firestore has ${opCount} unfinished operations executing.`, + ), + ); + } + }, 10); + } + }); +} + +function write( + document: api.IDocument, + mask: api.IDocumentMask | null, + transforms: api.DocumentTransform.IFieldTransform[] | null, + precondition: api.IPrecondition | null, +): api.ICommitRequest { + const writes: api.IWrite[] = []; + const update = Object.assign({}, document); + delete update.updateTime; + delete update.createTime; + writes.push({update}); + + if (mask) { + writes[0].updateMask = mask; + } + + if (transforms) { + writes[0].updateTransforms = transforms; + } + + if (precondition) { + writes[0].currentDocument = precondition; + } + + return {writes}; +} + +export function updateMask(...fieldPaths: string[]): api.IDocumentMask { + return fieldPaths.length === 0 ? {} : {fieldPaths}; +} + +export function set(opts: { + document: api.IDocument; + transforms?: api.DocumentTransform.IFieldTransform[]; + mask?: api.IDocumentMask; +}): api.ICommitRequest { + return write( + opts.document, + opts.mask || null, + opts.transforms || null, + /* precondition= */ null, + ); +} + +export function update(opts: { + document: api.IDocument; + transforms?: api.DocumentTransform.IFieldTransform[]; + mask?: api.IDocumentMask; + precondition?: api.IPrecondition; +}): api.ICommitRequest { + const precondition = opts.precondition || {exists: true}; + const mask = opts.mask || updateMask(); + return write(opts.document, mask, opts.transforms || null, precondition); +} + +export function create(opts: { + document: api.IDocument; + transforms?: api.DocumentTransform.IFieldTransform[]; + mask?: api.IDocumentMask; +}): api.ICommitRequest { + return write(opts.document, /* updateMask= */ null, opts.transforms || null, { + exists: false, + }); +} + +function value(value: string | api.IValue): api.IValue { + if (typeof value === 'string') { + return { + stringValue: value, + }; + } else { + return value; + } +} + +export function retrieve(id: string): api.IBatchGetDocumentsRequest { + return {documents: [`${DATABASE_ROOT}/documents/collectionId/${id}`]}; +} + +export function remove( + id: string, + precondition?: api.IPrecondition, +): api.ICommitRequest { + const writes: api.IWrite[] = [ + {delete: `${DATABASE_ROOT}/documents/collectionId/${id}`}, + ]; + + if (precondition) { + writes[0].currentDocument = precondition; + } + + return {writes}; +} + +export function found( + dataOrId: api.IDocument | string, +): api.IBatchGetDocumentsResponse { + return { + found: typeof dataOrId === 'string' ? document(dataOrId) : dataOrId, + readTime: {seconds: 5, nanos: 6}, + }; +} + +export function missing(id: string): api.IBatchGetDocumentsResponse { + return { + missing: `${DATABASE_ROOT}/documents/collectionId/${id}`, + readTime: {seconds: 5, nanos: 6}, + }; +} + +export function document( + id: string, + field?: string, + value?: string | api.IValue, + ...fieldOrValues: Array +): api.IDocument { + const document: api.IDocument = { + name: `${DATABASE_ROOT}/documents/collectionId/${id}`, + fields: {}, + createTime: {seconds: 1, nanos: 2}, + updateTime: {seconds: 3, nanos: 4}, + }; + + if (field !== undefined) { + fieldOrValues = [field, value!].concat(fieldOrValues); + + for (let i = 0; i < fieldOrValues.length; i += 2) { + const field = fieldOrValues[i] as string; + const value = fieldOrValues[i + 1]; + + if (typeof value === 'string') { + document.fields![field] = { + stringValue: value, + }; + } else { + document.fields![field] = value; + } + } + } + + return document; +} + +export function serverTimestamp( + field: string, +): api.DocumentTransform.IFieldTransform { + return {fieldPath: field, setToServerValue: 'REQUEST_TIME'}; +} + +export function incrementTransform( + field: string, + n: number, +): api.DocumentTransform.IFieldTransform { + return { + fieldPath: field, + increment: Number.isInteger(n) ? {integerValue: n} : {doubleValue: n}, + }; +} + +export function arrayTransform( + field: string, + transform: 'appendMissingElements' | 'removeAllFromArray', + ...values: Array +): api.DocumentTransform.IFieldTransform { + const fieldTransform: api.DocumentTransform.IFieldTransform = { + fieldPath: field, + }; + + fieldTransform[transform] = {values: values.map(val => value(val))}; + + return fieldTransform; +} + +export function writeResult(count: number): api.IWriteResponse { + const response: api.IWriteResponse = { + commitTime: { + nanos: 0, + seconds: 1, + }, + }; + + if (count > 0) { + response.writeResults = []; + + for (let i = 1; i <= count; ++i) { + response.writeResults.push({ + updateTime: { + nanos: i * 2, + seconds: i * 2 + 1, + }, + }); + } + } + + return response; +} + +export function requestEquals( + actual: object | undefined, + expected: object, +): void { + expect(actual).to.not.be.undefined; + + // 'extend' removes undefined fields in the request object. The backend + // ignores these fields, but we need to manually strip them before we compare + // the expected and the actual request. + actual = extend(true, {}, actual); + const proto = Object.assign({database: DATABASE_ROOT}, expected); + expect(actual).to.deep.eq(proto); +} + +export function stream(...elements: Array): Duplex { + const stream = through2.obj(); + + setImmediate(() => { + for (const el of elements) { + if (el instanceof Error) { + stream.destroy(el); + return; + } + stream.push(el); + } + stream.push(null); + }); + + return stream; +} + +/** + * Query streams with no results always at least emit a read time. + */ +export function emptyQueryStream(readTime = {seconds: 5, nanos: 6}) { + return stream({readTime}); +} + +export function streamWithoutEnd(...elements: Array): Duplex { + const stream = through2.obj(); + + setImmediate(() => { + for (const el of elements) { + if (el instanceof Error) { + stream.destroy(el); + return; + } + stream.push(el); + } + }); + + return stream; +} + +/** Creates a response as formatted by the GAPIC request methods. */ +export function response(result: T): Promise<[T, unknown, unknown]> { + return Promise.resolve([result, undefined, undefined]); +} + +/** Sample user object class used in tests. */ +export class Post { + constructor( + readonly title: string, + readonly author: string, + ) {} + toString(): string { + return this.title + ', by ' + this.author; + } +} + +/** Converts Post objects to and from Firestore in tests. */ +export const postConverter = { + toFirestore(post: Post): DocumentData { + return {title: post.title, author: post.author}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): Post { + const data = snapshot.data(); + return new Post(data.title, data.author); + }, +}; + +export const postConverterMerge = { + toFirestore( + post: PartialWithFieldValue, + options?: SetOptions, + ): DocumentData { + if (options) { + expect(post).to.not.be.an.instanceOf(Post); + } else { + expect(post).to.be.an.instanceof(Post); + } + const result: DocumentData = {}; + if (post.title) result.title = post.title; + if (post.author) result.author = post.author; + return result; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): Post { + const data = snapshot.data(); + return new Post(data.title, data.author); + }, +}; + +export async function bundleToElementArray( + bundle: Buffer, +): Promise> { + const result: Array = []; + const readable = new PassThrough(); + readable.end(bundle); + const streamIterator = new JSONStreamIterator(readable); + for await (const value of streamIterator) { + result.push(value as firestore.IBundleElement); + } + return result; +} + +/** + * Reads the elements of an AsyncIterator. + * + * Example: + * + * const query = firestore.collection('collectionId'); + * const iterator = query.stream()[Symbol.asyncIterator]() + * as AsyncIterator; + * return collect(iterator).then(snapshots => { + * expect(snapshots).to.have.length(2); + * }); + * + * @param iterator the iterator whose elements over which to iterate. + * @returns a Promise that is fulfilled with the elements that were produced, or + * is rejected with the cause of the first failed iteration. + */ +export async function collect( + iterator: AsyncIterator, +): Promise> { + const values: Array = []; + // eslint-disable-next-line no-constant-condition + while (true) { + const {done, value} = await iterator.next(); + if (done) { + break; + } + values.push(value); + } + return values; +} + +/** + * Returns a value indicating whether preferRest is enabled + * via the environment variable `FIRESTORE_PREFER_REST`. + * + * @returns `true` if preferRest is enabled via the environment variable `FIRESTORE_PREFER_REST`. + */ +export function isPreferRest(): boolean { + return ( + process.env.FIRESTORE_PREFER_REST === '1' || + process.env.FIRESTORE_PREFER_REST === 'true' + ); +} + +/** + * Returns a value indicating whether the tests are running against an Enterprise edition DB + */ +export function isEnterprise(): boolean { + return !!process.env.RUN_ENTERPRISE_TESTS; +} diff --git a/handwritten/firestore/dev/test/util/mocha_extensions.ts b/handwritten/firestore/dev/test/util/mocha_extensions.ts new file mode 100644 index 00000000000..4acd09f4d39 --- /dev/null +++ b/handwritten/firestore/dev/test/util/mocha_extensions.ts @@ -0,0 +1,103 @@ +/** + * @license + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* eslint-disable no-restricted-properties */ + +import {describe, it} from 'mocha'; + +// Helper to make a type itselt (T) and optionally union that with (T['skip']) +type tOrSkipT = T | (T extends {skip: unknown} ? T['skip'] : T); + +declare module 'mocha' { + // eslint-disable-next-line @typescript-eslint/no-namespace + interface TestFunction { + skipEnterprise: tOrSkipT; + skipEmulator: tOrSkipT; + skipClassic: tOrSkipT; + } + + interface PendingTestFunction { + skipEnterprise: tOrSkipT; + skipEmulator: tOrSkipT; + skipClassic: tOrSkipT; + } + + interface SuiteFunction { + skipEnterprise: tOrSkipT; + skipEmulator: tOrSkipT; + skipClassic: tOrSkipT; + } + + interface PendingSuiteFunction { + skipEnterprise: tOrSkipT; + skipEmulator: tOrSkipT; + skipClassic: tOrSkipT; + } +} + +// Define helpers +export function mixinSkipImplementations(obj: unknown): void { + Object.defineProperty(obj, 'skipEnterprise', { + get(): unknown { + if (this === it.skip) { + return this; + } + if (this === describe.skip) { + return this; + } + if (process.env.RUN_ENTERPRISE_TESTS) { + return this.skip; + } + return this; + }, + }); + + Object.defineProperty(obj, 'skipEmulator', { + get(): unknown { + if (this === it.skip) { + return this; + } + if (this === describe.skip) { + return this; + } + if (process.env.FIRESTORE_EMULATOR_HOST) { + return this.skip; + } + return this; + }, + }); + + Object.defineProperty(obj, 'skipClassic', { + get(): unknown { + if (this === it.skip) { + return this; + } + if (this === describe.skip) { + return this; + } + if (!process.env.RUN_ENTERPRISE_TESTS) { + return this.skip; + } + return this; + }, + }); +} + +// TODO add mocha functions that must be extended +[global.it, global.describe, it, it.skip, describe, describe.skip].forEach( + mixinSkipImplementations, +); diff --git a/handwritten/firestore/dev/test/vector-query.ts b/handwritten/firestore/dev/test/vector-query.ts new file mode 100644 index 00000000000..9e23c915b15 --- /dev/null +++ b/handwritten/firestore/dev/test/vector-query.ts @@ -0,0 +1,611 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {afterEach, beforeEach, it} from 'mocha'; +import {fieldFiltersQuery, queryEquals, result} from './query'; +import { + ApiOverride, + createInstance, + emptyQueryStream, + stream, + streamWithoutEnd, + verifyInstance, +} from './util/helpers'; +import { + DocumentSnapshot, + FieldValue, + FieldPath, + Firestore, + Query, + Timestamp, +} from '../src'; +import {expect, use} from 'chai'; +import {google} from '../protos/firestore_v1_proto_api'; +import api = google.firestore.v1; +import * as chaiAsPromised from 'chai-as-promised'; +import {setTimeoutHandler} from '../src/backoff'; +use(chaiAsPromised); + +export function findNearestQuery( + fieldPath: string, + queryVector: Array, + limit: number, + measure: api.StructuredQuery.FindNearest.DistanceMeasure, +): api.IStructuredQuery { + return { + findNearest: { + vectorField: {fieldPath}, + queryVector: { + mapValue: { + fields: { + __type__: {stringValue: '__vector__'}, + value: { + arrayValue: { + values: queryVector.map(n => { + return {doubleValue: n}; + }), + }, + }, + }, + }, + }, + limit: {value: limit}, + distanceMeasure: measure, + }, + }; +} + +describe('Vector(findNearest) query interface', () => { + let firestore: Firestore; + + beforeEach(() => { + setTimeoutHandler(setImmediate); + return createInstance().then(firestoreInstance => { + firestore = firestoreInstance; + }); + }); + + afterEach(async () => { + await verifyInstance(firestore); + setTimeoutHandler(setTimeout); + }); + + it('has isEqual() method', () => { + const queryA = firestore.collection('collectionId').where('foo', '==', 42); + const queryB = firestore.collection('collectionId').where('foo', '==', 42); + + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + limit: 10, + distanceMeasure: 'COSINE', + }) + .isEqual( + queryA.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'COSINE', + limit: 10, + }), + ), + ).to.be.true; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + }), + ), + ).to.be.true; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceThreshold: 0.125, + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceThreshold: 0.125, + }), + ), + ).to.be.true; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceThreshold: 0.125, + distanceResultField: new FieldPath('foo'), + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceThreshold: 0.125, + distanceResultField: new FieldPath('foo'), + }), + ), + ).to.be.true; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceResultField: 'distance', + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceResultField: new FieldPath('distance'), + }), + ), + ).to.be.true; + + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + limit: 10, + distanceMeasure: 'COSINE', + }) + .isEqual( + firestore.collection('collectionId').findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'COSINE', + limit: 10, + }), + ), + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + limit: 10, + distanceMeasure: 'COSINE', + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 42], + distanceMeasure: 'COSINE', + limit: 10, + }), + ), + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + limit: 10, + distanceMeasure: 'COSINE', + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'COSINE', + limit: 1000, + }), + ), + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + limit: 10, + distanceMeasure: 'COSINE', + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + }), + ), + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceThreshold: 1.125, + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceThreshold: 0.125, + }), + ), + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceThreshold: 1, + }), + ), + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceThreshold: 1, + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + }), + ), + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceResultField: 'distance', + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceResultField: 'result', + }), + ), + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceResultField: new FieldPath('bar'), + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceResultField: new FieldPath('foo'), + }), + ), + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceResultField: new FieldPath('foo'), + }), + ), + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceResultField: 'result', + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + }), + ), + ).to.be.false; + }); + + it('generates equal vector queries with deprecated API', () => { + const queryA = firestore.collection('collectionId').where('foo', '==', 42); + const queryB = firestore.collection('collectionId').where('foo', '==', 42); + + expect( + queryA + .findNearest('embedding', [40, 41, 42], { + limit: 10, + distanceMeasure: 'COSINE', + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'COSINE', + limit: 10, + }), + ), + ).to.be.true; + expect( + queryA + .findNearest('foo', [40, 41, 42, 43], { + limit: 1, + distanceMeasure: 'DOT_PRODUCT', + }) + .isEqual( + queryB.findNearest({ + vectorField: 'foo', + queryVector: [40, 41, 42, 43], + distanceMeasure: 'DOT_PRODUCT', + limit: 1, + }), + ), + ).to.be.true; + }); + + it('generates proto', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + fieldFiltersQuery('foo', 'EQUAL', 'bar'), + findNearestQuery('embedding', [3, 4, 5], 100, 'COSINE'), + ); + return emptyQueryStream(); + }, + }; + + return createInstance(overrides).then(firestoreInstance => { + firestore = firestoreInstance; + const query: Query = firestore.collection('collectionId'); + const vectorQuery = query + .where('foo', '==', 'bar') + .findNearest('embedding', FieldValue.vector([3, 4, 5]), { + limit: 100, + distanceMeasure: 'COSINE', + }); + return vectorQuery.get(); + }); + }); + + it('validates inputs', async () => { + const query: Query = firestore.collection('collectionId'); + expect(() => { + query.findNearest({ + vectorField: 'embedding', + queryVector: [], + limit: 10, + distanceMeasure: 'EUCLIDEAN', + }); + }).to.throw('not a valid vector size'); + expect(() => { + query.findNearest({ + vectorField: 'embedding', + queryVector: [10, 1000], + limit: 0, + distanceMeasure: 'EUCLIDEAN', + }); + }).to.throw('not a valid positive limit number'); + }); + + it('validates inputs - preview (deprecated) API', async () => { + const query: Query = firestore.collection('collectionId'); + expect(() => { + query.findNearest('embedding', [], { + limit: 10, + distanceMeasure: 'EUCLIDEAN', + }); + }).to.throw('not a valid vector size'); + expect(() => { + query.findNearest('embedding', [10, 1000], { + limit: 0, + distanceMeasure: 'EUCLIDEAN', + }); + }).to.throw('not a valid positive limit number'); + }); + + const distanceMeasure: ('EUCLIDEAN' | 'DOT_PRODUCT' | 'COSINE')[] = [ + 'EUCLIDEAN', + 'DOT_PRODUCT', + 'COSINE', + ]; + distanceMeasure.forEach(distanceMeasure => { + it(`returns results when distanceMeasure is ${distanceMeasure}`, async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals( + request, + findNearestQuery('embedding', [1], 2, distanceMeasure), + ); + return stream(result('first'), result('second')); + }, + }; + + return createInstance(overrides).then(firestoreInstance => { + firestore = firestoreInstance; + const query = firestore.collection('collectionId').findNearest({ + vectorField: 'embedding', + queryVector: [1], + limit: 2, + distanceMeasure: distanceMeasure, + }); + return query.get().then(results => { + expect(results.size).to.equal(2); + expect(results.empty).to.be.false; + expect(results.readTime.isEqual(new Timestamp(5, 6))).to.be.true; + expect(results.docs[0].id).to.equal('first'); + expect(results.docs[1].id).to.equal('second'); + expect(results.docChanges()).to.have.length(2); + + let count = 0; + + results.forEach(doc => { + expect(doc instanceof DocumentSnapshot).to.be.true; + expect(doc.createTime.isEqual(new Timestamp(1, 2))).to.be.true; + expect(doc.updateTime.isEqual(new Timestamp(3, 4))).to.be.true; + expect(doc.readTime.isEqual(new Timestamp(5, 6))).to.be.true; + ++count; + }); + + expect(2).to.equal(count); + }); + }); + }); + }); + + it('successful return without ending the stream on get()', async () => { + const overrides: ApiOverride = { + runQuery: request => { + queryEquals(request, findNearestQuery('vector', [1], 10, 'COSINE')); + return streamWithoutEnd(result('first'), result('second', true)); + }, + }; + + let counter = 0; + return createInstance(overrides).then(firestoreInstance => { + firestore = firestoreInstance; + const query = firestore.collection('collectionId').findNearest({ + vectorField: 'vector', + queryVector: [1], + limit: 10, + distanceMeasure: 'COSINE', + }); + return query.get().then(results => { + expect(++counter).to.equal(1); + expect(results.size).to.equal(2); + expect(results.empty).to.be.false; + expect(results.readTime.isEqual(new Timestamp(5, 6))).to.be.true; + expect(results.docs[0].id).to.equal('first'); + expect(results.docs[1].id).to.equal('second'); + expect(results.docChanges()).to.have.length(2); + }); + }); + }); + + it('handles stream exception at initialization', async () => { + let attempts = 0; + const query = firestore.collection('collectionId').findNearest({ + vectorField: 'embedding', + queryVector: [1], + limit: 100, + distanceMeasure: 'EUCLIDEAN', + }); + + query._queryUtil._stream = () => { + ++attempts; + throw new Error('Expected error'); + }; + + return query + .get() + .then(() => { + throw new Error('Unexpected success in Promise'); + }) + .catch(err => { + expect(err.message).to.equal('Expected error'); + expect(attempts).to.equal(1); + }); + }); + + it('handles stream exception during initialization', async () => { + let attempts = 0; + + const overrides: ApiOverride = { + runQuery: () => { + ++attempts; + return stream(new Error('Expected error')); + }, + }; + + return createInstance(overrides).then(firestoreInstance => { + firestore = firestoreInstance; + return firestore + .collection('collectionId') + .findNearest({ + vectorField: 'embedding', + queryVector: [1], + limit: 10, + distanceMeasure: 'COSINE', + }) + .get() + .then(() => { + throw new Error('Unexpected success in Promise'); + }) + .catch(err => { + expect(err.message).to.equal('Expected error'); + expect(attempts).to.equal(5); + }); + }); + }); +}); diff --git a/handwritten/firestore/dev/test/watch.ts b/handwritten/firestore/dev/test/watch.ts new file mode 100644 index 00000000000..348f7f0898b --- /dev/null +++ b/handwritten/firestore/dev/test/watch.ts @@ -0,0 +1,2722 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {DocumentData} from '@google-cloud/firestore'; + +import * as duplexify from 'duplexify'; +import {describe, it, beforeEach, afterEach} from 'mocha'; +import {expect} from 'chai'; +import * as extend from 'extend'; +import {GoogleError, Status} from 'google-gax'; +import {Duplex, Transform} from 'stream'; +import * as through2 from 'through2'; + +import {google} from '../protos/firestore_v1_proto_api'; + +import { + CollectionReference, + DocumentReference, + DocumentSnapshot, + FieldPath, + Firestore, + GeoPoint, + Query, + QueryDocumentSnapshot, + QuerySnapshot, + setLogFunction, + Timestamp, +} from '../src'; +import {MAX_RETRY_ATTEMPTS, setTimeoutHandler} from '../src/backoff'; +import {DocumentSnapshotBuilder} from '../src/document'; +import {DocumentChangeType} from '../src/document-change'; +import {Serializer} from '../src/serializer'; +import {WATCH_IDLE_TIMEOUT_MS} from '../src/watch'; +import {createInstance, InvalidApiUsage, verifyInstance} from './util/helpers'; +import api = google.firestore.v1; + +// Change the argument to 'console.log' to enable debug output. +setLogFunction(null); + +let PROJECT_ID = process.env.PROJECT_ID; +if (!PROJECT_ID) { + PROJECT_ID = 'test-project'; +} +/** + * Asserts that the given list of docs match. + * @param actual The computed docs array. + * @param expected The expected docs array. + */ +function docsEqual( + actual: QueryDocumentSnapshot[], + expected: QueryDocumentSnapshot[], +): void { + expect(actual.length).to.equal(expected.length); + for (let i = 0; i < actual.length; i++) { + expect(actual[i].ref.id).to.equal(expected[i].ref.id); + expect(actual[i].data()).to.deep.eq(expected[i].data()); + expect(expected[i].createTime).to.be.an.instanceOf(Timestamp); + expect(expected[i].updateTime).to.be.an.instanceOf(Timestamp); + } +} + +interface TestChange { + type: DocumentChangeType; + doc: QueryDocumentSnapshot; +} + +interface TestSnapshot { + docs: QueryDocumentSnapshot[]; + docChanges: TestChange[]; +} + +/** + * Asserts that the given query snapshot matches the expected results. + * @param lastSnapshot The previous snapshot that this snapshot is based upon. + * @param version The current snapshot version to use for the comparison. + * @param actual A QuerySnapshot with results. + * @param expected Array of DocumentSnapshot. + */ +function snapshotsEqual( + lastSnapshot: TestSnapshot, + version: number, + actual: Error | QuerySnapshot | undefined, + expected: TestSnapshot, +): TestSnapshot { + const localDocs = ([] as QueryDocumentSnapshot[]).concat(lastSnapshot.docs); + + expect(actual).to.be.an.instanceof(QuerySnapshot); + + const actualSnapshot = actual as QuerySnapshot; + const actualDocChanges = actualSnapshot.docChanges(); + + expect(actualDocChanges.length).to.equal(expected.docChanges.length); + for (let i = 0; i < expected.docChanges.length; i++) { + expect(actualDocChanges[i].type).to.equal(expected.docChanges[i].type); + expect(actualDocChanges[i].doc.ref.id).to.equal( + expected.docChanges[i].doc.ref.id, + ); + expect(actualDocChanges[i].doc.data()).to.deep.eq( + expected.docChanges[i].doc.data(), + ); + const readVersion = + actualDocChanges[i].type === 'removed' ? version - 1 : version; + expect( + actualDocChanges[i].doc.readTime.isEqual(new Timestamp(0, readVersion)), + ).to.be.true; + + if (actualDocChanges[i].oldIndex !== -1) { + localDocs.splice(actualDocChanges[i].oldIndex, 1); + } + + if (actualDocChanges[i].newIndex !== -1) { + localDocs.splice( + actualDocChanges[i].newIndex, + 0, + actualDocChanges[i].doc, + ); + } + } + + docsEqual(actualSnapshot.docs, expected.docs); + docsEqual(localDocs, expected.docs); + expect(actualSnapshot.readTime.isEqual(new Timestamp(0, version))).to.be.true; + expect(actualSnapshot.size).to.equal(expected.docs.length); + + return {docs: actualSnapshot.docs, docChanges: actualDocChanges}; +} + +/* + * Helper for constructing a snapshot. + */ +function snapshot( + ref: DocumentReference, + data: DocumentData, +): QueryDocumentSnapshot { + const snapshot = new DocumentSnapshotBuilder(ref); + snapshot.fieldsProto = ref.firestore._serializer!.encodeFields(data); + snapshot.readTime = new Timestamp(0, 0); + snapshot.createTime = new Timestamp(0, 0); + snapshot.updateTime = new Timestamp(0, 0); + return snapshot.build() as QueryDocumentSnapshot; +} + +/* + * Helpers for constructing document changes. + */ +function docChange( + type: DocumentChangeType, + ref: DocumentReference, + data: DocumentData, +): {type: DocumentChangeType; doc: QueryDocumentSnapshot} { + return {type, doc: snapshot(ref, data)}; +} + +const added = (ref: DocumentReference, data: DocumentData) => + docChange('added', ref, data); +const modified = (ref: DocumentReference, data: DocumentData) => + docChange('modified', ref, data); +const removed = (ref: DocumentReference, data: DocumentData) => + docChange('removed', ref, data); + +function verifyRequest(actual: T, expected: T): void { + // Remove undefined value, as these are ignored by the backend. + actual = extend(true, {}, actual); + expect(actual).to.deep.equal(expected); +} + +const EMPTY = { + docs: [], + docChanges: [], +}; + +/** Captures stream data and makes it available via deferred Promises. */ +class DeferredListener { + private readonly pendingData: Array<{type: string; data?: T | Error}> = []; + private readonly pendingListeners: Array<{ + type: string; + resolve: (r: T | Error | undefined) => void; + }> = []; + + /** + * Makes stream data available via the Promises set in the 'await' call. If no + * Promise has been set, the data will be cached. + */ + on(type: string, data?: T | Error): void { + const listener = this.pendingListeners.shift(); + + if (listener) { + expect(type).to.equal( + listener.type, + `Expected message of type '${listener.type}' but got '${type}' ` + + `with '${JSON.stringify(data)}'.`, + ); + listener.resolve(data); + } else { + this.pendingData.push({ + type, + data, + }); + } + } + + /** + * Returns a Promise with the next result from the underlying stream. The + * Promise resolves immediately if pending data is available, otherwise it + * resolves when the next chunk arrives. + */ + await(expectedType: string): Promise { + const data = this.pendingData.shift(); + + if (data) { + expect(data.type).to.equal( + expectedType, + `Expected message of type '${expectedType}' but got '${data.type}' ` + + `with '${JSON.stringify(data.data)}'.`, + ); + return Promise.resolve(data.data); + } + + return new Promise(resolve => + this.pendingListeners.push({ + type: expectedType, + resolve, + }), + ); + } +} + +/** + * Handles stream operations for the Firestore Listen API. StreamHelper + * supports one stream at a time, but multiple streams can be processed through + * sequential invocations of the Listen API. + */ +class StreamHelper { + private readonly deferredListener = + new DeferredListener(); + private backendStream: Duplex | null = null; + + streamCount = 0; // The number of streams that the client has requested + readStream: Transform | null = null; + writeStream: Transform | null = null; + + /** Returns the GAPIC callback to use with this stream helper. */ + getListenCallback(): () => Duplex { + return () => { + // Create a mock backend whose stream we can return. + ++this.streamCount; + + this.readStream = through2.obj(); + this.writeStream = through2.obj(); + + this.readStream!.once('data', result => + this.deferredListener.on('data', result), + ); + this.readStream!.on('error', error => + this.deferredListener.on('error', error), + ); + this.readStream!.on('end', () => this.deferredListener.on('end')); + this.readStream!.on('close', () => this.deferredListener.on('close')); + + this.deferredListener.on('open', {}); + + this.backendStream = duplexify.obj(this.readStream, this.writeStream); + return this.backendStream!; + }; + } + + /** + * Returns a Promise with the next results from the underlying stream. + */ + await(type: string): Promise { + return this.deferredListener.await(type); + } + + /** Waits for a destroyed stream to be re-opened. */ + awaitReopen(): Promise { + return this.await('error') + .then(() => this.await('close')) + .then(() => this.awaitOpen()); + } + + /** + * Waits for the stream to open and to receive its first message (the + * AddTarget message). + */ + awaitOpen(): Promise { + return this.await('open').then(() => { + return this.await('data') as api.IListenRequest; + }); + } + + /** + * Sends a message to the currently active stream. + */ + write(data: string | object): void { + // The stream returned by the Gapic library accepts Protobuf + // messages, but the type information does not expose this. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.writeStream!.write(data as any); + } + + /** + * Closes the currently active stream. + */ + close(): void { + this.backendStream!.emit('end'); + } + + /** + * Destroys the currently active stream with the optionally provided error. + * If omitted, the stream is closed with a GRPC Status of UNAVAILABLE. + */ + destroyStream(err?: GoogleError): void { + if (!err) { + err = new GoogleError('Server disconnect'); + err.code = Status.UNAVAILABLE; + } + this.readStream!.destroy(err); + } +} + +/** + * Encapsulates the stream logic for the Watch API. + */ +class WatchHelper { + private readonly streamHelper: StreamHelper; + private readonly deferredListener = new DeferredListener(); + private unsubscribe: (() => void) | null = null; + + snapshotVersion = 0; + serializer: Serializer; + + /** + * @param streamHelper The StreamHelper base class for this Watch operation. + * @param reference The CollectionReference or DocumentReference that is being + * watched. + * @param targetId The target ID of the watch stream. + */ + constructor( + streamHelper: StreamHelper, + private reference: DocumentReference | Query, + private targetId: number, + ) { + this.serializer = new Serializer(reference.firestore); + this.streamHelper = streamHelper; + this.snapshotVersion = 0; + this.deferredListener = new DeferredListener(); + } + + /** + * Returns a Promise with the next result from the underlying stream. + */ + await(type: 'snapshot'): Promise; + await(type: 'error'): Promise; + await(type: string): Promise { + return this.deferredListener.await(type); + } + + /** + * Creates a watch, starts a listen, and asserts that the request got + * processed. + * + * @returns The unsubscribe handler for the listener. + */ + startWatch(): () => void { + this.unsubscribe = this.reference.onSnapshot( + (snapshot: unknown) => { + this.deferredListener.on('snapshot', snapshot as T); + }, + (error: Error) => { + this.deferredListener.on('error', error); + }, + ); + return this.unsubscribe!; + } + + /** + * Ends the listen stream. + * + * @returns A Promise that will be fulfilled when the backend saw the end. + */ + async endWatch(): Promise { + this.unsubscribe!(); + await this.streamHelper.await('end'); + } + + /** + * Sends a target change from the backend simulating adding the query target. + * + * @param targetId The target ID to send. If omitted, uses the + * default target ID. + */ + sendAddTarget(targetId?: number): void { + this.streamHelper.write({ + targetChange: { + targetChangeType: 'ADD', + targetIds: [targetId !== undefined ? targetId : this.targetId], + }, + }); + } + + /** + * Sends a target change from the backend simulating removing a query target. + * + * @param cause The optional code indicating why the target was removed. + */ + sendRemoveTarget(cause?: number): void { + const proto: api.IListenResponse = { + targetChange: { + targetChangeType: 'REMOVE', + targetIds: [this.targetId], + }, + }; + if (cause) { + proto.targetChange!.cause = { + code: cause, + message: 'test remove', + }; + } + this.streamHelper.write(proto); + } + + /** + * Sends a target change from the backend of type 'NO_CHANGE'. If specified, + * includes a resume token. + */ + sendSnapshot(version: number, resumeToken?: Uint8Array): void { + this.snapshotVersion = version; + + const proto: api.IListenResponse = { + targetChange: { + targetChangeType: 'NO_CHANGE', + targetIds: [], + readTime: {seconds: 0, nanos: version}, + }, + }; + + if (resumeToken) { + proto.targetChange!.resumeToken = resumeToken; + } + + this.streamHelper.write(proto); + } + + /** + * Sends a target change from the backend of type 'CURRENT'. + */ + sendCurrent(resumeToken?: Uint8Array): void { + const proto: api.IListenResponse = { + targetChange: { + targetChangeType: 'CURRENT', + targetIds: [this.targetId], + }, + }; + + if (resumeToken) { + proto.targetChange!.resumeToken = resumeToken; + } + + this.streamHelper.write(proto); + } + + /** + * Sends a doc change from the backend to the client. + * + * @param ref The document reference. + * @param data The data for the doc in proto JSON format. + */ + sendDoc(ref: DocumentReference, data: DocumentData): void { + this.streamHelper.write({ + documentChange: { + document: { + name: ref.formattedName, + fields: this.serializer.encodeFields(data), + createTime: {seconds: 1, nanos: 2}, + updateTime: {seconds: 3, nanos: this.snapshotVersion}, + }, + targetIds: [this.targetId], + }, + }); + } + + /** + * Sends a doc removal from the backend to the client. + * + * @param ref The document reference. + * @param data The data for the doc in proto JSON format. + */ + sendDocRemove(ref: DocumentReference, data: DocumentData): void { + this.streamHelper.write({ + documentChange: { + document: { + name: ref.formattedName, + fields: this.serializer.encodeFields(data), + }, + removedTargetIds: [this.targetId], + }, + }); + } + + /** + * Sends a doc delete from the backend to the client. + * + * @param ref The document reference. + */ + sendDocDelete(ref: DocumentReference): void { + this.streamHelper.write({ + documentDelete: { + document: ref.formattedName, + removedTargetIds: [this.targetId], + }, + }); + } + + /** + * A wrapper for writing tests that successfully run a watch. + */ + runTest( + expectedRequest: api.IListenRequest, + func: () => Promise, + ): Promise { + this.startWatch(); + + return this.streamHelper + .awaitOpen() + .then(request => { + verifyRequest(request, expectedRequest); + return func(); + }) + .then(() => this.endWatch()); + } + + /** + * A wrapper for writing tests that fail to run a watch. + */ + runFailedTest( + expectedRequest: api.IListenRequest, + func: () => void | Promise, + expectedError: string, + ): Promise { + this.startWatch(); + + return this.streamHelper + .awaitOpen() + .then(request => { + verifyRequest(request, expectedRequest); + return func(); + }) + .then(() => { + return this.await('error'); + }) + .then(err => { + if (!(err instanceof Error)) { + throw new Error('Expected error from Watch'); + } + expect(err.message).to.equal(expectedError); + }); + } +} + +describe('Query watch', () => { + // The collection to query. + let colRef: CollectionReference; + + // The documents used in this query. + let doc1: DocumentReference; + let doc2: DocumentReference; + let doc3: DocumentReference; + let doc4: DocumentReference; + + let firestore: Firestore; + let targetId: number; + let watchHelper: WatchHelper; + let streamHelper: StreamHelper; + + let lastSnapshot: { + docs: QueryDocumentSnapshot[]; + docChanges: TestChange[]; + } = EMPTY; + + // The proto JSON that should be sent for the query. + const collQueryJSON = () => { + return { + database: `projects/${PROJECT_ID}/databases/(default)`, + addTarget: { + query: { + parent: `projects/${PROJECT_ID}/databases/(default)/documents`, + structuredQuery: { + from: [{collectionId: 'col'}], + }, + }, + targetId, + }, + }; + }; + + const includeQuery = () => { + return colRef.where('included', '==', 'yes'); + }; + + // The proto JSON that should be sent for the query. + const includeQueryJSON: () => api.IListenRequest = () => { + return { + database: `projects/${PROJECT_ID}/databases/(default)`, + addTarget: { + query: { + parent: `projects/${PROJECT_ID}/databases/(default)/documents`, + structuredQuery: { + from: [{collectionId: 'col'}], + where: { + fieldFilter: { + field: { + fieldPath: 'included', + }, + op: 'EQUAL', + value: { + stringValue: 'yes', + }, + }, + }, + }, + }, + targetId, + }, + }; + }; + + // The proto JSON that should be sent for a resumed query. + const resumeTokenQuery: (resumeToken: Buffer) => api.IListenRequest = ( + resumeToken: Buffer, + ) => { + return { + database: `projects/${PROJECT_ID}/databases/(default)`, + addTarget: { + query: { + parent: `projects/${PROJECT_ID}/databases/(default)/documents`, + structuredQuery: { + from: [{collectionId: 'col'}], + }, + }, + targetId, + resumeToken, + }, + }; + }; + + const sortedQuery = () => { + return colRef.orderBy('foo', 'desc'); + }; + + // The proto JSON that should be sent for the query. + const sortedQueryJSON: () => api.IListenRequest = () => { + return { + database: `projects/${PROJECT_ID}/databases/(default)`, + addTarget: { + query: { + parent: `projects/${PROJECT_ID}/databases/(default)/documents`, + structuredQuery: { + from: [{collectionId: 'col'}], + orderBy: [{direction: 'DESCENDING', field: {fieldPath: 'foo'}}], + }, + }, + targetId, + }, + }; + }; + + /** The GAPIC callback that executes the listen. */ + let listenCallback: () => Duplex; + + beforeEach(async () => { + // We are intentionally skipping the delays to ensure fast test execution. + // The retry semantics are unaffected by this, as we maintain their + // asynchronous behavior. + setTimeoutHandler((op, timeout) => { + if (timeout !== WATCH_IDLE_TIMEOUT_MS) { + setImmediate(op); + } + }); + + targetId = 0x1; + + streamHelper = new StreamHelper(); + listenCallback = streamHelper.getListenCallback(); + + firestore = await createInstance({listen: () => listenCallback()}); + watchHelper = new WatchHelper( + streamHelper, + firestore.collection('col'), + targetId, + ); + + colRef = firestore.collection('col'); + + doc1 = firestore.doc('col/doc1'); + doc2 = firestore.doc('col/doc2'); + doc3 = firestore.doc('col/doc3'); + doc4 = firestore.doc('col/doc4'); + + lastSnapshot = EMPTY; + }); + + afterEach(() => { + setTimeoutHandler(setTimeout); + return verifyInstance(firestore); + }); + + it('with invalid callbacks', () => { + expect(() => colRef.onSnapshot('foo' as InvalidApiUsage)).to.throw( + 'Value for argument "onNext" is not a valid function.', + ); + + expect(() => + colRef.onSnapshot(() => {}, 'foo' as InvalidApiUsage), + ).to.throw('Value for argument "onError" is not a valid function.'); + }); + + it('without error callback', done => { + const unsubscribe = colRef.onSnapshot(() => { + unsubscribe(); + done(); + }); + + void streamHelper.awaitOpen().then(() => { + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + }); + }); + + it('handles invalid listen protos', () => { + return watchHelper.runFailedTest( + collQueryJSON(), + () => { + // Mock the server responding to the query with an invalid proto. + streamHelper.write({invalid: true}); + }, + 'Unknown listen response type: {"invalid":true}', + ); + }); + + it('handles invalid target change protos', () => { + return watchHelper.runFailedTest( + collQueryJSON(), + () => { + // Mock the server responding to the query with an invalid proto. + streamHelper.write({ + targetChange: { + targetChangeType: 'INVALID', + targetIds: [0xfeed], + }, + }); + }, + 'Unknown target change type: {"targetChangeType":"INVALID",' + + '"targetIds":[65261]}', + ); + }); + + it('handles remove target change protos', () => { + return watchHelper.runFailedTest( + collQueryJSON(), + () => { + watchHelper.sendRemoveTarget(); + }, + 'Error 13: internal error', + ); + }); + + it('handles remove target change with code', () => { + return watchHelper.runFailedTest( + collQueryJSON(), + () => { + watchHelper.sendRemoveTarget(7); + }, + 'Error 7: test remove', + ); + }); + + it('rejects an unknown target', () => { + return watchHelper.runFailedTest( + collQueryJSON(), + () => { + watchHelper.sendAddTarget(2); + }, + 'Unexpected target ID sent by server', + ); + }); + + it('re-opens on unexpected stream end', () => { + return watchHelper.runTest(collQueryJSON(), () => { + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1, Buffer.from([0xabcd])); + return watchHelper.await('snapshot').then(async () => { + streamHelper.close(); + await streamHelper.await('end'); + await streamHelper.awaitOpen(); + + streamHelper.close(); + await streamHelper.await('end'); + await streamHelper.awaitOpen(); + + expect(streamHelper.streamCount).to.equal(3); + }); + }); + }); + + it('stops attempts after maximum retry attempts', () => { + const err = new GoogleError('GRPC Error'); + err.code = Status.ABORTED; + return watchHelper.runFailedTest( + collQueryJSON(), + async () => { + // Retry for the maximum of retry attempts. + for (let i = 0; i < MAX_RETRY_ATTEMPTS; i++) { + streamHelper.destroyStream(err); + await streamHelper.awaitReopen(); + } + // The next retry should fail with an error. + streamHelper.destroyStream(err); + await streamHelper.await('error'); + await streamHelper.await('close'); + }, + 'Exceeded maximum number of retries allowed.', + ); + }); + + it("doesn't re-open inactive stream", () => { + // This test uses the normal timeout handler since it relies on the actual + // backoff window during the the stream recovery. We then use this window to + // unsubscribe from the Watch stream and make sure that we don't + // re-open the stream once the backoff expires. + setTimeoutHandler(setTimeout); + + const unsubscribe = watchHelper.startWatch(); + return streamHelper + .awaitOpen() + .then(request => { + verifyRequest(request, collQueryJSON()); + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1, Buffer.from([0xabcd])); + return watchHelper.await('snapshot'); + }) + .then(() => { + streamHelper.close(); + unsubscribe(); + expect(streamHelper.streamCount).to.equal(1); + }); + }); + + it('retries based on error code', async () => { + const testCases = new Map(); + testCases.set(Status.CANCELLED, true); + testCases.set(Status.UNKNOWN, true); + testCases.set(Status.INVALID_ARGUMENT, false); + testCases.set(Status.DEADLINE_EXCEEDED, true); + testCases.set(Status.NOT_FOUND, false); + testCases.set(Status.ALREADY_EXISTS, false); + testCases.set(Status.PERMISSION_DENIED, false); + testCases.set(Status.RESOURCE_EXHAUSTED, true); + testCases.set(Status.FAILED_PRECONDITION, false); + testCases.set(Status.ABORTED, true); + testCases.set(Status.OUT_OF_RANGE, false); + testCases.set(Status.UNIMPLEMENTED, false); + testCases.set(Status.INTERNAL, true); + testCases.set(Status.UNAVAILABLE, true); + testCases.set(Status.DATA_LOSS, false); + testCases.set(Status.UNAUTHENTICATED, true); + + for (const [statusCode, expectRetry] of testCases) { + const err = new GoogleError('GRPC Error'); + err.code = statusCode; + + if (expectRetry) { + return watchHelper.runTest(collQueryJSON(), () => { + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1, Buffer.from([0xabcd])); + return watchHelper.await('snapshot').then(() => { + streamHelper.destroyStream(err); + return streamHelper.awaitReopen(); + }); + }); + } else { + await watchHelper.runFailedTest( + collQueryJSON(), + () => { + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1, Buffer.from([0xabcd])); + return watchHelper + .await('snapshot') + .then(() => { + streamHelper.destroyStream(err); + }) + .then(() => { + return streamHelper.await('error'); + }) + .then(() => { + return streamHelper.await('close'); + }); + }, + 'GRPC Error', + ); + } + } + }).timeout(5000); + + it('retries with unknown code', () => { + return watchHelper.runTest(collQueryJSON(), () => { + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1, Buffer.from([0xabcd])); + return watchHelper.await('snapshot').then(() => { + streamHelper.destroyStream(new Error('Unknown')); + return streamHelper.awaitReopen(); + }); + }); + }); + + it('handles changing a doc', () => { + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [added(doc1, {foo: 'a'})], + }); + + // Add another result. + watchHelper.sendDoc(doc2, {foo: 'b'}); + watchHelper.sendSnapshot(3); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 3, results, { + docs: [snapshot(doc1, {foo: 'a'}), snapshot(doc2, {foo: 'b'})], + docChanges: [added(doc2, {foo: 'b'})], + }); + + // Change a result. + watchHelper.sendDoc(doc2, {bar: 'c'}); + watchHelper.sendSnapshot(4); + return watchHelper.await('snapshot'); + }) + .then(results => { + snapshotsEqual(lastSnapshot, 4, results, { + docs: [snapshot(doc1, {foo: 'a'}), snapshot(doc2, {bar: 'c'})], + docChanges: [modified(doc2, {bar: 'c'})], + }); + }); + }); + }); + + it('reconnects after error', () => { + let resumeToken = Buffer.from([0xabcd]); + + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(resumeToken); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendSnapshot(2, resumeToken); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [added(doc1, {foo: 'a'})], + }); + expect(streamHelper.streamCount).to.equal(1); + streamHelper.destroyStream(); + return streamHelper.awaitReopen(); + }) + .then(request => { + verifyRequest(request, resumeTokenQuery(resumeToken)); + watchHelper.sendAddTarget(); + watchHelper.sendDoc(doc2, {foo: 'b'}); + + resumeToken = Buffer.from([0xbcde]); + watchHelper.sendSnapshot(3, resumeToken); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 3, results, { + docs: [snapshot(doc1, {foo: 'a'}), snapshot(doc2, {foo: 'b'})], + docChanges: [added(doc2, {foo: 'b'})], + }); + streamHelper.destroyStream(); + return streamHelper.awaitReopen(); + }) + .then(request => { + verifyRequest(request, resumeTokenQuery(resumeToken)); + watchHelper.sendAddTarget(); + watchHelper.sendDoc(doc3, {foo: 'c'}); + watchHelper.sendSnapshot(4, resumeToken); + return watchHelper.await('snapshot'); + }) + .then(results => { + expect(streamHelper.streamCount).to.equal(3); + snapshotsEqual(lastSnapshot, 4, results, { + docs: [ + snapshot(doc1, {foo: 'a'}), + snapshot(doc2, {foo: 'b'}), + snapshot(doc3, {foo: 'c'}), + ], + docChanges: [added(doc3, {foo: 'c'})], + }); + }); + }); + }); + + it('ignores changes sent after the last snapshot', () => { + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(Buffer.from([0x0])); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendDoc(doc2, {foo: 'b'}); + watchHelper.sendSnapshot(2, Buffer.from([0x1])); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {foo: 'a'}), snapshot(doc2, {foo: 'b'})], + docChanges: [added(doc1, {foo: 'a'}), added(doc2, {foo: 'b'})], + }); + expect(streamHelper.streamCount).to.equal(1); + // This document delete will be ignored. + watchHelper.sendDocDelete(doc1); + streamHelper.destroyStream(); + return streamHelper.awaitReopen(); + }) + .then(() => { + watchHelper.sendDocDelete(doc2); + watchHelper.sendSnapshot(3, Buffer.from([0x2])); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 3, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [removed(doc2, {foo: 'b'})], + }); + }); + }); + }); + + it('ignores non-matching tokens', () => { + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + + watchHelper.sendCurrent(); + let resumeToken = Buffer.from([0x1]); + watchHelper.sendSnapshot(1, resumeToken); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + + // Send snapshot with non-matching target id. No snapshot will be + // send. + streamHelper.write({ + targetChange: { + targetChangeType: 'NO_CHANGE', + targetIds: [0xfeed], + readTime: {seconds: 0, nanos: 0}, + resumeToken: Buffer.from([0x2]), + }, + }); + + resumeToken = Buffer.from([0x3]); + // Send snapshot with matching target id but no resume token. + // The old token continues to be used. + streamHelper.write({ + targetChange: { + targetChangeType: 'NO_CHANGE', + targetIds: [], + readTime: {seconds: 0, nanos: 0}, + resumeToken, + }, + }); + + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 0, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [added(doc1, {foo: 'a'})], + }); + streamHelper.destroyStream(); + return streamHelper.awaitReopen(); + }) + .then(request => { + verifyRequest(request, resumeTokenQuery(resumeToken)); + expect(streamHelper.streamCount).to.equal(2); + }); + }); + }); + + it('reconnects with multiple attempts', () => { + return watchHelper + .runFailedTest( + collQueryJSON(), + () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + const resumeToken = Buffer.from([0xabcd]); + watchHelper.sendSnapshot(1, resumeToken); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + listenCallback = () => { + // Return a stream that always errors on write + ++streamHelper.streamCount; + return through2.obj((chunk, enc, callback) => { + callback( + new Error(`Stream Error (${streamHelper.streamCount})`), + ); + }); + }; + + streamHelper.destroyStream(); + return streamHelper.await('error'); + }) + .then(() => { + return streamHelper.await('close'); + }) + .then(() => { + streamHelper.writeStream!.destroy(); + }); + }, + 'Stream Error (6)', + ) + .then(() => { + expect(streamHelper.streamCount).to.equal( + 6, + 'Expected stream to be opened once and retried five times', + ); + }); + }); + + it('sorts docs', () => { + watchHelper = new WatchHelper(streamHelper, sortedQuery(), targetId); + + return watchHelper.runTest(sortedQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add two result. + watchHelper.sendDoc(doc1, {foo: 'b'}); + watchHelper.sendDoc(doc2, {foo: 'a'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {foo: 'b'}), snapshot(doc2, {foo: 'a'})], + docChanges: [added(doc1, {foo: 'b'}), added(doc2, {foo: 'a'})], + }); + + // Change the results so they sort in a different order. + watchHelper.sendDoc(doc1, {foo: 'c'}); + watchHelper.sendDoc(doc2, {foo: 'd'}); + watchHelper.sendSnapshot(3); + return watchHelper.await('snapshot'); + }) + .then(results => { + snapshotsEqual(lastSnapshot, 3, results, { + docs: [snapshot(doc2, {foo: 'd'}), snapshot(doc1, {foo: 'c'})], + docChanges: [ + modified(doc2, {foo: 'd'}), + modified(doc1, {foo: 'c'}), + ], + }); + }); + }); + }); + + it('combines multiple change events for the same doc', () => { + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + // Modify it. + watchHelper.sendDoc(doc1, {foo: 'b'}); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, { + docs: [snapshot(doc1, {foo: 'b'})], + docChanges: [added(doc1, {foo: 'b'})], + }); + + // Modify it two more times. + watchHelper.sendDoc(doc1, {foo: 'c'}); + watchHelper.sendDoc(doc1, {foo: 'd'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {foo: 'd'})], + docChanges: [modified(doc1, {foo: 'd'})], + }); + + // Remove it, delete it, and then add it again. + watchHelper.sendDocRemove(doc1, {foo: 'e'}); + watchHelper.sendDocDelete(doc1); + watchHelper.sendDoc(doc1, {foo: 'f'}); + watchHelper.sendSnapshot(3); + return watchHelper.await('snapshot'); + }) + .then(results => { + snapshotsEqual(lastSnapshot, 3, results, { + docs: [snapshot(doc1, {foo: 'f'})], + docChanges: [modified(doc1, {foo: 'f'})], + }); + }); + }); + }); + + it('can sort by FieldPath.documentId()', () => { + let query = sortedQuery(); + const expectedJson = sortedQueryJSON(); + + // Add FieldPath.documentId() sorting + query = query.orderBy(FieldPath.documentId(), 'desc'); + expectedJson.addTarget!.query!.structuredQuery!.orderBy!.push({ + direction: 'DESCENDING', + field: {fieldPath: '__name__'}, + }); + + watchHelper = new WatchHelper(streamHelper, query, targetId); + + return watchHelper.runTest(expectedJson, () => { + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(() => { + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendDoc(doc2, {foo: 'a'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc2, {foo: 'a'}), snapshot(doc1, {foo: 'a'})], + docChanges: [added(doc2, {foo: 'a'}), added(doc1, {foo: 'a'})], + }); + }); + }); + }); + + it('sorts document changes in the right order', () => { + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendDoc(doc2, {foo: 'a'}); + watchHelper.sendDoc(doc4, {foo: 'a'}); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, { + docs: [ + snapshot(doc1, {foo: 'a'}), + snapshot(doc2, {foo: 'a'}), + snapshot(doc4, {foo: 'a'}), + ], + docChanges: [ + added(doc1, {foo: 'a'}), + added(doc2, {foo: 'a'}), + added(doc4, {foo: 'a'}), + ], + }); + + watchHelper.sendDocDelete(doc1); + watchHelper.sendDoc(doc2, {foo: 'b'}); + watchHelper.sendDoc(doc3, {foo: 'b'}); + watchHelper.sendDocDelete(doc4); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc2, {foo: 'b'}), snapshot(doc3, {foo: 'b'})], + docChanges: [ + removed(doc1, {foo: 'a'}), + removed(doc4, {foo: 'a'}), + added(doc3, {foo: 'b'}), + modified(doc2, {foo: 'b'}), + ], + }); + }); + }); + }); + + it("handles changing a doc so it doesn't match", () => { + watchHelper = new WatchHelper(streamHelper, includeQuery(), targetId); + + return watchHelper.runTest(includeQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add a result. + watchHelper.sendDoc(doc1, {included: 'yes'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {included: 'yes'})], + docChanges: [added(doc1, {included: 'yes'})], + }); + + // Add another result. + watchHelper.sendDoc(doc2, {included: 'yes'}); + watchHelper.sendSnapshot(3); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 3, results, { + docs: [ + snapshot(doc1, {included: 'yes'}), + snapshot(doc2, {included: 'yes'}), + ], + docChanges: [added(doc2, {included: 'yes'})], + }); + + // Change a result. + watchHelper.sendDocRemove(doc2, {included: 'no'}); + watchHelper.sendSnapshot(4); + return watchHelper.await('snapshot'); + }) + .then(results => { + snapshotsEqual(lastSnapshot, 4, results, { + docs: [snapshot(doc1, {included: 'yes'})], + docChanges: [removed(doc2, {included: 'yes'})], + }); + }); + }); + }); + + it('handles deleting a doc', () => { + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [added(doc1, {foo: 'a'})], + }); + + // Add another result. + watchHelper.sendDoc(doc2, {foo: 'b'}); + watchHelper.sendSnapshot(3); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 3, results, { + docs: [snapshot(doc1, {foo: 'a'}), snapshot(doc2, {foo: 'b'})], + docChanges: [added(doc2, {foo: 'b'})], + }); + + // Delete a result. + watchHelper.sendDocDelete(doc2); + watchHelper.sendSnapshot(4); + return watchHelper.await('snapshot'); + }) + .then(results => { + snapshotsEqual(lastSnapshot, 4, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [removed(doc2, {foo: 'b'})], + }); + }); + }); + }); + + it('handles removing a doc', () => { + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [added(doc1, {foo: 'a'})], + }); + + // Add another result. + watchHelper.sendDoc(doc2, {foo: 'b'}); + watchHelper.sendSnapshot(3); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 3, results, { + docs: [snapshot(doc1, {foo: 'a'}), snapshot(doc2, {foo: 'b'})], + docChanges: [added(doc2, {foo: 'b'})], + }); + + // Delete a result. + watchHelper.sendDocRemove(doc2, {foo: 'c'}); + watchHelper.sendSnapshot(4); + return watchHelper.await('snapshot'); + }) + .then(results => { + snapshotsEqual(lastSnapshot, 4, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [removed(doc2, {foo: 'b'})], + }); + }); + }); + }); + + it.skip('handles deleting a non-existent doc', () => { + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [added(doc1, {foo: 'a'})], + }); + + // Delete a different doc. + watchHelper.sendDocDelete(doc2); + watchHelper.sendSnapshot(3); + }); + }); + }); + + it('handles reset', () => { + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add three results. + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendDoc(doc2, {foo: 'b'}); + watchHelper.sendDoc(doc3, {foo: 'c'}); + + // Send the snapshot. Note that we do not increment the snapshot + // version to keep the update time the same. + watchHelper.sendSnapshot(1); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, { + docs: [ + snapshot(doc1, {foo: 'a'}), + snapshot(doc2, {foo: 'b'}), + snapshot(doc3, {foo: 'c'}), + ], + docChanges: [ + added(doc1, {foo: 'a'}), + added(doc2, {foo: 'b'}), + added(doc3, {foo: 'c'}), + ], + }); + + // Send a RESET. + streamHelper.write({ + targetChange: { + targetChangeType: 'RESET', + targetIds: [], + }, + }); + + // Send the same doc1, a modified doc2, no doc3, and a new doc4. + // Send a different result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.snapshotVersion = 2; + watchHelper.sendDoc(doc2, {foo: 'bb'}); + watchHelper.sendDoc(doc4, {foo: 'd'}); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + snapshotsEqual(lastSnapshot, 2, results, { + docs: [ + snapshot(doc1, {foo: 'a'}), + snapshot(doc2, {foo: 'bb'}), + snapshot(doc4, {foo: 'd'}), + ], + docChanges: [ + removed(doc3, {foo: 'c'}), + added(doc4, {foo: 'd'}), + modified(doc2, {foo: 'bb'}), + ], + }); + }); + }); + }); + + it('reset after idle timeout', async () => { + let idleTimeout = () => {}; + + setTimeoutHandler((op, timeout) => { + if (timeout === WATCH_IDLE_TIMEOUT_MS) { + idleTimeout = op; + } else { + setTimeout(op, timeout); + } + }); + + await watchHelper.runTest(collQueryJSON(), async () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1, /* resumeToken= */ Buffer.from([0xabcd])); + + let currentSnapshot = await watchHelper.await('snapshot'); + + lastSnapshot = snapshotsEqual(lastSnapshot, 1, currentSnapshot, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [added(doc1, {foo: 'a'})], + }); + + // Invoke the idle timeout + idleTimeout(); + await streamHelper.await('end'); + + // Restart the stream and send one additional document + await streamHelper.awaitOpen(); + + watchHelper.sendAddTarget(); + + watchHelper.snapshotVersion = 2; + watchHelper.sendDoc(doc2, {foo: 'b'}); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(2); + currentSnapshot = await watchHelper.await('snapshot'); + + // The snapshot now includes both `doc1` and `doc2`. + snapshotsEqual(lastSnapshot, 2, currentSnapshot, { + docs: [snapshot(doc1, {foo: 'a'}), snapshot(doc2, {foo: 'b'})], + docChanges: [added(doc2, {foo: 'b'})], + }); + }); + }); + + it('handles reset with phantom doc', () => { + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [added(doc1, {foo: 'a'})], + }); + + // Change the first doc. + watchHelper.sendDoc(doc1, {foo: 'b'}); + // Send a doc change that should be ignored after reset. + watchHelper.sendDoc(doc2, {foo: 'c'}); + + // Send a RESET. + streamHelper.write({ + targetChange: { + targetChangeType: 'RESET', + targetIds: [], + }, + }); + + // Change the first doc again. + watchHelper.sendDoc(doc1, {foo: 'd'}); + + // Take a snapshot. + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(3); + return watchHelper.await('snapshot'); + }) + .then(results => { + snapshotsEqual(lastSnapshot, 3, results, { + docs: [snapshot(doc1, {foo: 'd'})], + docChanges: [modified(doc1, {foo: 'd'})], + }); + }); + }); + }); + + it('handles sending the snapshot version multiple times', () => { + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendSnapshot(2); + watchHelper.sendSnapshot(3); + watchHelper.sendSnapshot(4); + watchHelper.sendSnapshot(5); + watchHelper.sendSnapshot(6); + return watchHelper.await('snapshot'); + }) + .then(results => { + snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [added(doc1, {foo: 'a'})], + }); + }); + }); + }); + + it('handles filter mismatch', () => { + let oldRequestStream: NodeJS.WritableStream; + + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [added(doc1, {foo: 'a'})], + }); + + // Send a filter that doesn't match. Make sure the stream gets + // reopened. + oldRequestStream = streamHelper.writeStream!; + streamHelper.write({filter: {count: 0}}); + return streamHelper.await('end'); + }) + .then(() => streamHelper.awaitOpen()) + .then(request => { + expect(streamHelper.streamCount).to.equal(2); + expect(oldRequestStream).to.not.equal(streamHelper.writeStream); + verifyRequest(request, collQueryJSON()); + + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(3); + return watchHelper.await('snapshot'); + }) + .then(results => { + snapshotsEqual(lastSnapshot, 3, results, { + docs: [], + docChanges: [removed(doc1, {foo: 'a'})], + }); + }); + }); + }); + + it('handles filter match', () => { + return watchHelper.runTest(collQueryJSON(), () => { + watchHelper.sendAddTarget(); + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [added(doc1, {foo: 'a'})], + }); + + // Send the filter count for the previously added documents. + streamHelper.write({filter: {count: 1}}); + + // Even sending a new snapshot version should be a no-op. + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(2); + + watchHelper.sendDoc(doc2, {foo: 'b'}); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + expect(streamHelper.streamCount).to.equal(1); + snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {foo: 'a'}), snapshot(doc2, {foo: 'b'})], + docChanges: [added(doc2, {foo: 'b'})], + }); + }); + }); + }); + + it('handles resets with pending updates', () => { + return watchHelper.runTest(collQueryJSON(), () => { + watchHelper.sendAddTarget(); + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [added(doc1, {foo: 'a'})], + }); + + watchHelper.sendDoc(doc1, {foo: 'b'}); + watchHelper.sendDoc(doc2, {foo: 'c'}); + watchHelper.sendDoc(doc3, {foo: 'd'}); + streamHelper.write({filter: {count: 3}}); + + watchHelper.sendDoc(doc1, {foo: 'd'}); + watchHelper.sendDoc(doc2, {foo: 'e'}); + watchHelper.sendDocDelete(doc3); + streamHelper.write({filter: {count: 2}}); + + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + expect(streamHelper.streamCount).to.equal(1); + snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {foo: 'd'}), snapshot(doc2, {foo: 'e'})], + docChanges: [added(doc2, {foo: 'e'}), modified(doc1, {foo: 'd'})], + }); + }); + }); + }); + + it('handles add and delete in same snapshot', () => { + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendDocDelete(doc1); + watchHelper.sendDoc(doc2, {foo: 'b'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc2, {foo: 'b'})], + docChanges: [added(doc2, {foo: 'b'})], + }); + }); + }); + }); + + it('handles non-changing modify', () => { + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + // Send the snapshot. Note that we do not increment the snapshot + // version to keep the update time the same. + watchHelper.sendSnapshot(1); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [added(doc1, {foo: 'a'})], + }); + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendDoc(doc1, {foo: 'b'}); + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendDoc(doc2, {foo: 'c'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {foo: 'a'}), snapshot(doc2, {foo: 'c'})], + docChanges: [added(doc2, {foo: 'c'})], + }); + }); + }); + }); + + it('handles update time change', () => { + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [added(doc1, {foo: 'a'})], + }); + + // Send the same document but with a different update time + streamHelper.write({ + documentChange: { + document: { + name: doc1.formattedName, + fields: watchHelper.serializer.encodeFields({foo: 'a'}), + createTime: {seconds: 1, nanos: 2}, + updateTime: {seconds: 3, nanos: 5}, + }, + targetIds: [targetId], + }, + }); + watchHelper.sendSnapshot(3); + return watchHelper.await('snapshot'); + }) + .then(results => { + snapshotsEqual(lastSnapshot, 3, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [modified(doc1, {foo: 'a'})], + }); + }); + }); + }); + + describe('supports isEqual', () => { + let snapshotVersion: number; + + beforeEach(() => { + snapshotVersion = 0; + }); + + function initialSnapshot( + watchTest: (initialSnapshot: QuerySnapshot) => Promise | void, + ) { + return watchHelper.runTest(collQueryJSON(), () => { + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(++snapshotVersion); + return watchHelper + .await('snapshot') + .then(snapshot => watchTest(snapshot)); + }); + } + + function nextSnapshot( + baseSnapshot: QuerySnapshot, + watchStep: (currentSnapshot: QuerySnapshot) => Promise | void, + ): Promise { + void watchStep(baseSnapshot); + watchHelper.sendSnapshot(++snapshotVersion); + return watchHelper.await('snapshot') as Promise; + } + + it('for equal snapshots', () => { + let firstSnapshot: QuerySnapshot; + let secondSnapshot: QuerySnapshot; + let thirdSnapshot: QuerySnapshot; + + return initialSnapshot(snapshot => { + return nextSnapshot(snapshot, snapshot => { + firstSnapshot = snapshot; + expect(firstSnapshot.isEqual(firstSnapshot)).to.be.true; + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendDoc(doc2, {foo: 'b'}); + watchHelper.sendDoc(doc3, {foo: 'c'}); + }) + .then(snapshot => + nextSnapshot(snapshot, snapshot => { + secondSnapshot = snapshot; + expect(secondSnapshot.isEqual(secondSnapshot)).to.be.true; + watchHelper.sendDocDelete(doc1); + watchHelper.sendDoc(doc2, {foo: 'bar'}); + watchHelper.sendDoc(doc4, {foo: 'd'}); + }), + ) + .then(snapshot => { + thirdSnapshot = snapshot; + expect(thirdSnapshot.isEqual(thirdSnapshot)).to.be.true; + }); + }).then(() => + initialSnapshot(snapshot => { + return nextSnapshot(snapshot, snapshot => { + expect(snapshot.isEqual(firstSnapshot)).to.be.true; + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendDoc(doc2, {foo: 'b'}); + watchHelper.sendDoc(doc3, {foo: 'c'}); + }) + .then(snapshot => + nextSnapshot(snapshot, snapshot => { + expect(snapshot.isEqual(secondSnapshot)).to.be.true; + watchHelper.sendDocDelete(doc1); + watchHelper.sendDoc(doc2, {foo: 'bar'}); + watchHelper.sendDoc(doc4, {foo: 'd'}); + }), + ) + .then(snapshot => { + expect(snapshot.isEqual(thirdSnapshot)).to.be.true; + }); + }), + ); + }); + + it('for equal snapshots with materialized changes', () => { + let firstSnapshot: QuerySnapshot; + + return initialSnapshot(snapshot => { + return nextSnapshot(snapshot, () => { + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendDoc(doc2, {foo: 'b'}); + watchHelper.sendDoc(doc3, {foo: 'c'}); + }).then(snapshot => { + firstSnapshot = snapshot; + }); + }).then(() => + initialSnapshot(snapshot => { + return nextSnapshot(snapshot, () => { + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendDoc(doc2, {foo: 'b'}); + watchHelper.sendDoc(doc3, {foo: 'c'}); + }).then(snapshot => { + const materializedDocs = snapshot.docs; + expect(materializedDocs.length).to.equal(3); + expect(snapshot.isEqual(firstSnapshot)).to.be.true; + }); + }), + ); + }); + + it('for snapshots of different size', () => { + let firstSnapshot: QuerySnapshot; + + return initialSnapshot(snapshot => { + return nextSnapshot(snapshot, () => { + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendDoc(doc2, {foo: 'b'}); + }).then(snapshot => { + firstSnapshot = snapshot; + }); + }).then(() => + initialSnapshot(snapshot => { + return nextSnapshot(snapshot, () => { + watchHelper.sendDoc(doc1, {foo: 'a'}); + }).then(snapshot => { + expect(snapshot.isEqual(firstSnapshot)).to.be.false; + }); + }), + ); + }); + + it('for snapshots with different kind of changes', () => { + let firstSnapshot: QuerySnapshot; + + return initialSnapshot(snapshot => { + return nextSnapshot(snapshot, () => { + watchHelper.sendDoc(doc1, {foo: 'a'}); + }).then(snapshot => { + firstSnapshot = snapshot; + expect( + snapshot.docChanges()[0].isEqual(firstSnapshot.docChanges()[0]), + ).to.be.true; + }); + }).then(() => + initialSnapshot(snapshot => { + return nextSnapshot(snapshot, () => { + watchHelper.sendDoc(doc1, {foo: 'b'}); + }).then(snapshot => { + expect(snapshot.isEqual(firstSnapshot)).to.be.false; + expect( + snapshot.docChanges()[0].isEqual(firstSnapshot.docChanges()[0]), + ).to.be.false; + }); + }), + ); + }); + + it('for snapshots with different number of changes', () => { + let firstSnapshot: QuerySnapshot; + + return initialSnapshot(snapshot => { + return nextSnapshot(snapshot, () => + watchHelper.sendDoc(doc1, {foo: 'a'}), + ) + .then(snapshot => + nextSnapshot(snapshot, () => watchHelper.sendDoc(doc2, {foo: 'b'})), + ) + .then(snapshot => { + firstSnapshot = snapshot; + }); + }).then(() => + initialSnapshot(snapshot => { + return nextSnapshot(snapshot, () => + watchHelper.sendDoc(doc1, {foo: 'a'}), + ) + .then(snapshot => + nextSnapshot(snapshot, () => { + watchHelper.sendDocDelete(doc1); + watchHelper.sendDoc(doc2, {foo: 'b'}); + watchHelper.sendDoc(doc3, {foo: 'c'}); + }), + ) + .then(snapshot => { + expect(snapshot.isEqual(firstSnapshot)).to.be.false; + }); + }), + ); + }); + + it('for snapshots with different data types', () => { + let originalSnapshot: QuerySnapshot; + + return initialSnapshot(snapshot => { + return nextSnapshot(snapshot, () => + watchHelper.sendDoc(doc1, {foo: '1'}), + ).then(snapshot => { + originalSnapshot = snapshot; + }); + }).then(() => + initialSnapshot(snapshot => { + return nextSnapshot(snapshot, () => + watchHelper.sendDoc(doc1, {foo: 1}), + ).then(snapshot => { + expect(snapshot.isEqual(originalSnapshot)).to.be.false; + }); + }), + ); + }); + + it('for snapshots with different queries', () => { + let firstSnapshot: QuerySnapshot; + + return initialSnapshot(snapshot => { + firstSnapshot = snapshot; + }).then(() => { + watchHelper = new WatchHelper(streamHelper, includeQuery(), targetId); + return watchHelper.runTest(includeQueryJSON(), () => { + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper.await('snapshot').then(snapshot => { + expect(snapshot.isEqual(firstSnapshot)).to.be.false; + }); + }); + }); + }); + + it('for objects with different type', () => { + return initialSnapshot(snapshot => { + expect(snapshot.isEqual('foo' as InvalidApiUsage)).to.be.false; + expect(snapshot.isEqual({} as InvalidApiUsage)).to.be.false; + expect(snapshot.isEqual(new GeoPoint(0, 0) as InvalidApiUsage)).to.be + .false; + }); + }); + }); + + it('handles delete and re-add in same snapshot', () => { + return watchHelper.runTest(collQueryJSON(), () => { + // Mock the server responding to the query. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY); + + // Add a result. + watchHelper.sendDoc(doc1, {foo: 'a'}); + watchHelper.sendSnapshot(1); + return watchHelper.await('snapshot'); + }) + .then(results => { + lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, { + docs: [snapshot(doc1, {foo: 'a'})], + docChanges: [added(doc1, {foo: 'a'})], + }); + + // Delete a doc and send the same doc again. Note that we did not + // increment the snapshot version to keep the update time the same. + watchHelper.sendDocDelete(doc1); + watchHelper.sendDoc(doc1, {foo: 'a'}); + + watchHelper.sendDoc(doc2, {foo: 'b'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(results => { + snapshotsEqual(lastSnapshot, 2, results, { + docs: [snapshot(doc1, {foo: 'a'}), snapshot(doc2, {foo: 'b'})], + docChanges: [added(doc2, {foo: 'b'})], + }); + }); + }); + }); +}); + +describe('DocumentReference watch', () => { + // The document to query. + let doc: DocumentReference; + + let firestore: Firestore; + let targetId: number; + let watchHelper: WatchHelper; + let streamHelper: StreamHelper; + + // The proto JSON that should be sent for the watch. + const watchJSON = () => { + return { + database: `projects/${PROJECT_ID}/databases/(default)`, + addTarget: { + documents: { + documents: [doc.formattedName], + }, + targetId, + }, + }; + }; + + // The proto JSON that should be sent for a resumed query. + const resumeTokenJSON = (resumeToken: Uint8Array) => { + return { + database: `projects/${PROJECT_ID}/databases/(default)`, + addTarget: { + documents: { + documents: [doc.formattedName], + }, + targetId, + resumeToken, + }, + }; + }; + + beforeEach(async () => { + // We are intentionally skipping the delays to ensure fast test execution. + // The retry semantics are unaffected by this, as we maintain their + // asynchronous behavior. + setTimeoutHandler((op, timeout) => { + if (timeout !== WATCH_IDLE_TIMEOUT_MS) { + setImmediate(op); + } + }); + + targetId = 0x1; + streamHelper = new StreamHelper(); + + const overrides = {listen: streamHelper.getListenCallback()}; + firestore = await createInstance(overrides); + doc = firestore.doc('col/doc'); + watchHelper = new WatchHelper(streamHelper, doc, targetId); + }); + + afterEach(() => { + setTimeoutHandler(setTimeout); + return verifyInstance(firestore); + }); + + it('with invalid callbacks', () => { + expect(() => doc.onSnapshot('foo' as InvalidApiUsage)).to.throw( + 'Value for argument "onNext" is not a valid function.', + ); + + expect(() => doc.onSnapshot(() => {}, 'foo' as InvalidApiUsage)).to.throw( + 'Value for argument "onError" is not a valid function.', + ); + }); + + it('without error callback', done => { + const unsubscribe = doc.onSnapshot(() => { + unsubscribe(); + done(); + }); + + void streamHelper.awaitOpen().then(() => { + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + }); + }); + + it('handles invalid listen protos', () => { + return watchHelper.runFailedTest( + watchJSON(), + () => { + // Mock the server responding to the watch with an invalid proto. + streamHelper.write({invalid: true}); + }, + 'Unknown listen response type: {"invalid":true}', + ); + }); + + it('handles invalid target change protos', () => { + return watchHelper.runFailedTest( + watchJSON(), + () => { + // Mock the server responding to the watch with an invalid proto. + streamHelper.write({ + targetChange: { + targetChangeType: 'INVALID', + targetIds: [0xfeed], + }, + }); + }, + 'Unknown target change type: {"targetChangeType":"INVALID",' + + '"targetIds":[65261]}', + ); + }); + + it('handles remove target change protos', () => { + return watchHelper.runFailedTest( + watchJSON(), + () => { + watchHelper.sendRemoveTarget(); + }, + 'Error 13: internal error', + ); + }); + + it('handles remove target change with code', () => { + return watchHelper.runFailedTest( + watchJSON(), + () => { + watchHelper.sendRemoveTarget(7); + }, + 'Error 7: test remove', + ); + }); + + it('handles changing a doc', () => { + return watchHelper.runTest(watchJSON(), () => { + // Mock the server responding to the watch. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(snapshot => { + expect(snapshot.exists).to.be.false; + + // Add a result. + watchHelper.sendDoc(doc, {foo: 'a'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(snapshot => { + expect(snapshot.exists).to.be.true; + expect(snapshot.createTime!.isEqual(new Timestamp(1, 2))).to.be.true; + expect(snapshot.updateTime!.isEqual(new Timestamp(3, 1))).to.be.true; + expect(snapshot.get('foo')).to.equal('a'); + + // Change the document. + watchHelper.sendDoc(doc, {foo: 'b'}); + watchHelper.sendSnapshot(3); + return watchHelper.await('snapshot'); + }) + .then(snapshot => { + expect(snapshot.exists).to.be.true; + expect(snapshot.get('foo')).to.equal('b'); + }); + }); + }); + + it('ignores non-matching doc', () => { + return watchHelper.runTest(watchJSON(), () => { + // Mock the server responding to the watch. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(snapshot => { + expect(snapshot.exists).to.be.false; + + streamHelper.write({ + documentChange: { + document: { + name: `projects/${PROJECT_ID}/databases/(default)/documents/col/wrong`, + fields: {}, + createTime: {seconds: 1, nanos: 2}, + updateTime: {seconds: 3, nanos: 4}, + }, + targetIds: [targetId], + }, + }); + + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(snapshot => { + expect(snapshot.exists).to.be.false; + }); + }); + }); + + it('reconnects after error', () => { + const resumeToken = Buffer.from([0xabcd]); + + return watchHelper.runTest(watchJSON(), () => { + // Mock the server responding to the watch. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(snapshot => { + expect(snapshot.exists).to.be.false; + + // Add a result. + watchHelper.sendDoc(doc, {foo: 'a'}); + watchHelper.sendSnapshot(2, resumeToken); + return watchHelper.await('snapshot'); + }) + .then(snapshot => { + expect(snapshot.exists).to.be.true; + expect(snapshot.get('foo')).to.equal('a'); + + streamHelper.destroyStream(); + return streamHelper.awaitReopen(); + }) + .then(request => { + verifyRequest(request, resumeTokenJSON(resumeToken)); + // Change the document. + watchHelper.sendDoc(doc, {foo: 'b'}); + watchHelper.sendSnapshot(3, resumeToken); + return watchHelper.await('snapshot'); + }) + .then(snapshot => { + expect(snapshot.exists).to.be.true; + expect(snapshot.get('foo')).to.equal('b'); + + // Remove the document. + watchHelper.sendDocDelete(doc); + watchHelper.sendSnapshot(4); + return watchHelper.await('snapshot'); + }) + .then(snapshot => { + expect(snapshot.exists).to.be.false; + expect(streamHelper.streamCount).to.equal(2); + }); + }); + }); + + it('combines multiple change events for the same doc', () => { + return watchHelper.runTest(watchJSON(), () => { + // Mock the server responding to the watch. + watchHelper.sendAddTarget(); + + // Add a result. + watchHelper.sendDoc(doc, {foo: 'a'}); + // Modify it. + watchHelper.sendDoc(doc, {foo: 'b'}); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(snapshot => { + expect(snapshot.get('foo')).to.equal('b'); + + // Modify it two more times. + watchHelper.sendDoc(doc, {foo: 'c'}); + watchHelper.sendDoc(doc, {foo: 'd'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(snapshot => { + expect(snapshot.get('foo')).to.equal('d'); + + // Remove it, delete it, and then add it again. + watchHelper.sendDocRemove(doc, {foo: 'e'}); + watchHelper.sendDocDelete(doc); + watchHelper.sendDoc(doc, {foo: 'f'}); + watchHelper.sendSnapshot(3); + return watchHelper.await('snapshot'); + }) + .then(snapshot => { + expect(snapshot.get('foo')).to.equal('f'); + }); + }); + }); + + it('handles deleting a doc', () => { + return watchHelper.runTest(watchJSON(), () => { + // Mock the server responding to the watch. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(snapshot => { + expect(snapshot.exists).to.be.false; + + // Add a result. + watchHelper.sendDoc(doc, {foo: 'a'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(snapshot => { + expect(snapshot.exists).to.be.true; + + // Delete the document. + watchHelper.sendDocDelete(doc); + watchHelper.sendSnapshot(3); + return watchHelper.await('snapshot'); + }) + .then(snapshot => { + expect(snapshot.exists).to.be.false; + }); + }); + }); + + it('handles removing a doc', () => { + return watchHelper.runTest(watchJSON(), () => { + // Mock the server responding to the watch. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(snapshot => { + expect(snapshot.exists).to.be.false; + + // Add a result. + watchHelper.sendDoc(doc, {foo: 'a'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(snapshot => { + expect(snapshot.exists).to.be.true; + + // Remove the document. + watchHelper.sendDocRemove(doc, {foo: 'c'}); + watchHelper.sendSnapshot(3); + return watchHelper.await('snapshot'); + }) + .then(snapshot => { + expect(snapshot.exists).to.be.false; + }); + }); + }); + + it('handles reset', () => { + return watchHelper.runTest(watchJSON(), () => { + // Mock the server responding to the watch. + watchHelper.sendAddTarget(); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(1); + return watchHelper + .await('snapshot') + .then(() => { + // Add three results. + watchHelper.sendDoc(doc, {foo: 'a'}); + watchHelper.sendSnapshot(2); + return watchHelper.await('snapshot'); + }) + .then(snapshot => { + expect(snapshot.get('foo')).to.equal('a'); + + // Send a RESET. + streamHelper.write({ + targetChange: { + targetChangeType: 'RESET', + targetIds: [], + }, + }); + + // Send the modified doc. + watchHelper.sendDoc(doc, {foo: 'b'}); + watchHelper.sendCurrent(); + watchHelper.sendSnapshot(3); + return watchHelper.await('snapshot'); + }) + .then(snapshot => { + expect(snapshot.get('foo')).to.equal('b'); + }); + }); + }); +}); + +describe('Query comparator', () => { + let firestore: Firestore; + let colRef: Query; + let doc1: DocumentReference; + let doc2: DocumentReference; + let doc3: DocumentReference; + let doc4: DocumentReference; + + beforeEach(async () => { + firestore = await createInstance(); + + colRef = firestore.collection('col'); + + doc1 = firestore.doc('col/doc1'); + doc2 = firestore.doc('col/doc2'); + doc3 = firestore.doc('col/doc3'); + doc4 = firestore.doc('col/doc4'); + }); + + afterEach(() => verifyInstance(firestore)); + + function testSort( + query: Query, + input: QueryDocumentSnapshot[], + expected: QueryDocumentSnapshot[], + ) { + const comparator = query.comparator(); + input.sort(comparator); + docsEqual(input, expected); + } + + it('handles basic case', () => { + const query = colRef.orderBy('foo'); + + const input = [ + snapshot(doc3, {foo: 2}), + snapshot(doc4, {foo: 1}), + snapshot(doc2, {foo: 2}), + ]; + + const expected = [ + snapshot(doc4, {foo: 1}), + snapshot(doc2, {foo: 2}), + snapshot(doc3, {foo: 2}), + ]; + + testSort(query, input, expected); + }); + + it('handles descending case', () => { + const query = colRef.orderBy('foo', 'desc'); + + const input = [ + snapshot(doc3, {foo: 2}), + snapshot(doc4, {foo: 1}), + snapshot(doc2, {foo: 2}), + ]; + + const expected = [ + snapshot(doc3, {foo: 2}), + snapshot(doc2, {foo: 2}), + snapshot(doc4, {foo: 1}), + ]; + + testSort(query, input, expected); + }); + + it('handles nested fields', () => { + const query = colRef.orderBy('foo.bar'); + + const input = [ + snapshot(doc1, {foo: {bar: 1}}), + snapshot(doc2, {foo: {bar: 2}}), + snapshot(doc3, {foo: {bar: 2}}), + ]; + + const expected = [ + snapshot(doc1, {foo: {bar: 1}}), + snapshot(doc2, {foo: {bar: 2}}), + snapshot(doc3, {foo: {bar: 2}}), + ]; + + testSort(query, input, expected); + }); + + it('fails on missing fields', () => { + const query = colRef.orderBy('bar'); + + const input = [ + snapshot(doc3, {foo: 2}), + snapshot(doc1, {foo: 1}), + snapshot(doc2, {foo: 2}), + ]; + + const comparator = query.comparator(); + expect(() => input.sort(comparator)).to.throw( + "Trying to compare documents on fields that don't exist", + ); + }); +}); diff --git a/handwritten/firestore/dev/test/write-batch.ts b/handwritten/firestore/dev/test/write-batch.ts new file mode 100644 index 00000000000..2eea68907ef --- /dev/null +++ b/handwritten/firestore/dev/test/write-batch.ts @@ -0,0 +1,437 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {DocumentData} from '@google-cloud/firestore'; + +import {describe, it, beforeEach, afterEach} from 'mocha'; +import {expect} from 'chai'; + +import {Status} from 'google-gax'; +import { + FieldValue, + Firestore, + setLogFunction, + Timestamp, + WriteBatch, + WriteResult, + QueryDocumentSnapshot, +} from '../src'; +import { + ApiOverride, + createInstance, + InvalidApiUsage, + response, + verifyInstance, + Post, +} from './util/helpers'; + +const REQUEST_TIME = 'REQUEST_TIME'; + +// Change the argument to 'console.log' to enable debug output. +setLogFunction(null); + +const PROJECT_ID = 'test-project'; + +describe('set() method', () => { + let firestore: Firestore; + let writeBatch: WriteBatch; + + beforeEach(() => { + return createInstance().then(firestoreClient => { + firestore = firestoreClient; + writeBatch = firestore.batch(); + }); + }); + + afterEach(() => verifyInstance(firestore)); + + it('requires document name', () => { + expect(() => (writeBatch as InvalidApiUsage).set()).to.throw( + 'Value for argument "documentRef" is not a valid DocumentReference.', + ); + }); + + it('requires object', () => { + expect(() => + (writeBatch as InvalidApiUsage).set(firestore.doc('sub/doc')), + ).to.throw( + 'Value for argument "data" is not a valid Firestore document. Input is not a plain JavaScript object.', + ); + }); + + it('accepts document data', () => { + writeBatch.set(firestore.doc('sub/doc'), {foo: 'bar'}); + }); + + it('works with null objects', () => { + const nullObject = Object.create(null); + nullObject.bar = 'ack'; + writeBatch.set(firestore.doc('sub/doc'), nullObject); + }); + + it('requires the correct converter for Partial usage', async () => { + const converter = { + toFirestore(post: Post): DocumentData { + return {title: post.title, author: post.author}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): Post { + const data = snapshot.data(); + return new Post(data.title, data.author); + }, + }; + const ref = firestore.doc('sub/doc').withConverter(converter); + expect(() => + writeBatch.set(ref, {title: 'foo'} as Partial, {merge: true}), + ).to.throw( + 'Value for argument "data" is not a valid Firestore document. Cannot use "undefined" as a Firestore value (found in field "author").', + ); + }); +}); + +describe('delete() method', () => { + let firestore: Firestore; + let writeBatch: WriteBatch; + + beforeEach(() => { + return createInstance().then(firestoreInstance => { + firestore = firestoreInstance; + writeBatch = firestore.batch(); + }); + }); + + afterEach(() => verifyInstance(firestore)); + + it('requires document name', () => { + expect(() => (writeBatch as InvalidApiUsage).delete()).to.throw( + 'Value for argument "documentRef" is not a valid DocumentReference.', + ); + }); + + it('accepts preconditions', () => { + writeBatch.delete(firestore.doc('sub/doc'), { + lastUpdateTime: new Timestamp(479978400, 123000000), + }); + }); +}); + +describe('update() method', () => { + let firestore: Firestore; + let writeBatch: WriteBatch; + + beforeEach(() => { + return createInstance().then(firestoreInstance => { + firestore = firestoreInstance; + writeBatch = firestore.batch(); + }); + }); + + afterEach(() => verifyInstance(firestore)); + + it('requires document name', () => { + expect(() => writeBatch.update({} as InvalidApiUsage, {})).to.throw( + 'Value for argument "documentRef" is not a valid DocumentReference.', + ); + }); + + it('requires object', () => { + expect(() => { + writeBatch.update( + firestore.doc('sub/doc'), + firestore.doc('sub/doc') as InvalidApiUsage, + ); + }).to.throw( + 'Update() requires either a single JavaScript object or an alternating list of field/value pairs that can be followed by an optional precondition. Value for argument "dataOrField" is not a valid Firestore document. Detected an object of type "DocumentReference" that doesn\'t match the expected instance. Please ensure that the Firestore types you are using are from the same NPM package.', + ); + }); + + it('accepts preconditions', () => { + writeBatch.update( + firestore.doc('sub/doc'), + {foo: 'bar'}, + {lastUpdateTime: new Timestamp(479978400, 123000000)}, + ); + }); + + it('works with null objects', () => { + const nullObject = Object.create(null); + nullObject.bar = 'ack'; + writeBatch.update(firestore.doc('sub/doc'), nullObject); + }); +}); + +describe('create() method', () => { + let firestore: Firestore; + let writeBatch: WriteBatch; + + beforeEach(() => { + return createInstance().then(firestoreClient => { + firestore = firestoreClient; + writeBatch = firestore.batch(); + }); + }); + + afterEach(() => verifyInstance(firestore)); + + it('requires document name', () => { + expect(() => (writeBatch as InvalidApiUsage).create()).to.throw( + 'Value for argument "documentRef" is not a valid DocumentReference.', + ); + }); + + it('requires object', () => { + expect(() => { + (writeBatch as InvalidApiUsage).create(firestore.doc('sub/doc')); + }).to.throw( + 'Value for argument "data" is not a valid Firestore document. Input is not a plain JavaScript object.', + ); + }); + + it('works with null objects', () => { + const nullObject = Object.create(null); + nullObject.bar = 'ack'; + writeBatch.create(firestore.doc('sub/doc'), nullObject); + }); +}); + +describe('batch support', () => { + const documentName = `projects/${PROJECT_ID}/databases/(default)/documents/col/doc`; + + let firestore: Firestore; + let writeBatch: WriteBatch; + + beforeEach(() => { + const overrides: ApiOverride = { + commit: (request, options) => { + expect(options!.retry!.retryCodes).contains(Status.ABORTED); + + expect(request).to.deep.eq({ + database: `projects/${PROJECT_ID}/databases/(default)`, + writes: [ + { + update: { + fields: {}, + name: documentName, + }, + updateTransforms: [ + { + fieldPath: 'foo', + setToServerValue: REQUEST_TIME, + }, + ], + }, + { + currentDocument: { + exists: true, + }, + update: { + fields: { + foo: { + stringValue: 'bar', + }, + }, + name: documentName, + }, + updateMask: { + fieldPaths: ['foo'], + }, + }, + { + currentDocument: { + exists: false, + }, + update: { + fields: {}, + name: documentName, + }, + }, + { + delete: documentName, + }, + ], + }); + return response({ + commitTime: { + nanos: 0, + seconds: 0, + }, + writeResults: [ + { + updateTime: { + nanos: 0, + seconds: 0, + }, + }, + { + updateTime: { + nanos: 1, + seconds: 1, + }, + }, + { + updateTime: { + nanos: 2, + seconds: 2, + }, + }, + { + updateTime: { + nanos: 3, + seconds: 3, + }, + }, + ], + }); + }, + }; + return createInstance(overrides).then(firestoreClient => { + firestore = firestoreClient; + writeBatch = firestore.batch(); + }); + }); + + afterEach(() => verifyInstance(firestore)); + + function verifyResponse(writeResults: WriteResult[]) { + expect(writeResults[0].writeTime.isEqual(new Timestamp(0, 0))).to.be.true; + expect(writeResults[1].writeTime.isEqual(new Timestamp(1, 1))).to.be.true; + expect(writeResults[2].writeTime.isEqual(new Timestamp(2, 2))).to.be.true; + expect(writeResults[3].writeTime.isEqual(new Timestamp(3, 3))).to.be.true; + } + + it('accepts multiple operations', () => { + const documentName = firestore.doc('col/doc'); + + writeBatch.set(documentName, {foo: FieldValue.serverTimestamp()}); + writeBatch.update(documentName, {foo: 'bar'}); + writeBatch.create(documentName, {}); + writeBatch.delete(documentName); + + return writeBatch.commit().then(resp => { + verifyResponse(resp); + }); + }); + + it('chains multiple operations', () => { + const documentName = firestore.doc('col/doc'); + + return writeBatch + .set(documentName, {foo: FieldValue.serverTimestamp()}) + .update(documentName, {foo: 'bar'}) + .create(documentName, {}) + .delete(documentName) + .commit() + .then(resp => { + verifyResponse(resp); + }); + }); + + it('handles exception', () => { + firestore.request = () => { + return Promise.reject(new Error('Expected exception')); + }; + + return firestore + .batch() + .commit() + .then(() => { + throw new Error('Unexpected success in Promise'); + }) + .catch(err => { + expect(err.message).to.equal('Expected exception'); + }); + }); + + it('cannot append to committed batch', () => { + const documentName = firestore.doc('col/doc'); + + const batch = firestore.batch(); + batch.set(documentName, {foo: FieldValue.serverTimestamp()}); + batch.update(documentName, {foo: 'bar'}); + batch.create(documentName, {}); + batch.delete(documentName); + const promise = batch.commit(); + + expect(() => { + batch.set(documentName, {}); + }).to.throw('Cannot modify a WriteBatch that has been committed.'); + + return promise; + }); + + it('can reset a committed batch', async () => { + const documentName = firestore.doc('col/doc'); + + const batch = firestore.batch(); + batch.set(documentName, {foo: FieldValue.serverTimestamp()}); + batch.update(documentName, {foo: 'bar'}); + batch.create(documentName, {}); + batch.delete(documentName); + await batch.commit(); + + batch._reset(); + + batch.set(documentName, {foo: FieldValue.serverTimestamp()}); + batch.update(documentName, {foo: 'bar'}); + batch.create(documentName, {}); + batch.delete(documentName); + await batch.commit(); + }); + + it('can commit an unmodified batch multiple times', () => { + const documentName = firestore.doc('col/doc'); + + const batch = firestore.batch(); + batch.set(documentName, {foo: FieldValue.serverTimestamp()}); + batch.update(documentName, {foo: 'bar'}); + batch.create(documentName, {}); + batch.delete(documentName); + return batch.commit().then(() => batch.commit); + }); + + it('can return same write result', () => { + const overrides: ApiOverride = { + commit: () => { + return response({ + commitTime: { + nanos: 0, + seconds: 0, + }, + writeResults: [ + { + updateTime: { + nanos: 0, + seconds: 0, + }, + }, + { + updateTime: {}, + }, + ], + }); + }, + }; + + return createInstance(overrides).then(firestore => { + const documentName = firestore.doc('col/doc'); + + const batch = firestore.batch(); + batch.set(documentName, {}); + batch.set(documentName, {}); + + return batch.commit().then(results => { + expect(results[0].isEqual(results[1])).to.be.true; + }); + }); + }); +}); diff --git a/handwritten/firestore/docfx.json b/handwritten/firestore/docfx.json new file mode 100644 index 00000000000..e69de29bb2d diff --git a/handwritten/firestore/linkinator.config.json b/handwritten/firestore/linkinator.config.json new file mode 100644 index 00000000000..29a223b6db6 --- /dev/null +++ b/handwritten/firestore/linkinator.config.json @@ -0,0 +1,10 @@ +{ + "recurse": true, + "skip": [ + "https://codecov.io/gh/googleapis/", + "www.googleapis.com", + "img.shields.io" + ], + "silent": true, + "concurrency": 10 +} diff --git a/handwritten/firestore/owlbot.py b/handwritten/firestore/owlbot.py new file mode 100644 index 00000000000..284518f7a07 --- /dev/null +++ b/handwritten/firestore/owlbot.py @@ -0,0 +1,246 @@ +import synthtool as s +import synthtool.gcp as gcp +import synthtool.languages.node_mono_repo as node +import logging +import os +import subprocess +from pathlib import Path +from synthtool import _tracked_paths +import shutil +from synthtool import shell +from synthtool.log import logger + +logging.basicConfig(level=logging.DEBUG) + +staging = Path("owl-bot-staging") +if staging.is_dir(): + try: + v1_admin_library = staging / "admin/v1" + v1beta1_library = staging / "firestore" / "v1beta1" + v1_library = staging / "firestore" / "v1" + + _tracked_paths.add(v1_admin_library) + _tracked_paths.add(v1beta1_library) + _tracked_paths.add(v1_library) + + # skip index, protos, package.json, and README.md + s.copy(v1_admin_library, "handwritten/firestore/dev", excludes=["package.json", "README.md", "src/index.ts", "src/v1/index.ts", + "tsconfig.json", "linkinator.config.json", "webpack.config.js"]) + s.copy(v1beta1_library, "handwritten/firestore/dev", excludes=["package.json", "README.md", "src/index.ts", "src/v1beta1/index.ts", + "tsconfig.json", "linkinator.config.json", "webpack.config.js"]) + s.copy(v1_library, "handwritten/firestore/dev", excludes=["package.json", "README.md", "src/index.ts", "src/v1/index.ts", + "tsconfig.json", "linkinator.config.json", "webpack.config.js"]) + + # Fix dropping of google-cloud-resource-header + # See: https://github.com/googleapis/nodejs-firestore/pull/375 + s.replace( + "handwritten/firestore/dev/src/v1beta1/firestore_client.ts", + r"return this\.innerApiCalls\.listen\(options\);", + "return this.innerApiCalls.listen({}, options);", + ) + s.replace( + "handwritten/firestore/dev/src/v1/firestore_client.ts", + r"return this\.innerApiCalls\.listen\(options\);", + "return this.innerApiCalls.listen({}, options);", + ) + s.replace( + "handwritten/firestore/dev/test/gapic_firestore_v1.ts", + r"calledWithExactly\(undefined\)", + "calledWithExactly({}, undefined)", + ) + s.replace( + "handwritten/firestore/dev/src/v1beta1/firestore_client.ts", + r"return this\.innerApiCalls\.write\(options\);", + "return this.innerApiCalls.write({}, options);", + ) + s.replace( + "handwritten/firestore/dev/src/v1/firestore_client.ts", + r"return this\.innerApiCalls\.write\(options\);", + "return this.innerApiCalls.write({}, options);", + ) + s.replace( + "handwritten/firestore/dev/test/gapic_firestore_v1.ts", + r"calledWithExactly\(undefined\)", + "calledWithExactly({}, undefined)", + ) + + # use the existing proto .js / .d.ts files + s.replace( + "handwritten/firestore/dev/src/v1/firestore_client.ts", + r"/protos/protos'", + "/protos/firestore_v1_proto_api'" + ) + s.replace( + "handwritten/firestore/dev/test/gapic_firestore_v1.ts", + r"/protos/protos'", + "/protos/firestore_v1_proto_api'" + ) + s.replace( + "handwritten/firestore/dev/test/gapic_firestore_v1.ts", + r"import \* as firestoreModule from '\.\./src';", + "import * as firestoreModule from '../src/v1';" + ) + s.replace( + "handwritten/firestore/dev/test/gapic_firestore_v1.ts", + r"firestoreModule\.v1", + "firestoreModule" + ) + s.replace( + "handwritten/firestore/dev/src/v1/firestore_admin_client.ts", + r"/protos/protos'", + "/protos/firestore_admin_v1_proto_api'" + ) + s.replace( + "handwritten/firestore/dev/test/gapic_firestore_admin_v1.ts", + r"/protos/protos'", + "/protos/firestore_admin_v1_proto_api'" + ) + s.replace( + "handwritten/firestore/dev/test/gapic_firestore_admin_v1.ts", + r"import \* as firestoreadminModule from '\.\./src';", + "import * as firestoreadminModule from '../src/v1';" + ) + s.replace( + "handwritten/firestore/dev/test/gapic_firestore_admin_v1.ts", + r"firestoreadminModule\.v1", + "firestoreadminModule" + ) + s.replace( + "handwritten/firestore/dev/src/v1beta1/firestore_client.ts", + r"/protos/protos'", + "/protos/firestore_v1beta1_proto_api'" + ) + s.replace( + "handwritten/firestore/dev/test/gapic_firestore_v1beta1.ts", + r"/protos/protos'", + "/protos/firestore_v1beta1_proto_api'" + ) + s.replace( + "handwritten/firestore/dev/test/gapic_firestore_v1beta1.ts", + r"import \* as firestoreModule from \'../src\';", + "import * as firestoreModule from '../src/v1beta1';" + ) + s.replace( + "handwritten/firestore/dev/test/gapic_firestore_v1beta1.ts", + r"firestoreModule\.v1beta1", + "firestoreModule" + ) + s.replace( + "handwritten/firestore/dev/src/v1/firestore_client.ts", + r"\.\./\.\./protos/protos.json", + "../../protos/v1.json" + ) + s.replace( + "handwritten/firestore/dev/src/v1/firestore_admin_client.ts", + r"\.\./\.\./protos/protos.json", + "../../protos/admin_v1.json" + ) + s.replace( + "handwritten/firestore/dev/src/v1beta1/firestore_client.ts", + r"\.\./\.\./protos/protos.json", + "../../protos/v1beta1.json" + ) + s.replace( + "handwritten/firestore/dev/test/gapic_firestore_v1.ts", + r"\.\./protos/protos.json", + "../protos/v1.json" + ) + s.replace( + "handwritten/firestore/dev/test/gapic_firestore_admin_v1.ts", + r"\.\./protos/protos.json", + "../protos/admin_v1.json" + ) + s.replace( + "handwritten/firestore/dev/test/gapic_firestore_v1beta1.ts", + r"\.\./protos/protos.json", + "../protos/v1beta1.json" + ) + + # Mark v1beta1 as deprecated + s.replace( + "handwritten/firestore/dev/src/v1beta1/firestore_client.ts", + r"@class", + "@class\n * @deprecated Use v1/firestore_client instead." + ) + s.replace( + "handwritten/firestore/dev/src/v1beta1/firestore_client.ts", + r"const version", + "// tslint:disable deprecation\n\nconst version", + 1 + ) + + os.rename("handwritten/firestore/dev/.gitignore", "handwritten/firestore/.gitignore") + os.rename("handwritten/firestore/dev/.eslintignore", "handwritten/firestore/.eslintignore") + os.rename("handwritten/firestore/dev/.mocharc.js", "handwritten/firestore/.mocharc.js") + os.rename("handwritten/firestore/dev/.jsdoc.js", "handwritten/firestore/.jsdoc.js") + os.rename("handwritten/firestore/dev/.prettierrc.js", "handwritten/firestore/.prettierrc.js") + os.unlink("handwritten/firestore/dev/.eslintrc.json") + + s.replace(".jsdoc.js", r"protos", "build/protos", 1) + + # Remove auto-generated packaging tests + os.system('rm -rf handwritten/firestore/dev/system-test/fixtures handwritten/firestore/dev/system-test/install.ts') + + node.compile_protos_hermetic(relative_dir="handwritten/firestore") + os.unlink('handwritten/firestore/dev/protos.js') + os.unlink('handwritten/firestore/dev/protos.d.ts') + os.unlink('handwritten/firestore/dev/protos.json') + subprocess.run('handwritten/firestore/dev/protos/update.sh', shell=True) + + # Copy types into types/ + logger.debug("Running compile...") + shell.run(["npm", "run", "compile"], cwd="handwritten/firestore", hide_output=True) + s.copy("handwritten/firestore/build/src/v1/firestore*.d.ts", "handwritten/firestore/types/v1") + s.copy("handwritten/firestore/build/src/v1beta1/firestore_client.d.ts", "handwritten/firestore/types/v1beta1") + s.copy("handwritten/firestore/build/protos/firestore*.d.ts", "handwritten/firestore/types/protos") + s.replace( + "handwritten/firestore/types/v1/firestore_client.d.ts", + r"../../protos", + "../protos" + ) + s.replace( + "handwritten/firestore/types/v1/firestore_admin_client.d.ts", + r"../../protos", + "../protos" + ) + s.replace( + "handwritten/firestore/types/v1beta1/firestore_client.d.ts", + r"../../protos", + "../protos" + ) + s.replace( + "handwritten/firestore/types/protos/firestore_admin_v1_proto_api.d.ts", + 'import Long = require\("long"\);', + "" + ) + s.replace( + "handwritten/firestore/types/protos/firestore_v1_proto_api.d.ts", + r'import Long = require\("long"\);', + "" + ) + s.replace( + "handwritten/firestore/types/protos/firestore_v1beta1_proto_api.d.ts", + r'import Long = require\("long"\);', + "" + ) + + finally: + # The staging directory should never be merged into the main branch. + shutil.rmtree(staging) + + +# Copy template files +common_templates = gcp.CommonTemplates() +templates = common_templates.node_mono_repo_library(relative_dir="handwritten/firestore", + source_location="build/src", test_project="node-gcloud-ci" +) + +s.copy(templates, destination="handwritten/firestore", excludes=[".eslintrc.json", ".kokoro/**/*", ".github/CODEOWNERS", "README.md"]) + +# Remove generated samples from veneer library: +shell.run(('rm', '-rf', 'handwritten/firestore/dev/samples/generated'), hide_output = False) + +shell.run(('node', 'handwritten/firestore/scripts/license.js', 'handwritten/firestore/dev/protos'), hide_output = False) +shell.run(('node', 'handwritten/firestore/scripts/license.js', 'handwritten/firestore/types'), hide_output = False) + +node.fix_hermetic(relative_dir="handwritten/firestore") # fix formatting \ No newline at end of file diff --git a/handwritten/firestore/package.json b/handwritten/firestore/package.json new file mode 100644 index 00000000000..99e404ce694 --- /dev/null +++ b/handwritten/firestore/package.json @@ -0,0 +1,135 @@ +{ + "name": "@google-cloud/firestore", + "description": "Firestore Client Library for Node.js", + "version": "8.3.0", + "license": "Apache-2.0", + "author": "Google Inc.", + "engines": { + "node": ">=18" + }, + "repository": { + "type": "git", + "directory": "handwritten/firestore", + "url": "https://github.com/googleapis/google-cloud-node.git" + }, + "main": "./build/src/index.js", + "types": "./types/firestore.d.ts", + "files": [ + "build/protos", + "build/src", + "!build/src/**/*.map", + "types", + "pipelines" + ], + "keywords": [ + "google apis client", + "google api client", + "google apis", + "google api", + "google", + "google cloud platform", + "google cloud", + "cloud", + "firestore" + ], + "scripts": { + "precloud-rad": "npm run compile", + "cloud-rad": "NO_UPLOAD=1 npx @google-cloud/cloud-rad", + "preapi-report": "npm run compile", + "api-report": "node scripts/api-report.mjs", + "predocs": "npm run compile", + "docs": "jsdoc -c .jsdoc.js", + "system-test:rest": "FIRESTORE_PREFER_REST=true mocha build/system-test --timeout 1200000", + "system-test:named-db:rest": "FIRESTORE_NAMED_DATABASE=test-db FIRESTORE_PREFER_REST=true mocha build/system-test --timeout 1200000", + "system-test:grpc": "mocha build/system-test --timeout 1200000", + "system-test:named-db:grpc": "FIRESTORE_NAMED_DATABASE=test-db mocha build/system-test --timeout 1200000", + "system-test:emulator:rest": "FIRESTORE_EMULATOR_HOST=localhost:8080 FIRESTORE_PREFER_REST=true mocha build/system-test --timeout 1200000", + "system-test:named-db:emulator:rest": "FIRESTORE_NAMED_DATABASE=test-db FIRESTORE_EMULATOR_HOST=localhost:8080 FIRESTORE_PREFER_REST=true mocha build/system-test --timeout 1200000", + "system-test:emulator:grpc": "FIRESTORE_EMULATOR_HOST=localhost:8080 mocha build/system-test --timeout 1200000", + "system-test:named-db:emulator:grpc": "FIRESTORE_NAMED_DATABASE=test-db FIRESTORE_EMULATOR_HOST=localhost:8080 mocha build/system-test --timeout 1200000", + "system-test": "npm run system-test:grpc && npm run system-test:rest && npm run system-test:named-db:grpc && npm run system-test:named-db:rest", + "system-test:emulator": "npm run system-test:emulator:grpc && npm run system-test:emulator:rest && npm run system-test:named-db:emulator:grpc && npm run system-test:named-db:emulator:rest", + "presystem-test": "npm run compile", + "samples-test": "npm link && cd samples/ && npm link ../ && npm test && cd ../", + "conformance": "mocha build/conformance", + "preconformance": "npm run compile", + "test-only": "c8 mocha build/test", + "pretest-only": "npm run compile", + "test": "npm run test-only && npm run conformance", + "lint": "gts check", + "clean": "gts clean", + "compile": "tsc -p .", + "postcompile": "node scripts/init-directories.js && cp -r dev/protos build && cp dev/src/v1beta1/*.json build/src/v1beta1/ && cp dev/src/v1/*.json build/src/v1/ && cp dev/conformance/test-definition.proto build/conformance && cp dev/conformance/conformance-tests/*.json build/conformance/conformance-tests && minifyProtoJson", + "fix": "gts fix", + "prepare": "npm run compile", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "prelint": "cd samples; npm link ../; npm install", + "precompile": "gts clean" + }, + "dependencies": { + "@opentelemetry/api": "^1.9.0", + "fast-deep-equal": "^3.1.3", + "functional-red-black-tree": "^1.0.1", + "google-gax": "^5.0.1", + "protobufjs": "^7.5.3" + }, + "devDependencies": { + "@google-cloud/cloud-rad": "^0.4.10", + "@google-cloud/opentelemetry-cloud-trace-exporter": "^3.0.0", + "@google-cloud/promisify": "^5.0.0", + "@google-cloud/trace-agent": "^8.0.0", + "@googleapis/cloudtrace": "^3.0.1", + "@opentelemetry/context-async-hooks": "^2.0.1", + "@opentelemetry/sdk-trace-node": "^2.0.1", + "@types/assert": "^1.5.11", + "@types/chai": "^4.3.20", + "@types/chai-as-promised": "^7.1.8", + "@types/duplexify": "^3.6.4", + "@types/extend": "^3.0.4", + "@types/mocha": "^10.0.10", + "@types/node": "^24.1.0", + "@types/sinon": "^17.0.4", + "@types/through2": "^2.0.41", + "c8": "^10.1.3", + "chai": "^4.5.0", + "chai-as-promised": "^7.1.2", + "codecov": "^3.8.3", + "duplexify": "^4.1.3", + "eslint-plugin-node": "^11.1.0", + "execa": "^9.6.0", + "extend": "^3.0.2", + "fs-extra": "^11.3.0", + "gapic-tools": "^1.0.2", + "gts": "^6.0.2", + "jsdoc": "^4.0.4", + "jsdoc-fresh": "^4.0.0", + "jsdoc-region-tag": "^3.0.0", + "length-prefixed-json-stream": "^1.0.1", + "linkinator": "^6.1.4", + "long": "^5.3.2", + "mkdirp": "^3.0.1", + "mocha": "^11.7.1", + "nise": "^6.1.1", + "path-to-regexp": "^8.2.0", + "protobufjs-cli": "^1.1.3", + "proxyquire": "^2.1.3", + "sinon": "^21.0.0", + "through2": "^4.0.2", + "ts-node": "^10.9.2", + "typescript": "^5.9.2" + }, + "exports": { + ".": { + "types": "./types/firestore.d.ts", + "default": "./build/src/index.js" + }, + "./pipelines": { + "types": "./types/pipelines.d.ts", + "default": "./build/src/pipelines/index.js" + }, + "./package.json": "./package.json", + "./build/src/path": "./build/src/path.js" + }, + "homepage": "https://github.com/googleapis/google-cloud-node/tree/main/handwritten/firestore" +} diff --git a/handwritten/firestore/pipelines/package.json b/handwritten/firestore/pipelines/package.json new file mode 100644 index 00000000000..1515c5eb2a2 --- /dev/null +++ b/handwritten/firestore/pipelines/package.json @@ -0,0 +1,10 @@ +{ + "name": "@google-cloud/firestore/pipelines", + "description": "pipelines", + "main": "../build/src/pipelines/index.js", + "typings": "../types/pipelines.d.ts", + "private": true, + "engines": { + "node": ">=14.0.0" + } +} diff --git a/handwritten/firestore/scripts/.eslintrc.yml b/handwritten/firestore/scripts/.eslintrc.yml new file mode 100644 index 00000000000..4e82c4b69ab --- /dev/null +++ b/handwritten/firestore/scripts/.eslintrc.yml @@ -0,0 +1,7 @@ +--- +rules: + no-console: off + no-unused-vars: off + node/no-unpublished-require: off + node/no-extraneous-require: off + diff --git a/handwritten/firestore/scripts/api-report.mjs b/handwritten/firestore/scripts/api-report.mjs new file mode 100644 index 00000000000..6b68ef13848 --- /dev/null +++ b/handwritten/firestore/scripts/api-report.mjs @@ -0,0 +1,122 @@ +/* + Copyright 2024 Google LLC + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +import { execaNode } from 'execa'; +import fs from 'fs-extra'; +import { join } from 'path'; +import { createRequire } from 'module'; + +async function apiReport(opts) { + const cwd = opts.cwd; + + // Location of the created API report file. + // This file should be checked in. + const outputDir = join(cwd, 'api-report'); + await fs.ensureDir(outputDir); + + console.log(outputDir); + + // Create API Extractor config file for the package. + // This config extends the API Extractor config file + // used by Cloud RAD, to ensure the base configuration + // is the sme. + const apiExtractorConfig = { + extends: join(opts.cloudRadApiExtractorConfigPath), + mainEntryPointFilePath: join(cwd, 'build', 'types', 'src', 'index.d.ts'), + projectFolder: cwd, + docModel: { + enabled: false, + }, + apiReport: { + enabled: true, + reportFolder: outputDir, + }, + dtsRollup: { + enabled: false, + }, + messages: { + extractorMessageReporting: { + 'ae-forgotten-export': { + logLevel: 'warning', + }, + 'ae-unresolved-link': { + // Error on unresolved link because this can + // lead to a bad user experience when reading docs. + logLevel: 'error' + }, + 'ae-extra-release-tag': { + // @internal tag is used for TSDoc + // @private tag is used for JSDoc + // TODO: Suppress this warning until we drop JSDoc. + logLevel: 'none' + } + }, + tsdocMessageReporting: { + 'tsdoc-param-tag-missing-hyphen': { + // TSDoc and JSDoc use different formats for param tags. + // TSDoc works fine without the hypen, and JSDoc does not use it. + // TODO: Suppress this warning until we drop JSDoc. + logLevel: 'none', + "addToApiReportFile": false + } + } + }, + }; + const apiExtractorConfigPath = join(cwd, 'api-extractor.json'); + await fs.writeFile( + apiExtractorConfigPath, + JSON.stringify(apiExtractorConfig, null, 2), + ); + + // Run API Extractor + const apiExtractorCmd = join( + process.cwd(), + 'node_modules', + '.bin', + 'api-extractor', + ); + await withLogs(execaNode)(apiExtractorCmd, ['run', '--local']); + + // Cleanup + await fs.remove(apiExtractorConfigPath); + + return outputDir; +} + +function withLogs(execaFn) { + return async function (cmd, args, cwd) { + const opts = {cwd}; + + opts.stdout = process.stdout; + opts.stderr = process.stderr; + + return execaFn(cmd, args, opts); + }; +} + +const require = createRequire(import.meta.url); +apiReport({ + cloudRadApiExtractorConfigPath: require.resolve( + '@google-cloud/cloud-rad/api-extractor.json', + ), + cwd: process.cwd(), +}) + .then(outputDir => { + console.log(`SUCCESS: API Report written to ${outputDir}`); + }) + .catch(err => { + console.log(`FAILED: ${err}`); + }); diff --git a/handwritten/firestore/scripts/init-directories.js b/handwritten/firestore/scripts/init-directories.js new file mode 100644 index 00000000000..adc337c413f --- /dev/null +++ b/handwritten/firestore/scripts/init-directories.js @@ -0,0 +1,21 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const mkdirp = require('mkdirp'); + +// We have to manually add the directory here because the docker image that +// runs CI does not have this directory. We also can't use `mkdir -p` in the +// package.json file because CI is also run on Windows, which does not support +// the `-p` flag. +mkdirp.sync('build/conformance/conformance-tests'); diff --git a/handwritten/firestore/scripts/license.js b/handwritten/firestore/scripts/license.js new file mode 100755 index 00000000000..96d2fdb6ad6 --- /dev/null +++ b/handwritten/firestore/scripts/license.js @@ -0,0 +1,61 @@ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const fs = require('fs'); +const path = require('path'); + +const LICENSE_HEADER = `/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +`; + +function addLicenses(dirNameReads) { + for (const dirNameRead of dirNameReads) { + iterateThroughFiles(dirNameRead); + } +} +function iterateThroughFiles(dirNameRead) { + console.log(dirNameRead); + if (fs.existsSync(path.join(dirNameRead))) { + const files = fs.readdirSync(dirNameRead); + files.forEach(file => { + const fileName = file.toString(); + const readName = path.join(dirNameRead, fileName); + if (fs.statSync(readName).isDirectory()) { + iterateThroughFiles(readName); + } else { + const content = fs.readFileSync(readName, 'utf-8'); + if (!content.includes('Copyright') && !fileName.endsWith('.json')) { + fs.writeFileSync(readName, `${LICENSE_HEADER}\n${content.trim()}\n`); + } + } + }); + } +} + +addLicenses(process.argv.slice(2)); diff --git a/handwritten/firestore/tsconfig.json b/handwritten/firestore/tsconfig.json new file mode 100644 index 00000000000..015884045b1 --- /dev/null +++ b/handwritten/firestore/tsconfig.json @@ -0,0 +1,31 @@ +{ + "extends": "./node_modules/gts/tsconfig-google.json", + "compilerOptions": { + "resolveJsonModule": true, + "outDir": "build", + "rootDir": "dev", + "lib": [ + "es2023", + "dom" + ], + "useUnknownInCatchVariables": false, + "composite": false, + "incremental": false, + "declaration": true, + "declarationDir": "build/types", + "stripInternal": false, + }, + "include": [ + "dev/src/*.d.ts", + "dev/src/*.ts", + "dev/src/**/*.ts", + "dev/src/v1/*.json", + "dev/src/v1beta1/*.json", + "dev/protos/*.json", + "dev/test/*.ts", + "dev/test/**/*.ts", + "dev/system-test/*.ts", + "dev/conformance/*.ts", + "types/*.d.ts" + ] +} diff --git a/handwritten/firestore/types/firestore.d.ts b/handwritten/firestore/types/firestore.d.ts new file mode 100644 index 00000000000..2272224edf0 --- /dev/null +++ b/handwritten/firestore/types/firestore.d.ts @@ -0,0 +1,11885 @@ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// We deliberately use `any` in the external API to not impose type-checking +// on end users. +/* eslint-disable @typescript-eslint/no-explicit-any */ +// Declare a global (ambient) namespace +// (used when not using import statement, but just script include). +declare namespace FirebaseFirestore { + /** Alias for `any` but used where a Firestore field value would be provided. */ + export type DocumentFieldValue = any; + /** + * Document data (for use with `DocumentReference.set()`) consists of fields + * mapped to values. + */ + export type DocumentData = { + [field: string]: DocumentFieldValue; + }; + /** + * Similar to Typescript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ + export type PartialWithFieldValue = + | Partial + | (T extends Primitive + ? T + : T extends {} + ? { + [K in keyof T]?: T[K] extends Function + ? T[K] + : PartialWithFieldValue | FieldValue; + } + : never); + /** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ + export type WithFieldValue = + | T + | (T extends Primitive + ? T + : T extends {} + ? { + [K in keyof T]: T[K] extends Function + ? T[K] + : WithFieldValue | FieldValue; + } + : never); + /** + * Update data (for use with [update]{@link DocumentReference#update}) + * that contains paths mapped to values. Fields that contain dots reference + * nested fields within the document. FieldValues can be passed in + * as property values. + * + * You can update a top-level field in your document by using the field name + * as a key (e.g. `foo`). The provided value completely replaces the contents + * for this field. + * + * You can also update a nested field directly by using its field path as a + * key (e.g. `foo.bar`). This nested field update replaces the contents at + * `bar` but does not modify other data under `foo`. + */ + export type UpdateData = T extends Primitive + ? T + : T extends {} + ? { + // If `string extends K`, this is an index signature like + // `{[key: string]: { foo: bool }}`. In the generated UpdateData + // indexed properties can match their type or any child types. + [K in keyof T]?: string extends K + ? PartialWithFieldValue> + : UpdateData | FieldValue; + } & NestedUpdateFields + : Partial; + + /** + * For the given type, return a union type of T + * and the types of all child properties of T. + */ + export type ChildTypes = + T extends Record + ? + | { + [K in keyof T & string]: ChildTypes; + }[keyof T & string] + | T + : T; + + /** Primitive types. */ + export type Primitive = string | number | boolean | undefined | null; + /** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ + export type NestedUpdateFields> = + UnionToIntersection< + { + // If `string extends K`, this is an index signature like + // `{[key: string]: { foo: bool }}`. We map these properties to + // `never`, which prevents prefixing a nested key with `[string]`. + // We don't want to generate a field like `[string].foo: bool`. + [K in keyof T & string]: string extends K + ? never + : ChildUpdateFields; + }[keyof T & string] // Also include the generated prefix-string keys. + >; + /** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ + export type ChildUpdateFields = + // Only allow nesting for map values + V extends Record + ? // Recurse into the map and add the prefix in front of each key + // (for example prefix 'bar.' to create: 'bar.baz' and 'bar.qux'). + AddPrefixToKeys> + : never; + /** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ + export type AddPrefixToKeys< + Prefix extends string, + T extends Record, + > = + // Remap K => Prefix.K. See https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#key-remapping-via-as + + // `string extends K : ...` is used to detect index signatures + // like `{[key: string]: bool}`. We map these properties to type `any` + // because a field path like `foo.[string]` will match `foo.bar` or a + // sub-path `foo.bar.baz`. Because it matches a sub-path, we have to + // make this type a union to including all types of the sub-path properties. + // This is a significant downside to using index signatures in types for `T` + // for `UpdateData`. + + { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K + ? ChildTypes + : T[K]; + }; + + /** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ + export type UnionToIntersection = ( + U extends unknown ? (k: U) => void : never + ) extends (k: infer I) => void + ? I + : never; + /** + * Utility type to create an type that only allows one + * property of the Type param T to be set. + * + * type XorY = OneOf<{ x: unknown, y: unknown}> + * let a = { x: "foo" } // OK + * let b = { y: "foo" } // OK + * let c = { a: "foo", y: "foo" } // Not OK + */ + export type OneOf = { + [K in keyof T]: Pick & { + [P in Exclude]?: undefined; + }; + }[keyof T]; + /** + * Sets or disables the log function for all active Firestore instances. + * + * @param logger A log function that takes a message (such as `console.log`) or + * `null` to turn off logging. + */ + function setLogFunction(logger: ((msg: string) => void) | null): void; + /** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties + * used for memoization, properties of types not supported by Firestore (such + * as `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In + * this context, this type is referred to as the "DbModel" and would be an + * object suitable for persisting into Firestore. For convenience, + * applications can implement `FirestoreDataConverter` and register the + * converter with Firestore objects, such as `DocumentReference` or `Query`, + * to automatically convert `AppModel` to `DbModel` when storing into + * Firestore, and convert `DbModel` to `AppModel` when retrieving from + * Firestore. + * + * @example + * + * Simple Example + * + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot) { + * return snapshot.data().value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = db.doc('values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await documentRef.set(42); + * const snapshot1 = await documentRef.get(); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await documentRef.update({ value: 999 }); + * const snapshot2 = await documentRef.get(); + * assertEqual(snapshot2.data(), 999); + * } + * + * Advanced Example + * + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot): Post { + * const data = snapshot.data() as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = db.doc('posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `DocumentReference.set()` is type + * // checked by the TypeScript compiler to be compatible with `Post`. Since + * // the `data` argument is typed as `WithFieldValue` rather than just + * // `Post`, this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `FieldValue.arrayRemove()`, `FieldValue.delete()`, and + * // `FieldValue.serverTimestamp()`. + * await documentRef.set({ + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: FieldValue.serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument + * // to `DocumentReference.set()` is _not_ compatible with + * // `WithFieldValue`. This type checking prevents the caller from + * // specifying objects with incorrect properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await documentRef.set(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `DocumentReference.get()` the + * // `DocumentSnapshot` object's `data()` method returns a `Post`, rather + * // than a generic object, which would have been returned if the + * // `DocumentReference` did _not_ have a `FirestoreDataConverter` + * // attached to it. + * const snapshot1: DocumentSnapshot = await documentRef.get(); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `DocumentReference.update()` is type + * // checked by the TypeScript compiler to be compatible with + * // `PostDbModel`. Note that unlike `DocumentReference.set()`, whose + * // `data` argument must be compatible with `Post`, the `data` argument + * // to `update()` must be compatible with `PostDbModel`. Similar to + * // `set()`, since the `data` argument is typed as + * // `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `FieldValue.arrayRemove()`, + * // `FieldValue.delete()`, and `FieldValue.serverTimestamp()`. + * await documentRef.update({ + * 'aut.firstName': 'NewFirstName', + * lut: FieldValue.serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument + * // to `DocumentReference.update()` is _not_ compatible with + * // `WithFieldValue`. This type checking prevents the caller + * // from specifying objects with incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not + * // assignable to parameter of type WithFieldValue" + * await documentRef.update({ title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await documentRef.get(); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + */ + export interface FirestoreDataConverter< + AppModelType, + DbModelType extends DocumentData = DocumentData, + > { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain Javascript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. + * + * To use set() with `merge` and `mergeFields`, + * toFirestore() must be defined with `Partial`. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such + * as `FieldValue.delete()` to be used as property values. + */ + toFirestore( + modelObject: WithFieldValue, + ): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain Javascript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. + * + * To use set() with `merge` and `mergeFields`, + * toFirestore() must be defined with `Partial`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as `FieldValue.delete()` to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore( + modelObject: PartialWithFieldValue, + options: SetOptions, + ): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data()`. + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use + * a type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + */ + fromFirestore(snapshot: QueryDocumentSnapshot): AppModelType; + } + /** + * Settings used to directly configure a `Firestore` instance. + */ + export interface Settings { + /** + * The project ID from the Google Developer's Console, e.g. + * 'grape-spaceship-123'. We will also check the environment variable + * GCLOUD_PROJECT for your project ID. Can be omitted in environments that + * support {@link https://cloud.google.com/docs/authentication Application + * Default Credentials} + */ + projectId?: string; + /** + * The database name. If omitted, the default database will be used. + */ + databaseId?: string; + /** The hostname to connect to. */ + host?: string; + /** The port to connect to. */ + port?: number; + /** + * Local file containing the Service Account credentials as downloaded from + * the Google Developers Console. Can be omitted in environments that + * support {@link https://cloud.google.com/docs/authentication Application + * Default Credentials}. To configure Firestore with custom credentials, use + * the `credentials` property to provide the `client_email` and + * `private_key` of your service account. + */ + keyFilename?: string; + /** + * The 'client_email' and 'private_key' properties of the service account + * to use with your Firestore project. Can be omitted in environments that + * support {@link https://cloud.google.com/docs/authentication Application + * Default Credentials}. If your credentials are stored in a JSON file, you + * can specify a `keyFilename` instead. + */ + credentials?: { + client_email?: string; + private_key?: string; + }; + /** Whether to use SSL when connecting. */ + ssl?: boolean; + /** + * The maximum number of idle GRPC channels to keep. A smaller number of idle + * channels reduces memory usage but increases request latency for clients + * with fluctuating request rates. If set to 0, shuts down all GRPC channels + * when the client becomes idle. Defaults to 1. + */ + maxIdleChannels?: number; + /** + * Whether to use `BigInt` for integer types when deserializing Firestore + * Documents. Regardless of magnitude, all integer values are returned as + * `BigInt` to match the precision of the Firestore backend. Floating point + * numbers continue to use JavaScript's `number` type. + */ + useBigInt?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set `false` or omitted, the SDK throws + * an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; + /** + * Whether to force the use of HTTP/1.1 REST transport until a method that requires gRPC + * is called. When a method requires gRPC, this Firestore client will load dependent gRPC + * libraries and then use gRPC transport for communication from that point forward. + * Currently the only operation that requires gRPC is creating a snapshot listener with + * the method `DocumentReference.onSnapshot()`, `CollectionReference.onSnapshot()`, + * or `Query.onSnapshot()`. + */ + preferRest?: boolean; + /** + * Settings related to telemetry collection by this client. + * @beta + */ + openTelemetry?: FirestoreOpenTelemetryOptions; + [key: string]: any; // Accept other properties, such as GRPC settings. + } + /** + * Options to configure telemetry collection. + * This is a 'beta' interface and may change in backwards incompatible ways. + * @beta + */ + export interface FirestoreOpenTelemetryOptions { + /** + * The OpenTelemetry TracerProvider instance that the SDK should use to + * create trace spans. If not provided, the SDK will use the Global TracerProvider. + * + * Even if a Global TracerProvider has been registered, users can still + * disable this client's span creation by passing in a "no-op" tracer provider + * here, or by setting the `FIRESTORE_ENABLE_TRACING` environment variable to `OFF` or `FALSE`. + */ + tracerProvider?: any; + } + /** Options to configure a read-only transaction. */ + export interface ReadOnlyTransactionOptions { + /** Set to true to indicate a read-only transaction. */ + readOnly: true; + /** + * If specified, documents are read at the given time. This may not be more + * than 60 seconds in the past from when the request is processed by the + * server. + */ + readTime?: Timestamp; + } + /** Options to configure a read-write transaction. */ + export interface ReadWriteTransactionOptions { + /** Set to false or omit to indicate a read-write transaction. */ + readOnly?: false; + /** + * The maximum number of attempts for this transaction. Defaults to 5. + */ + maxAttempts?: number; + } + /** + * `Firestore` represents a Firestore Database and is the entry point for all + * Firestore operations. + */ + export class Firestore { + /** + * @param settings Configuration object. See [Firestore Documentation] + * {@link https://firebase.google.com/docs/firestore/} + */ + public constructor(settings?: Settings); + /** + * Specifies custom settings to be used to configure the `Firestore` + * instance. Can only be invoked once and before any other Firestore + * method. + * + * If settings are provided via both `settings()` and the `Firestore` + * constructor, both settings objects are merged and any settings provided + * via `settings()` take precedence. + * + * @param {object} settings The settings to use for all Firestore + * operations. + */ + settings(settings: Settings): void; + /** + * Returns the Database ID for this Firestore instance. + */ + get databaseId(): string; + /** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified path. + * + * @param collectionPath A slash-separated path to a collection. + * @returns The `CollectionReference` instance. + */ + collection(collectionPath: string): CollectionReference; + /** + * Gets a `DocumentReference` instance that refers to the document at the + * specified path. + * + * @param documentPath A slash-separated path to a document. + * @returns The `DocumentReference` instance. + */ + doc(documentPath: string): DocumentReference; + /** + * Creates and returns a new Query that includes all documents in the + * database that are contained in a collection or subcollection with the + * given collectionId. + * + * @param collectionId Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `CollectionGroup`. + */ + collectionGroup(collectionId: string): CollectionGroup; + /** + * Retrieves multiple documents from Firestore. + * + * The first argument is required and must be of type `DocumentReference` + * followed by any additional `DocumentReference` documents. If used, the + * optional `ReadOptions` must be the last argument. + * + * @param {Array.} documentRefsOrReadOptions + * The `DocumentReferences` to receive, followed by an optional field + * mask. + * @returns A Promise that resolves with an array of resulting document + * snapshots. + */ + getAll( + ...documentRefsOrReadOptions: Array + ): Promise>; + /** + * Recursively deletes all documents and subcollections at and under the + * specified level. + * + * If any delete fails, the promise is rejected with an error message + * containing the number of failed deletes and the stack trace of the last + * failed delete. The provided reference is deleted regardless of whether + * all deletes succeeded. + * + * `recursiveDelete()` uses a BulkWriter instance with default settings to + * perform the deletes. To customize throttling rates or add success/error + * callbacks, pass in a custom BulkWriter instance. + * + * @param ref The reference of a document or collection to delete. + * @param bulkWriter A custom BulkWriter instance used to perform the + * deletes. + * @returns A promise that resolves when all deletes have been performed. + * The promise is rejected if any of the deletes fail. + * + * @example + * // Recursively delete a reference and log the references of failures. + * const bulkWriter = firestore.bulkWriter(); + * bulkWriter + * .onWriteError((error) => { + * if ( + * error.failedAttempts < MAX_RETRY_ATTEMPTS + * ) { + * return true; + * } else { + * console.log('Failed write at document: ', error.documentRef.path); + * return false; + * } + * }); + * await firestore.recursiveDelete(docRef, bulkWriter); + */ + recursiveDelete( + ref: CollectionReference | DocumentReference, + bulkWriter?: BulkWriter, + ): Promise; + /** + * Terminates the Firestore client and closes all open streams. + * + * @returns A Promise that resolves when the client is terminated. + */ + terminate(): Promise; + /** + * Fetches the root collections that are associated with this Firestore + * database. + * + * @returns A Promise that resolves with an array of CollectionReferences. + */ + listCollections(): Promise>; + /** + * Executes the given updateFunction and commits the changes applied within + * the transaction. + * + * You can use the transaction object passed to 'updateFunction' to read and + * modify Firestore documents under lock. You have to perform all reads + * before you perform any write. + * + * Transactions can be performed as read-only or read-write transactions. By + * default, transactions are executed in read-write mode. + * + * A read-write transaction obtains a pessimistic lock on all documents that + * are read during the transaction. These locks block other transactions, + * batched writes, and other non-transactional writes from changing that + * document. Any writes in a read-write transactions are committed once + * 'updateFunction' resolves, which also releases all locks. + * + * If a read-write transaction fails with contention, the transaction is + * retried up to five times. The `updateFunction` is invoked once for each + * attempt. + * + * Read-only transactions do not lock documents. They can be used to read + * documents at a consistent snapshot in time, which may be up to 60 seconds + * in the past. Read-only transactions are not retried. + * + * Transactions time out after 60 seconds if no documents are read. + * Transactions that are not committed within than 270 seconds are also + * aborted. Any remaining locks are released when a transaction times out. + * + * @param updateFunction The function to execute within the transaction + * context. + * @param transactionOptions Transaction options. + * @returns If the transaction completed successfully or was explicitly + * aborted (by the updateFunction returning a failed Promise), the Promise + * returned by the updateFunction will be returned here. Else if the + * transaction failed, a rejected Promise with the corresponding failure + * error will be returned. + */ + runTransaction( + updateFunction: (transaction: Transaction) => Promise, + transactionOptions?: + | ReadWriteTransactionOptions + | ReadOnlyTransactionOptions, + ): Promise; + /** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. + */ + batch(): WriteBatch; + /** + * Creates a [BulkWriter]{@link BulkWriter}, used for performing + * multiple writes in parallel. Gradually ramps up writes as specified + * by the 500/50/5 rule. + * + * @see https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic + * + * @param options An options object used to configure the throttling + * behavior for the underlying BulkWriter. + */ + bulkWriter(options?: BulkWriterOptions): BulkWriter; + /** + * Creates a new `BundleBuilder` instance to package selected Firestore data into + * a bundle. + * + * @param bundleId The ID of the bundle. When loaded on clients, client SDKs use this ID + * and the timestamp associated with the bundle to tell if it has been loaded already. + * If not specified, a random identifier will be used. + * + * + * @example + * const bundle = firestore.bundle('data-bundle'); + * const docSnapshot = await firestore.doc('abc/123').get(); + * const querySnapshot = await firestore.collection('coll').get(); + * + * const bundleBuffer = bundle.add(docSnapshot); // Add a document + * .add('coll-query', querySnapshot) // Add a named query. + * .build() + * // Save `bundleBuffer` to CDN or stream it to clients. + */ + bundle(bundleId?: string): BundleBuilder; + /** + * Define a pipeline query. Every pipeline is defined as a series of stages + * starting with a source stage. + * + * @example + * ``` + * let goodBooksPipeline: Pipeline = + * myFirestore.pipeline() + * .collection('books') + * .where(field('rating').greaterThan(4)); + * ``` + */ + pipeline(): Pipelines.PipelineSource; + } + /** + * An immutable object representing a geo point in Firestore. The geo point + * is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ + export class GeoPoint { + /** + * Creates a new immutable GeoPoint object with the provided latitude and + * longitude values. + * @param latitude The latitude as number between -90 and 90. + * @param longitude The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + readonly latitude: number; + readonly longitude: number; + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + } + /** + * A reference to a transaction. + * The `Transaction` object passed to a transaction's updateFunction provides + * the methods to read and write data within the transaction context. See + * `Firestore.runTransaction()`. + */ + export class Transaction { + private constructor(); + /** + * Retrieves a query result. Holds a pessimistic lock on all returned + * documents. + * + * @param query A query to execute. + * @returns A QuerySnapshot for the retrieved data. + */ + get( + query: Query, + ): Promise>; + /** + * Reads the document referenced by the provided `DocumentReference.` + * Holds a pessimistic lock on the returned document. + * + * @param documentRef A reference to the document to be read. + * @returns A DocumentSnapshot for the read data. + */ + get( + documentRef: DocumentReference, + ): Promise>; + /** + * Retrieves an aggregate query result. Holds a pessimistic lock on all + * documents that were matched by the underlying query. + * + * @param aggregateQuery An aggregate query to execute. + * @returns An AggregateQuerySnapshot for the retrieved data. + */ + get< + AppModelType, + DbModelType extends DocumentData, + AggregateSpecType extends AggregateSpec, + >( + aggregateQuery: AggregateQuery< + AggregateSpecType, + AppModelType, + DbModelType + >, + ): Promise< + AggregateQuerySnapshot + >; + /** + * Retrieves multiple documents from Firestore. Holds a pessimistic lock on + * all returned documents. + * + * The first argument is required and must be of type `DocumentReference` + * followed by any additional `DocumentReference` documents. If used, the + * optional `ReadOptions` must be the last argument. + * + * @param {Array.} documentRefsOrReadOptions + * The `DocumentReferences` to receive, followed by an optional field + * mask. + * @returns A Promise that resolves with an array of resulting document + * snapshots. + */ + getAll( + ...documentRefsOrReadOptions: Array< + DocumentReference | ReadOptions + > + ): Promise>>; + /** + * Create the document referred to by the provided `DocumentReference`. + * The operation will fail the transaction if a document exists at the + * specified location. + * + * @param documentRef A reference to the document to be create. + * @param data The object data to serialize as the document. + * @throws Error If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + create( + documentRef: DocumentReference, + data: WithFieldValue, + ): Transaction; + /** + * Writes to the document referred to by the provided `DocumentReference`. + * If the document does not exist yet, it will be created. If you pass + * `SetOptions`, the provided data can be merged into the existing document. + * + * @param documentRef A reference to the document to be set. + * @param data An object of the fields and values for the document. + * @param options An object to configure the set behavior. + * @param options.merge - If true, set() merges the values specified in its + * data argument. Fields omitted from this set() call remain untouched. If + * your input sets any field to an empty map, all nested fields are + * overwritten. + * @param options.mergeFields - If provided, set() only replaces the + * specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @throws Error If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set( + documentRef: DocumentReference, + data: PartialWithFieldValue, + options: SetOptions, + ): Transaction; + set( + documentRef: DocumentReference, + data: WithFieldValue, + ): Transaction; + /** + * Updates fields in the document referred to by the provided + * `DocumentReference`. The update will fail if applied to a document that + * does not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings. + * + * @param documentRef A reference to the document to be updated. + * @param data An object containing the fields and values with which to + * update the document. + * @param precondition A Precondition to enforce on this update. + * @throws Error If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + data: UpdateData, + precondition?: Precondition, + ): Transaction; + /** + * Updates fields in the document referred to by the provided + * `DocumentReference`. The update will fail if applied to a document that + * does not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing FieldPath objects. + * + * A `Precondition` restricting this update can be specified as the last + * argument. + * + * @param documentRef A reference to the document to be updated. + * @param field The first field to update. + * @param value The first value + * @param fieldsOrPrecondition An alternating list of field paths and values + * to update, optionally followed by a `Precondition` to enforce on this + * update. + * @throws Error If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + field: string | FieldPath, + value: any, + ...fieldsOrPrecondition: any[] + ): Transaction; + /** + * Deletes the document referred to by the provided `DocumentReference`. + * + * @param documentRef A reference to the document to be deleted. + * @param precondition A Precondition to enforce for this delete. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete( + documentRef: DocumentReference, + precondition?: Precondition, + ): Transaction; + /** + * Executes this pipeline and returns a Promise to represent the asynchronous operation. + * + * The returned Promise can be used to track the progress of the pipeline execution + * and retrieve the results (or handle any errors) asynchronously. + * + *

The pipeline results are returned in a `PipelineSnapshot` object, which contains a list of + * `PipelineResult` objects. Each `PipelineResult` typically represents a single key/value map that + * has passed through all the stages of the pipeline, however this might differ depending on the stages involved + * in the pipeline. For example: + * + *

    + *
  • If there are no stages or only transformation stages, each `PipelineResult` + * represents a single document.
  • + *
  • If there is an aggregation, only a single `PipelineResult` is returned, + * representing the aggregated results over the entire dataset .
  • + *
  • If there is an aggregation stage with grouping, each `PipelineResult` represents a + * distinct group and its associated aggregated values.
  • + *
+ * + * + * @example + * ```typescript + * const futureResults = await transaction + * .execute( + * firestore.pipeline().collection("books") + * .where(greaterThan(Field.of("rating"), 4.5)) + * .select("title", "author", "rating")); + * ``` + * + * @returns A Promise representing the asynchronous pipeline execution. + */ + execute(pipeline: Pipelines.Pipeline): Promise; + } + /** + * A Firestore BulkWriter than can be used to perform a large number of writes + * in parallel. Writes to the same document will be executed sequentially. + * + * @class + */ + export class BulkWriter { + private constructor(); + /** + * Create a document with the provided data. This single operation will fail + * if a document exists at its location. + * + * @param documentRef A reference to the document to be + * created. + * @param data The object to serialize as the document. + * @throws Error If the provided input is not a valid Firestore document. + * @returns A promise that resolves with the result of the write. If the + * write fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + */ + create( + documentRef: DocumentReference, + data: WithFieldValue, + ): Promise; + /** + * Delete a document from the database. + * + * @param documentRef A reference to the document to be + * deleted. + * @param precondition A precondition to enforce for this + * delete. + * @param precondition.lastUpdateTime If set, enforces that the + * document was last updated at lastUpdateTime. Fails the batch if the + * document doesn't exist or was last updated at a different time. + * @param precondition.exists If set, enforces that the target document + * must or must not exist. + * @returns A promise that resolves with the result of the delete. If the + * delete fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + */ + delete( + documentRef: DocumentReference, + precondition?: Precondition, + ): Promise; + /** + * Write to the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document does not + * exist yet, it will be created. If you pass + * [SetOptions]{@link SetOptions}., the provided data can be merged into the + * existing document. + * + * @param documentRef A reference to the document to be + * set. + * @param data The object to serialize as the document. + * @param options An object to configure the set behavior. + * @param options.merge - If true, set() merges the values specified in its + * data argument. Fields omitted from this set() call remain untouched. If + * your input sets any field to an empty map, all nested fields are + * overwritten. + * @param options.mergeFields - If provided, set() only replaces the + * specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @throws Error If the provided input is not a valid Firestore document. + * @returns A promise that resolves with the result of the write. If the + * write fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + */ + set( + documentRef: DocumentReference, + data: PartialWithFieldValue, + options: SetOptions, + ): Promise; + set( + documentRef: DocumentReference, + data: WithFieldValue, + ): Promise; + /** + * Update fields of the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document doesn't yet + * exist, the update fails and the entire batch will be rejected. + * + * The update() method accepts either an object with field paths encoded as + * keys and field values encoded as values, or a variable number of + * arguments that alternate between field paths and field values. Nested + * fields can be updated by providing dot-separated field path strings or by + * providing FieldPath objects. + * + * + * A Precondition restricting this update can be specified as the last + * argument. + * + * @param documentRef A reference to the document to be updated. + * @param data An object containing the fields and values with which to + * update the document. + * @param precondition A Precondition to enforce on this update. + * @throws Error If the provided input is not valid Firestore data. + * @returns A promise that resolves with the result of the write. If the + * write fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + */ + update( + documentRef: DocumentReference, + data: UpdateData, + precondition?: Precondition, + ): Promise; + /** + * Update fields of the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document doesn't yet + * exist, the update fails and the entire batch will be rejected. + * + * The update() method accepts either an object with field paths encoded as + * keys and field values encoded as values, or a variable number of + * arguments that alternate between field paths and field values. Nested + * fields can be updated by providing dot-separated field path strings or by + * providing FieldPath objects. + * + * + * A Precondition restricting this update can be specified as the last + * argument. + * + * @param documentRef A reference to the document to be updated. + * @param field The first field to update. + * @param value The first value + * @param fieldsOrPrecondition An alternating list of field paths and values + * to update, optionally followed a `Precondition` to enforce on this + * update. + * @throws Error If the provided input is not valid Firestore data; + * @returns A promise that resolves with the result of the write. If the + * write fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + */ + update( + documentRef: DocumentReference, + field: string | FieldPath, + value: any, + ...fieldsOrPrecondition: any[] + ): Promise; + /** + * Attaches a listener that is run every time a BulkWriter operation + * successfully completes. + * + * @param callback A callback to be called every time a BulkWriter operation + * successfully completes. + */ + onWriteResult( + callback: ( + documentRef: DocumentReference, + result: WriteResult, + ) => void, + ): void; + /** + * Attaches an error handler listener that is run every time a BulkWriter + * operation fails. + * + * BulkWriter has a default error handler that retries UNAVAILABLE and + * ABORTED errors up to a maximum of 10 failed attempts. When an error + * handler is specified, the default error handler will be overwritten. + * + * @param shouldRetryCallback A callback to be called every time a BulkWriter + * operation fails. Returning `true` will retry the operation. Returning + * `false` will stop the retry loop. + */ + onWriteError( + shouldRetryCallback: (error: BulkWriterError) => boolean, + ): void; + /** + * Commits all writes that have been enqueued up to this point in parallel. + * + * Returns a Promise that resolves when all currently queued operations have + * been committed. The Promise will never be rejected since the results for + * each individual operation are conveyed via their individual Promises. + * + * The Promise resolves immediately if there are no pending writes. + * Otherwise, the Promise waits for all previously issued writes, but it + * does not wait for writes that were added after the method is called. If + * you want to wait for additional writes, call `flush()` again. + * + * @returns A promise that resolves when all enqueued writes + * up to this point have been committed. + */ + flush(): Promise; + /** + * Commits all enqueued writes and marks the BulkWriter instance as closed. + * + * After calling `close()`, calling any method will throw an error. Any + * retries scheduled as part of an `onWriteError()` handler will be run + * before the `close()` promise resolves. + * + * Returns a Promise that resolves when all writes have been committed. The + * Promise will never be rejected. Calling this method will send all + * requests. The promise resolves immediately if there are no pending + * writes. + * + * @returns A promise that resolves when all enqueued writes + * up to this point have been committed. + */ + close(): Promise; + } + /** + * An options object to configure throttling on BulkWriter. + */ + export interface BulkWriterOptions { + /** + * Whether to disable or configure throttling. By default, throttling is + * enabled. This field can be set to either a boolean or a config + * object. Setting it to `true` will use default values. You can override + * the defaults by setting it to `false` to disable throttling, or by + * setting the config values to enable throttling with the provided values. + * + * @see https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic + * + * @param initialOpsPerSecond The initial maximum number of operations per + * second allowed by the throttler. If this field is not set, the default + * is 500 operations per second. + * @param maxOpsPerSecond The maximum number of operations per second + * allowed by the throttler. If this field is set, the throttler's allowed + * operations per second does not ramp up past the specified operations per + * second. + */ + readonly throttling?: + | boolean + | { + initialOpsPerSecond?: number; + maxOpsPerSecond?: number; + }; + } + /** + * The error thrown when a BulkWriter operation fails. + */ + export class BulkWriterError extends Error { + /** The status code of the error. */ + readonly code: GrpcStatus; + /** The error message of the error. */ + readonly message: string; + /** The document reference the operation was performed on. */ + readonly documentRef: DocumentReference; + /** The type of operation performed. */ + readonly operationType: 'create' | 'set' | 'update' | 'delete'; + /** How many times this operation has been attempted unsuccessfully. */ + readonly failedAttempts: number; + } + /** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling `Firestore.batch()`. It + * provides methods for adding writes to the write batch. None of the + * writes will be committed (or visible locally) until `WriteBatch.commit()` + * is called. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + */ + export class WriteBatch { + private constructor(); + /** + * Create the document referred to by the provided `DocumentReference`. The + * operation will fail the batch if a document exists at the specified + * location. + * + * @param documentRef A reference to the document to be created. + * @param data The object data to serialize as the document. + * @throws Error If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + create( + documentRef: DocumentReference, + data: WithFieldValue, + ): WriteBatch; + /** + * Write to the document referred to by the provided `DocumentReference`. + * If the document does not exist yet, it will be created. If you pass + * `SetOptions`, the provided data can be merged into the existing document. + * + * @param documentRef A reference to the document to be set. + * @param data An object of the fields and values for the document. + * @param options An object to configure the set behavior. + * @param options.merge - If true, set() merges the values specified in its + * data argument. Fields omitted from this set() call remain untouched. If + * your input sets any field to an empty map, all nested fields are + * overwritten. + * @param options.mergeFields - If provided, set() only replaces the + * specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @throws Error If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set( + documentRef: DocumentReference, + data: PartialWithFieldValue, + options: SetOptions, + ): WriteBatch; + set( + documentRef: DocumentReference, + data: WithFieldValue, + ): WriteBatch; + /** + * Update fields of the document referred to by the provided + * `DocumentReference`. If the document doesn't yet exist, the update fails + * and the entire batch will be rejected. + * + * Nested fields can be updated by providing dot-separated field path + * strings. + * + * @param documentRef A reference to the document to be updated. + * @param data An object containing the fields and values with which to + * update the document. + * @param precondition A Precondition to enforce on this update. + * @throws Error If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + data: UpdateData, + precondition?: Precondition, + ): WriteBatch; + /** + * Updates fields in the document referred to by the provided + * `DocumentReference`. The update will fail if applied to a document that + * does not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing FieldPath objects. + * + * A `Precondition` restricting this update can be specified as the last + * argument. + * + * @param documentRef A reference to the document to be updated. + * @param field The first field to update. + * @param value The first value + * @param fieldsOrPrecondition An alternating list of field paths and values + * to update, optionally followed a `Precondition` to enforce on this + * update. + * @throws Error If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + field: string | FieldPath, + value: any, + ...fieldsOrPrecondition: any[] + ): WriteBatch; + /** + * Deletes the document referred to by the provided `DocumentReference`. + * + * @param documentRef A reference to the document to be deleted. + * @param precondition A Precondition to enforce for this delete. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete( + documentRef: DocumentReference, + precondition?: Precondition, + ): WriteBatch; + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * @returns A Promise resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit. + */ + commit(): Promise; + } + /** + * An options object that configures conditional behavior of `update()` and + * `delete()` calls in `DocumentReference`, `WriteBatch`, and `Transaction`. + * Using Preconditions, these calls can be restricted to only apply to + * documents that match the specified restrictions. + */ + export interface Precondition { + /** + * If set, the last update time to enforce. + */ + readonly lastUpdateTime?: Timestamp; + /** + * If set, enforces that the target document must or must not exist. + */ + readonly exists?: boolean; + } + /** + * An options object that configures the behavior of `set()` calls in + * `DocumentReference`, `WriteBatch` and `Transaction`. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety. + * + * @param merge Changes the behavior of a set() call to only replace the + * values specified in its data argument. Fields omitted from the set() call + * remain untouched. If your input sets any field to an empty map, all nested + * fields are overwritten. + * + * @param mergeFields Changes the behavior of set() calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ + export type SetOptions = + | { + readonly merge?: boolean; + } + | { + readonly mergeFields?: Array; + }; + /** + * An options object that can be used to configure the behavior of `getAll()` + * calls. By providing a `fieldMask`, these calls can be configured to only + * return a subset of fields. + */ + export interface ReadOptions { + /** + * Specifies the set of fields to return and reduces the amount of data + * transmitted by the backend. + * + * Adding a field mask does not filter results. Documents do not need to + * contain values for all the fields in the mask to be part of the result + * set. + */ + readonly fieldMask?: (string | FieldPath)[]; + } + /** + * A WriteResult wraps the write time set by the Firestore servers on `sets()`, + * `updates()`, and `creates()`. + */ + export class WriteResult { + private constructor(); + /** + * The write time as set by the Firestore servers. + */ + readonly writeTime: Timestamp; + /** + * Returns true if this `WriteResult` is equal to the provided one. + * + * @param other The `WriteResult` to compare against. + * @returns true if this `WriteResult` is equal to the provided one. + */ + isEqual(other: WriteResult): boolean; + } + /** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. A `DocumentReference` can + * also be used to create a `CollectionReference` to a subcollection. + */ + export class DocumentReference< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + private constructor(); + /** The identifier of the document within its collection. */ + readonly id: string; + /** + * The `Firestore` for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore; + /** + * A reference to the Collection to which this DocumentReference belongs. + */ + readonly parent: CollectionReference; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + readonly path: string; + /** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified path. + * + * @param collectionPath A slash-separated path to a collection. + * @returns The `CollectionReference` instance. + */ + collection(collectionPath: string): CollectionReference; + /** + * Fetches the subcollections that are direct children of this document. + * + * @returns A Promise that resolves with an array of CollectionReferences. + */ + listCollections(): Promise>; + /** + * Creates a document referred to by this `DocumentReference` with the + * provided object values. The write fails if the document already exists + * + * @param data The object data to serialize as the document. + * @throws {Error} If the provided input is not a valid Firestore document or if the document already exists. + * @returns A Promise resolved with the write time of this create. + */ + create(data: WithFieldValue): Promise; + /** + * Writes to the document referred to by this `DocumentReference`. If the + * document does not yet exist, it will be created. If you pass + * `SetOptions`, the provided data can be merged into an existing document. + * + * @param data A map of the fields and values for the document. + * @param options An object to configure the set behavior. + * @param options.merge - If true, set() merges the values specified in its + * data argument. Fields omitted from this set() call remain untouched. If + * your input sets any field to an empty map, all nested fields are + * overwritten. + * @param options.mergeFields - If provided, set() only replaces the + * specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @throws Error If the provided input is not a valid Firestore document. + * @returns A Promise resolved with the write time of this set. + */ + set( + data: PartialWithFieldValue, + options: SetOptions, + ): Promise; + set(data: WithFieldValue): Promise; + /** + * Updates fields in the document referred to by this `DocumentReference`. + * The update will fail if applied to a document that does not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings. + * + * @param data An object containing the fields and values with which to + * update the document. + * @param precondition A Precondition to enforce on this update. + * @throws Error If the provided input is not valid Firestore data. + * @returns A Promise resolved with the write time of this update. + */ + update( + data: UpdateData, + precondition?: Precondition, + ): Promise; + /** + * Updates fields in the document referred to by this `DocumentReference`. + * The update will fail if applied to a document that does not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing FieldPath objects. + * + * A `Precondition` restricting this update can be specified as the last + * argument. + * + * @param field The first field to update. + * @param value The first value. + * @param moreFieldsOrPrecondition An alternating list of field paths and + * values to update, optionally followed by a `Precondition` to enforce on + * this update. + * @throws Error If the provided input is not valid Firestore data. + * @returns A Promise resolved with the write time of this update. + */ + update( + field: string | FieldPath, + value: any, + ...moreFieldsOrPrecondition: any[] + ): Promise; + /** + * Deletes the document referred to by this `DocumentReference`. + * + * @param precondition A Precondition to enforce for this delete. + * @returns A Promise resolved with the write time of this delete. + */ + delete(precondition?: Precondition): Promise; + /** + * Reads the document referred to by this `DocumentReference`. + * + * @returns A Promise resolved with a DocumentSnapshot containing the + * current document contents. + */ + get(): Promise>; + /** + * Attaches a listener for DocumentSnapshot events. + * + * @param onNext A callback to be called every time a new `DocumentSnapshot` + * is available. + * @param onError A callback to be called if the listen fails or is + * cancelled. No further callbacks will occur. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ + onSnapshot( + onNext: (snapshot: DocumentSnapshot) => void, + onError?: (error: Error) => void, + ): () => void; + /** + * Returns true if this `DocumentReference` is equal to the provided one. + * + * @param other The `DocumentReference` to compare against. + * @returns true if this `DocumentReference` is equal to the provided one. + */ + isEqual(other: DocumentReference): boolean; + /** + * Applies a custom data converter to this DocumentReference, allowing you + * to use your own custom model objects with Firestore. When you call + * set(), get(), etc. on the returned DocumentReference instance, the + * provided converter will convert between Firestore data of type + * `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter Converts objects to and from Firestore. Passing in + * `null` removes the current converter. + * @returns A DocumentReference that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData, + >( + converter: FirestoreDataConverter | null, + ): DocumentReference; + } + /** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists` property to + * explicitly verify a document's existence. + */ + export class DocumentSnapshot< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + protected constructor(); + /** True if the document exists. */ + readonly exists: boolean; + /** A `DocumentReference` to the document location. */ + readonly ref: DocumentReference; + /** + * The ID of the document for which this `DocumentSnapshot` contains data. + */ + readonly id: string; + /** + * The time the document was created. Not set for documents that don't + * exist. + */ + readonly createTime?: Timestamp; + /** + * The time the document was last updated (at the time the snapshot was + * generated). Not set for documents that don't exist. + */ + readonly updateTime?: Timestamp; + /** + * The time this snapshot was read. + */ + readonly readTime: Timestamp; + /** + * Retrieves all fields in the document as an Object. Returns 'undefined' if + * the document doesn't exist. + * + * @returns An Object containing all fields in the document. + */ + data(): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. + * + * @param fieldPath The path (e.g. 'foo' or 'foo.bar') to a specific field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath): any; + /** + * Returns true if the document's data and path in this `DocumentSnapshot` + * is equal to the provided one. + * + * @param other The `DocumentSnapshot` to compare against. + * @returns true if this `DocumentSnapshot` is equal to the provided one. + */ + isEqual(other: DocumentSnapshot): boolean; + } + /** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ + export class QueryDocumentSnapshot< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > extends DocumentSnapshot { + private constructor(); + /** + * The time the document was created. + */ + readonly createTime: Timestamp; + /** + * The time the document was last updated (at the time the snapshot was + * generated). + */ + readonly updateTime: Timestamp; + /** + * Retrieves all fields in the document as an Object. + * + * @override + * @returns An Object containing all fields in the document. + */ + data(): AppModelType; + } + /** + * The direction of a `Query.orderBy()` clause is specified as 'desc' or 'asc' + * (descending or ascending). + */ + export type OrderByDirection = 'desc' | 'asc'; + /** + * Filter conditions in a `Query.where()` clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', 'not-in', + * and 'array-contains-any'. + */ + export type WhereFilterOp = + | '<' + | '<=' + | '==' + | '!=' + | '>=' + | '>' + | 'array-contains' + | 'in' + | 'not-in' + | 'array-contains-any'; + /** + * A `Query` refers to a Query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ + export class Query< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + protected constructor(); + /** + * The `Firestore` for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore; + /** + * Creates and returns a new Query with the additional filter that documents + * must contain the specified field and that its value should satisfy the + * relation constraint provided. + * + * This function returns a new (immutable) instance of the Query (rather + * than modify the existing instance) to impose the filter. + * + * @param fieldPath The path to compare + * @param opStr The operation string (e.g "<", "<=", "==", ">", ">="). + * @param value The value for comparison + * @returns The created Query. + */ + where( + fieldPath: string | FieldPath, + opStr: WhereFilterOp, + value: any, + ): Query; + /** + * Creates and returns a new [Query]{@link Query} with the additional filter + * that documents should satisfy the relation constraint provided. Documents + * must contain the field specified in the filter. + * + * This function returns a new (immutable) instance of the Query (rather than + * modify the existing instance) to impose the filter. + * + * @param {Filter} filter A filter to apply to the Query. + * @returns {Query} The created Query. + */ + where(filter: Filter): Query; + /** + * Creates and returns a new Query that's additionally sorted by the + * specified field, optionally in descending order instead of ascending. + * + * This function returns a new (immutable) instance of the Query (rather + * than modify the existing instance) to impose the order. + * + * @param fieldPath The field to sort by. + * @param directionStr Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created Query. + */ + orderBy( + fieldPath: string | FieldPath, + directionStr?: OrderByDirection, + ): Query; + /** + * Creates and returns a new Query that only returns the first matching + * documents. + * + * This function returns a new (immutable) instance of the Query (rather + * than modify the existing instance) to impose the limit. + * + * @param limit The maximum number of items to return. + * @returns The created Query. + */ + limit(limit: number): Query; + /** + * Creates and returns a new Query that only returns the last matching + * documents. + * + * You must specify at least one orderBy clause for limitToLast queries, + * otherwise an exception will be thrown during execution. + * + * Results for limitToLast queries cannot be streamed via the `stream()` + * API. + * + * @param limit The maximum number of items to return. + * @returns The created Query. + */ + limitToLast(limit: number): Query; + /** + * Specifies the offset of the returned results. + * + * This function returns a new (immutable) instance of the Query (rather + * than modify the existing instance) to impose the offset. + * + * @param offset The offset to apply to the Query results. + * @returns The created Query. + */ + offset(offset: number): Query; + /** + * Creates and returns a new Query instance that applies a field mask to + * the result and returns only the specified subset of fields. You can + * specify a list of field paths to return, or use an empty list to only + * return the references of matching documents. + * + * Queries that contain field masks cannot be listened to via `onSnapshot()` + * listeners. + * + * This function returns a new (immutable) instance of the Query (rather + * than modify the existing instance) to impose the field mask. + * + * @param field The field paths to return. + * @returns The created Query. + */ + select(...field: (string | FieldPath)[]): Query; + /** + * Creates and returns a new Query that starts at the provided document + * (inclusive). The starting position is relative to the order of the query. + * The document must contain all of the fields provided in the orderBy of + * this query. + * + * @param snapshot The snapshot of the document to start after. + * @returns The created Query. + */ + startAt( + snapshot: DocumentSnapshot, + ): Query; + /** + * Creates and returns a new Query that starts at the provided fields + * relative to the order of the query. The order of the field values + * must match the order of the order by clauses of the query. + * + * @param fieldValues The field values to start this query at, in order + * of the query's order by. + * @returns The created Query. + */ + startAt(...fieldValues: any[]): Query; + /** + * Creates and returns a new Query that starts after the provided document + * (exclusive). The starting position is relative to the order of the query. + * The document must contain all of the fields provided in the orderBy of + * this query. + * + * @param snapshot The snapshot of the document to start after. + * @returns The created Query. + */ + startAfter( + snapshot: DocumentSnapshot, + ): Query; + /** + * Creates and returns a new Query that starts after the provided fields + * relative to the order of the query. The order of the field values + * must match the order of the order by clauses of the query. + * + * @param fieldValues The field values to start this query after, in order + * of the query's order by. + * @returns The created Query. + */ + startAfter(...fieldValues: any[]): Query; + /** + * Creates and returns a new Query that ends before the provided document + * (exclusive). The end position is relative to the order of the query. The + * document must contain all of the fields provided in the orderBy of this + * query. + * + * @param snapshot The snapshot of the document to end before. + * @returns The created Query. + */ + endBefore( + snapshot: DocumentSnapshot, + ): Query; + /** + * Creates and returns a new Query that ends before the provided fields + * relative to the order of the query. The order of the field values + * must match the order of the order by clauses of the query. + * + * @param fieldValues The field values to end this query before, in order + * of the query's order by. + * @returns The created Query. + */ + endBefore(...fieldValues: any[]): Query; + /** + * Creates and returns a new Query that ends at the provided document + * (inclusive). The end position is relative to the order of the query. The + * document must contain all of the fields provided in the orderBy of this + * query. + * + * @param snapshot The snapshot of the document to end at. + * @returns The created Query. + */ + endAt( + snapshot: DocumentSnapshot, + ): Query; + /** + * Creates and returns a new Query that ends at the provided fields + * relative to the order of the query. The order of the field values + * must match the order of the order by clauses of the query. + * + * @param fieldValues The field values to end this query at, in order + * of the query's order by. + * @returns The created Query. + */ + endAt(...fieldValues: any[]): Query; + /** + * Executes the query and returns the results as a `QuerySnapshot`. + * + * @returns A Promise that will be resolved with the results of the Query. + */ + get(): Promise>; + /** + * Plans and optionally executes this query. Returns a Promise that will be + * resolved with the planner information, statistics from the query execution (if any), + * and the query results (if any). + * + * @returns A Promise that will be resolved with the planner information, statistics + * from the query execution (if any), and the query results (if any). + */ + explain( + options?: ExplainOptions, + ): Promise>>; + /** + * Executes the query and returns the results as Node Stream. + * + * @returns A stream of QueryDocumentSnapshot. + */ + stream(): NodeJS.ReadableStream; + /** + * Plans and optionally executes this query, and streams the results as Node Stream + * of `{document?: DocumentSnapshot, metrics?: ExplainMetrics}` objects. + * + * The stream surfaces documents one at a time as they are received from the + * server, and at the end, it will surface the metrics associated with + * executing the query (if any). + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * let count = 0; + * + * query.explainStream({analyze: true}).on('data', (data) => { + * if (data.document) { + * // Use data.document which is a DocumentSnapshot instance. + * console.log(`Found document with name '${data.document.id}'`); + * ++count; + * } + * if (data.metrics) { + * // Use data.metrics which is an ExplainMetrics instance. + * } + * }).on('end', () => { + * console.log(`Received ${count} documents.`); + * }); + * ``` + * + * @returns A stream of `{document?: DocumentSnapshot, metrics?: ExplainMetrics}` + * objects. + */ + explainStream(options?: ExplainOptions): NodeJS.ReadableStream; + /** + * Attaches a listener for `QuerySnapshot `events. + * + * @param onNext A callback to be called every time a new `QuerySnapshot` + * is available. + * @param onError A callback to be called if the listen fails or is + * cancelled. No further callbacks will occur. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ + onSnapshot( + onNext: (snapshot: QuerySnapshot) => void, + onError?: (error: Error) => void, + ): () => void; + /** + * Returns a query that counts the documents in the result set of this + * query. + * + * The returned query, when executed, counts the documents in the result set + * of this query without actually downloading the documents. + * + * Using the returned query to count the documents is efficient because only + * the final count, not the documents' data, is downloaded. The returned + * query can count the documents in cases where the result set is + * prohibitively large to download entirely (thousands of documents). + * + * @returns a query that counts the documents in the result set of this + * query. The count can be retrieved from `snapshot.data().count`, where + * `snapshot` is the `AggregateQuerySnapshot` resulting from running the + * returned query. + */ + count(): AggregateQuery< + { + count: AggregateField; + }, + AppModelType, + DbModelType + >; + /** + * Returns a query that can perform the given aggregations. + * + * The returned query, when executed, calculates the specified aggregations + * over the documents in the result set of this query without actually + * downloading the documents. + * + * Using the returned query to perform aggregations is efficient because only + * the final aggregation values, not the documents' data, is downloaded. The + * returned query can perform aggregations of the documents in cases where + * the result set is prohibitively large to download entirely (thousands of + * documents). + * + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateQuery = col.aggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const aggregateSnapshot = await aggregateQuery.get(); + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ + aggregate( + aggregateSpec: T, + ): AggregateQuery; + /** + * Returns a query that can perform vector distance (similarity) search with given parameters. + * + * The returned query, when executed, performs a distance (similarity) search on the specified + * `vectorField` against the given `queryVector` and returns the top documents that are closest + * to the `queryVector`. + * + * Only documents whose `vectorField` field is a {@link VectorValue} of the same dimension as `queryVector` + * participate in the query, all other documents are ignored. + * + * @example + * ``` + * // Returns the closest 10 documents whose Euclidean distance from their 'embedding' fields are closed to [41, 42]. + * const vectorQuery = col.findNearest('embedding', [41, 42], {limit: 10, distanceMeasure: 'EUCLIDEAN'}); + * + * const querySnapshot = await aggregateQuery.get(); + * querySnapshot.forEach(...); + * ``` + * + * @param vectorField - A string or {@link FieldPath} specifying the vector field to search on. + * @param queryVector - The {@link VectorValue} used to measure the distance from `vectorField` values in the documents. + * @param options - Options control the vector query. `limit` specifies the upper bound of documents to return, must + * be a positive integer with a maximum value of 1000. `distanceMeasure` specifies what type of distance is calculated + * when performing the query. + * + * @deprecated Use the new {@link Query.findNearest:VectorQueryOptions} implementation + * accepting a single `options` param. + */ + findNearest( + vectorField: string | FieldPath, + queryVector: VectorValue | Array, + options: { + limit: number; + distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; + }, + ): VectorQuery; + /** + * Returns a query that can perform vector distance (similarity) search with given parameters. + * + * The returned query, when executed, performs a distance (similarity) search on the specified + * `vectorField` against the given `queryVector` and returns the top documents that are closest + * to the `queryVector`. + * + * Only documents whose `vectorField` field is a {@link VectorValue} of the same dimension as `queryVector` + * participate in the query, all other documents are ignored. + * + * @example + * ``` + * // Returns the closest 10 documents whose Euclidean distance from their 'embedding' fields are closed to [41, 42]. + * const vectorQuery = col.findNearest({ + * vectorField: 'embedding', + * queryVector: [41, 42], + * limit: 10, + * distanceMeasure: 'EUCLIDEAN', + * distanceResultField: 'distance', + * distanceThreshold: 0.125 + * }); + * + * const querySnapshot = await aggregateQuery.get(); + * querySnapshot.forEach(...); + * ``` + * @param options - An argument specifying the behavior of the {@link VectorQuery} returned by this function. + * See {@link VectorQueryOptions}. + */ + findNearest( + options: VectorQueryOptions, + ): VectorQuery; + /** + * Returns a query that can perform vector distance (similarity) search with given parameters. + * + * The returned query, when executed, performs a distance (similarity) search on the specified + * `vectorField` against the given `queryVector` and returns the top documents that are closest + * to the `queryVector`. + * + * Only documents whose `vectorField` field is a {@link VectorValue} of the same dimension as `queryVector` + * participate in the query, all other documents are ignored. + * + * @example + * ``` + * // Returns the closest 10 documents whose Euclidean distance from their 'embedding' fields are closed to [41, 42]. + * const vectorQuery = col.findNearest({ + * vectorField: 'embedding', + * queryVector: [41, 42], + * limit: 10, + * distanceMeasure: 'EUCLIDEAN', + * distanceResultField: 'distance', + * distanceThreshold: 0.125 + * }); + * + * const querySnapshot = await aggregateQuery.get(); + * querySnapshot.forEach(...); + * ``` + * @param options - An argument specifying the behavior of the {@link VectorQuery} returned by this function. + * See {@link VectorQueryOptions}. + */ + findNearest( + options: VectorQueryOptions, + ): VectorQuery; + /** + * Returns true if this `Query` is equal to the provided one. + * + * @param other The `Query` to compare against. + * @returns true if this `Query` is equal to the provided one. + */ + isEqual(other: Query): boolean; + /** + * Applies a custom data converter to this Query, allowing you to use your + * own custom model objects with Firestore. When you call get() on the + * returned Query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter Converts objects to and from Firestore. Passing in + * `null` removes the current converter. + * @returns A Query that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData, + >( + converter: FirestoreDataConverter | null, + ): Query; + } + /** + * A `QuerySnapshot` contains zero or more `QueryDocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ + export class QuerySnapshot< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + private constructor(); + /** + * The query on which you called `get` or `onSnapshot` in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + /** An array of all the documents in the QuerySnapshot. */ + readonly docs: Array>; + /** The number of documents in the QuerySnapshot. */ + readonly size: number; + /** True if there are no documents in the QuerySnapshot. */ + readonly empty: boolean; + /** The time this query snapshot was obtained. */ + readonly readTime: Timestamp; + /** + * Returns an array of the documents changes since the last snapshot. If + * this is the first snapshot, all documents will be in the list as added + * changes. + */ + docChanges(): DocumentChange[]; + /** + * Enumerates all of the documents in the QuerySnapshot. + * + * @param callback A callback to be called with a `DocumentSnapshot` for + * each document in the snapshot. + * @param thisArg The `this` binding for the callback. + */ + forEach( + callback: ( + result: QueryDocumentSnapshot, + ) => void, + thisArg?: any, + ): void; + /** + * Returns true if the document data in this `QuerySnapshot` is equal to the + * provided one. + * + * @param other The `QuerySnapshot` to compare against. + * @returns true if this `QuerySnapshot` is equal to the provided one. + */ + isEqual(other: QuerySnapshot): boolean; + } + /** + * A `VectorQuerySnapshot` contains zero or more `QueryDocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ + export class VectorQuerySnapshot< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + private constructor(); + /** + * The query on which you called `get` in order to get this + * `VectorQuerySnapshot`. + */ + readonly query: VectorQuery; + /** An array of all the documents in the QuerySnapshot. */ + readonly docs: Array>; + /** The number of documents in the QuerySnapshot. */ + readonly size: number; + /** True if there are no documents in the QuerySnapshot. */ + readonly empty: boolean; + /** The time this query snapshot was obtained. */ + readonly readTime: Timestamp; + /** + * Returns an array of the documents changes since the last snapshot. If + * this is the first snapshot, all documents will be in the list as added + * changes. + */ + docChanges(): DocumentChange[]; + /** + * Enumerates all of the documents in the QuerySnapshot. + * + * @param callback A callback to be called with a `DocumentSnapshot` for + * each document in the snapshot. + * @param thisArg The `this` binding for the callback. + */ + forEach( + callback: ( + result: QueryDocumentSnapshot, + ) => void, + thisArg?: any, + ): void; + /** + * Returns true if the document data in this `VectorQuerySnapshot` is equal to the + * provided one. + * + * @param other The `VectorQuerySnapshot` to compare against. + * @returns true if this `VectorQuerySnapshot` is equal to the provided one. + */ + isEqual(other: VectorQuerySnapshot): boolean; + } + /** + * The type of `DocumentChange` may be 'added', 'removed', or 'modified'. + */ + export type DocumentChangeType = 'added' | 'removed' | 'modified'; + /** + * A `DocumentChange` represents a change to the documents matching a query. + * It contains the document affected and the type of change that occurred. + */ + export interface DocumentChange< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + /** The type of change ('added', 'modified', or 'removed'). */ + readonly type: DocumentChangeType; + /** The document affected by this change. */ + readonly doc: QueryDocumentSnapshot; + /** + * The index of the changed document in the result set immediately prior to + * this DocumentChange (i.e. supposing that all prior DocumentChange objects + * have been applied). Is -1 for 'added' events. + */ + readonly oldIndex: number; + /** + * The index of the changed document in the result set immediately after + * this DocumentChange (i.e. supposing that all prior DocumentChange + * objects and the current DocumentChange object have been applied). + * Is -1 for 'removed' events. + */ + readonly newIndex: number; + /** + * Returns true if the data in this `DocumentChange` is equal to the + * provided one. + * + * @param other The `DocumentChange` to compare against. + * @returns true if this `DocumentChange` is equal to the provided one. + */ + isEqual(other: DocumentChange): boolean; + } + /** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using the methods + * inherited from `Query`). + */ + export class CollectionReference< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > extends Query { + private constructor(); + /** The identifier of the collection. */ + readonly id: string; + /** + * A reference to the containing Document if this is a subcollection, else + * null. + */ + readonly parent: DocumentReference | null; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + readonly path: string; + /** + * Retrieves the list of documents in this collection. + * + * The document references returned may include references to "missing + * documents", i.e. document locations that have no document present but + * which contain subcollections with documents. Attempting to read such a + * document reference (e.g. via `.get()` or `.onSnapshot()`) will return a + * `DocumentSnapshot` whose `.exists` property is false. + * + * @returns {Promise} The list of documents in this + * collection. + */ + listDocuments(): Promise< + Array> + >; + /** + * Get a `DocumentReference` for a randomly-named document within this + * collection. An automatically-generated unique ID will be used as the + * document ID. + * + * @returns The `DocumentReference` instance. + */ + doc(): DocumentReference; + /** + * Get a `DocumentReference` for the document within the collection at the + * specified path. + * + * @param documentPath A slash-separated path to a document. + * @returns The `DocumentReference` instance. + */ + doc(documentPath: string): DocumentReference; + /** + * Add a new document to this collection with the specified data, assigning + * it a document ID automatically. + * + * @param data An Object containing the data for the new document. + * @throws Error If the provided input is not a valid Firestore document. + * @returns A Promise resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ + add( + data: WithFieldValue, + ): Promise>; + /** + * Returns true if this `CollectionReference` is equal to the provided one. + * + * @param other The `CollectionReference` to compare against. + * @returns true if this `CollectionReference` is equal to the provided one. + */ + isEqual(other: CollectionReference): boolean; + /** + * Applies a custom data converter to this CollectionReference, allowing you + * to use your own custom model objects with Firestore. When you call add() + * on the returned CollectionReference instance, the provided converter will + * convert between Firestore data of type `NewDbModelType` and your custom + * type `NewAppModelType`. + * + * @param converter Converts objects to and from Firestore. Passing in + * `null` removes the current converter. + * @returns A CollectionReference that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData, + >( + converter: FirestoreDataConverter | null, + ): CollectionReference; + } + /** + * A `CollectionGroup` refers to all documents that are contained in a + * collection or subcollection with a specific collection ID. + */ + export class CollectionGroup< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > extends Query { + private constructor(); + /** + * Partitions a query by returning partition cursors that can be used to run + * the query in parallel. The returned cursors are split points that can be + * used as starting and end points for individual query invocations. + * + * @param desiredPartitionCount The desired maximum number of partition + * points. The number must be strictly positive. The actual number of + * partitions returned may be fewer. + * @returns An AsyncIterable of `QueryPartition`s. + */ + getPartitions( + desiredPartitionCount: number, + ): AsyncIterable>; + /** + * Applies a custom data converter to this `CollectionGroup`, allowing you + * to use your own custom model objects with Firestore. When you call get() + * on the returned `CollectionGroup`, the provided converter will convert + * between Firestore data of type `NewDbModelType` and your custom type + * `NewAppModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * @example + * class Post { + * constructor(readonly title: string, readonly author: string) {} + * + * toString(): string { + * return this.title + ', by ' + this.author; + * } + * } + * + * const postConverter = { + * toFirestore(post: Post): FirebaseFirestore.DocumentData { + * return {title: post.title, author: post.author}; + * }, + * fromFirestore( + * snapshot: FirebaseFirestore.QueryDocumentSnapshot + * ): Post { + * const data = snapshot.data(); + * return new Post(data.title, data.author); + * } + * }; + * + * const querySnapshot = await Firestore() + * .collectionGroup('posts') + * .withConverter(postConverter) + * .get(); + * for (const doc of querySnapshot.docs) { + * const post = doc.data(); + * post.title; // string + * post.toString(); // Should be defined + * post.someNonExistentProperty; // TS error + * } + * + * @param converter Converts objects to and from Firestore. Passing in + * `null` removes the current converter. + * @returns A `CollectionGroup` that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData, + >( + converter: FirestoreDataConverter | null, + ): CollectionGroup; + } + /** + * A split point that can be used in a query as a starting and/or end point for + * the query results. The cursors returned by {@link #startAt} and {@link + * #endBefore} can only be used in a query that matches the constraint of query + * that produced this partition. + */ + export class QueryPartition< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + private constructor(); + /** + * The cursor that defines the first result for this partition or + * `undefined` if this is the first partition. The cursor value must be + * destructured when passed to `startAt()` (for example with + * `query.startAt(...queryPartition.startAt)`). + * + * @returns Cursor values that can be used with {@link Query#startAt} or + * `undefined` if this is the first partition. + */ + get startAt(): unknown[] | undefined; + /** + * The cursor that defines the first result after this partition or + * `undefined` if this is the last partition. The cursor value must be + * destructured when passed to `endBefore()` (for example with + * `query.endBefore(...queryPartition.endBefore)`). + * + * @returns Cursor values that can be used with {@link Query#endBefore} or + * `undefined` if this is the last partition. + */ + get endBefore(): unknown[] | undefined; + /** + * Returns a query that only returns the documents for this partition. + * + * @returns A query partitioned by a {@link Query#startAt} and {@link + * Query#endBefore} cursor. + */ + toQuery(): Query; + } + /** + * Union type representing the aggregate type to be performed. + */ + export type AggregateType = 'count' | 'avg' | 'sum'; + /** + * The union of all `AggregateField` types that are supported by Firestore. + */ + export type AggregateFieldType = + | ReturnType + | ReturnType + | ReturnType; + /** + * Represents an aggregation that can be performed by Firestore. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + export class AggregateField { + private constructor(); + /** A type string to uniquely identify instances of this class. */ + readonly type = 'AggregateField'; + /** The kind of aggregation performed by this AggregateField. */ + public readonly aggregateType: AggregateType; + /** + * Compares this object with the given object for equality. + * + * This object is considered "equal" to the other object if and only if + * `other` performs the same kind of aggregation on the same field (if any). + * + * @param other The object to compare to this object for equality. + * @returns `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual(other: AggregateField): boolean; + /** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ + static count(): AggregateField; + /** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ + static average(field: string | FieldPath): AggregateField; + /** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ + static sum(field: string | FieldPath): AggregateField; + } + /** + * A type whose property values are all `AggregateField` objects. + */ + export interface AggregateSpec { + [field: string]: AggregateFieldType; + } + /** + * A type whose keys are taken from an `AggregateSpec`, and whose values are + * the result of the aggregation performed by the corresponding + * `AggregateField` from the input `AggregateSpec`. + */ + export type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; + }; + /** + * A query that calculates aggregations over an underlying query. + */ + export class AggregateQuery< + AggregateSpecType extends AggregateSpec, + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + private constructor(); + /** The query whose aggregations will be calculated by this object. */ + readonly query: Query; + /** + * Executes this query. + * + * @returns A promise that will be resolved with the results of the query. + */ + get(): Promise< + AggregateQuerySnapshot + >; + /** + * Plans and optionally executes this query. Returns a Promise that will be + * resolved with the planner information, statistics from the query execution (if any), + * and the query results (if any). + * + * @returns A Promise that will be resolved with the planner information, statistics + * from the query execution (if any), and the query results (if any). + */ + explain( + options?: ExplainOptions, + ): Promise< + ExplainResults< + AggregateQuerySnapshot + > + >; + /** + * Compares this object with the given object for equality. + * + * This object is considered "equal" to the other object if and only if + * `other` performs the same aggregations as this `AggregateQuery` and + * the underlying Query of `other` compares equal to that of this object + * using `Query.isEqual()`. + * + * @param other The object to compare to this object for equality. + * @returns `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual( + other: AggregateQuery, + ): boolean; + } + /** + * The results of executing an aggregation query. + */ + export class AggregateQuerySnapshot< + AggregateSpecType extends AggregateSpec, + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + private constructor(); + /** The query that was executed to produce this result. */ + readonly query: AggregateQuery< + AggregateSpecType, + AppModelType, + DbModelType + >; + /** The time this snapshot was read. */ + readonly readTime: Timestamp; + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the + * values will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; + /** + * Compares this object with the given object for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they + * have the same data and their underlying queries compare "equal" using + * `AggregateQuery.isEqual()`. + * + * @param other The object to compare to this object for equality. + * @returns `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual( + other: AggregateQuerySnapshot< + AggregateSpecType, + AppModelType, + DbModelType + >, + ): boolean; + } + /** + * A query that finds the document whose vector fields are closest to a certain vector. + */ + export class VectorQuery< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + private constructor(); + /** The query whose results participants in the distance search. */ + readonly query: Query; + /** + * Executes this query. + * + * @returns A promise that will be resolved with the results of the query. + */ + get(): Promise>; + /** + * Compares this object with the given object for equality. + * + * This object is considered "equal" to the other object if and only if + * `other` performs the same vector distance search as this `VectorQuery` and + * the underlying Query of `other` compares equal to that of this object + * using `Query.isEqual()`. + * + * @param other The object to compare to this object for equality. + * @returns `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual(other: VectorQuery): boolean; + } + /** + * Represent a vector type in Firestore documents. + */ + export class VectorValue { + private constructor(values: number[] | undefined); + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns true if the two `VectorValue` has the same raw number arrays, returns false otherwise. + */ + isEqual(other: VectorValue): boolean; + } + /** + * Sentinel values that can be used when writing document fields with set(), + * create() or update(). + */ + export class FieldValue { + private constructor(); + /** + * Returns a sentinel used with set(), create() or update() to include a + * server-generated timestamp in the written data. + * + * @returns The FieldValue sentinel for use in a call to set(), create() or + * update(). + */ + static serverTimestamp(): FieldValue; + /** + * Returns a sentinel for use with update() or set() with {merge:true} to + * mark a field for deletion. + * + * @returns The FieldValue sentinel for use in a call to set() or update(). + */ + static delete(): FieldValue; + /** + * Returns a special value that can be used with set(), create() or update() + * that tells the server to increment the field's current value by the given + * value. + * + * If either current field value or the operand uses floating point + * precision, both values will be interpreted as floating point numbers and + * all arithmetic will follow IEEE 754 semantics. Otherwise, integer + * precision is kept and the result is capped between -2^63 and 2^63-1. + * + * If the current field value is not of type 'number', or if the field does + * not yet exist, the transformation will set the field to the given value. + * + * @param n The value to increment by. + * @returns The FieldValue sentinel for use in a call to set(), create() or + * update(). + */ + static increment(n: number): FieldValue; + /** + * Returns a special value that can be used with set(), create() or update() + * that tells the server to union the given elements with any array value + * that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements The elements to union into the array. + * @returns The FieldValue sentinel for use in a call to set(), create() or + * update(). + */ + static arrayUnion(...elements: any[]): FieldValue; + /** + * Returns a special value that can be used with set(), create() or update() + * that tells the server to remove the given elements from any array value + * that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is + * not already an array it will be overwritten with an empty array. + * + * @param elements The elements to remove from the array. + * @returns The FieldValue sentinel for use in a call to set(), create() or + * update(). + */ + static arrayRemove(...elements: any[]): FieldValue; + /** + * @returns A new `VectorValue` constructed with a copy of the given array of number. + */ + static vector(values?: number[]): VectorValue; + /** + * Returns true if this `FieldValue` is equal to the provided one. + * + * @param other The `FieldValue` to compare against. + * @returns true if this `FieldValue` is equal to the provided one. + */ + isEqual(other: FieldValue): boolean; + } + /** + * A FieldPath refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + */ + export class FieldPath { + /** + * Creates a FieldPath from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames A list of field names. + */ + constructor(...fieldNames: string[]); + /** + * Returns a special sentinel FieldPath to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ + static documentId(): FieldPath; + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; + } + /** + * A Timestamp represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian + * Calendar which extends the Gregorian calendar backwards to year one. It is + * encoded assuming all minutes are 60 seconds long, i.e. leap seconds are + * "smeared" so that no leap second table is needed for interpretation. Range + * is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. + * + * @see https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto + */ + export class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns A new `Timestamp` representing the current date. + */ + static now(): Timestamp; + /** + * Creates a new timestamp from the given date. + * + * @param date The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the + * given date. + */ + static fromDate(date: Date): Timestamp; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the + * given number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + /** + * Creates a new timestamp. + * + * @param seconds The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be from + * 0 to 999,999,999 inclusive. + */ + constructor(seconds: number, nanoseconds: number); + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + /** The non-negative fractions of a second at nanosecond resolution. */ + readonly nanoseconds: number; + /** + * Returns a new `Date` corresponding to this timestamp. This may lose + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Returns the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other The `Timestamp` to compare against. + * @returns 'true' if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp): boolean; + /** + * Converts this object to a primitive `string`, which allows `Timestamp` objects to be compared + * using the `>`, `<=`, `>=` and `>` operators. + * + * @returns a string encoding of this object. + */ + valueOf(): string; + } + /** + * Builds a Firestore data bundle with results from the given document and query snapshots. + */ + export class BundleBuilder { + /** The ID of this bundle. */ + readonly bundleId: string; + /** + * Adds a Firestore `DocumentSnapshot` to the bundle. Both the documents data and the document + * read time will be included in the bundle. + * + * @param documentSnapshot A `DocumentSnapshot` to add. + * @returns This instance. + */ + add( + documentSnapshot: DocumentSnapshot, + ): BundleBuilder; + /** + * Adds a Firestore `QuerySnapshot` to the bundle. Both the documents in the query results and + * the query read time will be included in the bundle. + * + * @param queryName The name of the query to add. + * @param querySnapshot A `QuerySnapshot` to add to the bundle. + * @returns This instance. + */ + add( + queryName: string, + querySnapshot: QuerySnapshot, + ): BundleBuilder; + /** + * Builds the bundle and returns the result as a `Buffer` instance. + */ + build(): Buffer; + } + /** + * The v1beta1 Veneer client. This client provides access to to the underlying + * Firestore v1beta1 RPCs. + * @deprecated Use v1 instead. + */ + export const v1beta1: { + FirestoreClient: typeof import('./v1beta1/firestore_client').FirestoreClient; + }; + /** + * The v1 Veneer clients. These clients provide access to the Firestore Admin + * API and the underlying Firestore v1 RPCs. + */ + export const v1: { + FirestoreClient: typeof import('./v1/firestore_client').FirestoreClient; + FirestoreAdminClient: typeof import('./v1/firestore_admin_client').FirestoreAdminClient; + }; + /** + * Status codes returned by Firestore's gRPC calls. + */ + export enum GrpcStatus { + OK = 0, + CANCELLED = 1, + UNKNOWN = 2, + INVALID_ARGUMENT = 3, + DEADLINE_EXCEEDED = 4, + NOT_FOUND = 5, + ALREADY_EXISTS = 6, + PERMISSION_DENIED = 7, + RESOURCE_EXHAUSTED = 8, + FAILED_PRECONDITION = 9, + ABORTED = 10, + OUT_OF_RANGE = 11, + UNIMPLEMENTED = 12, + INTERNAL = 13, + UNAVAILABLE = 14, + DATA_LOSS = 15, + UNAUTHENTICATED = 16, + } + /** + * A `Filter` represents a restriction on one or more field values and can + * be used to refine the results of a {@link Query}. + * `Filters`s are created by invoking {@link Filter#where}, {@link Filter#or}, + * or {@link Filter#and} and can then be passed to {@link Query#where} + * to create a new {@link Query} instance that also contains this `Filter`. + */ + export abstract class Filter { + /** + * Creates and returns a new [Filter]{@link Filter}, which can be + * applied to [Query.where()]{@link Query#where}, [Filter.or()]{@link Filter#or}, + * or [Filter.and()]{@link Filter#and}. When applied to a [Query]{@link Query} + * it requires that documents must contain the specified field and that its value should + * satisfy the relation constraint provided. + * + * Returns a new Filter that can be used to constrain the value of a Document property. + * + * @param {string|FieldPath} fieldPath The name of a property value to compare. + * @param {string} opStr A comparison operation in the form of a string + * (e.g., "<"). + * @param {*} value The value to which to compare the field for inclusion in + * a query. + * @returns {Filter} The created Filter. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.where(Filter.where('foo', '==', 'bar')).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + static where( + fieldPath: string | FieldPath, + opStr: WhereFilterOp, + value: unknown, + ): Filter; + /** + * Creates and returns a new [Filter]{@link Filter} that is a + * disjunction of the given {@link Filter}s. A disjunction filter includes + * a document if it satisfies any of the given {@link Filter}s. + * + * The returned Filter can be applied to [Query.where()]{@link Query#where}, + * [Filter.or()]{@link Filter#or}, or [Filter.and()]{@link Filter#and}. When + * applied to a [Query]{@link Query} it requires that documents must satisfy + * one of the provided {@link Filter}s. + * + * @param {...Filter} filters Optional. The {@link Filter}s + * for OR operation. These must be created with calls to {@link Filter#where}, + * {@link Filter#or}, or {@link Filter#and}. + * @returns {Filter} The created {@link Filter}. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * // doc.foo == 'bar' || doc.baz > 0 + * let orFilter = Filter.or(Filter.where('foo', '==', 'bar'), Filter.where('baz', '>', 0)); + * + * collectionRef.where(orFilter).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + static or(...filters: Filter[]): Filter; + /** + * Creates and returns a new [Filter]{@link Filter} that is a + * conjunction of the given {@link Filter}s. A conjunction filter includes + * a document if it satisfies all of the given {@link Filter}s. + * + * The returned Filter can be applied to [Query.where()]{@link Query#where}, + * [Filter.or()]{@link Filter#or}, or [Filter.and()]{@link Filter#and}. When + * applied to a [Query]{@link Query} it requires that documents must satisfy + * one of the provided {@link Filter}s. + * + * @param {...Filter} filters Optional. The {@link Filter}s + * for OR operation. These must be created with calls to {@link Filter#where}, + * {@link Filter#or}, or {@link Filter#and}. + * @returns {Filter} The created {@link Filter}. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * // doc.foo == 'bar' && doc.baz > 0 + * let orFilter = Filter.and(Filter.where('foo', '==', 'bar'), Filter.where('baz', '>', 0)); + * + * collectionRef.where(orFilter).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + static and(...filters: Filter[]): Filter; + } + type Duration = { + /** Signed seconds of the span of time. */ + seconds: number; + /** + * 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. + */ + nanoseconds: number; + }; + /** Options used to configure explain queries. */ + export interface ExplainOptions { + /** + * Whether analyzing the query is enabled. If true, the query will be + * executed and execution statistics will be returned as part of the + * [ExplainResults]{@link ExplainResults}. + */ + readonly analyze?: boolean; + } + /** + * PlanSummary contains information about the planning stage of a query. + */ + export interface PlanSummary { + /** + * Information about the indexes that were used to serve the query. + * This should be inspected or logged, because the contents are intended to be + * human-readable. Contents are subject to change, and it is advised to not + * program against this object. + */ + readonly indexesUsed: Record[]; + } + /** ExecutionStats contains information about the execution of a query. */ + export interface ExecutionStats { + /** The number of query results. */ + readonly resultsReturned: number; + /** The total execution time of the query. */ + readonly executionDuration: Duration; + /** The number of read operations that occurred when executing the query. */ + readonly readOperations: number; + /** + * Contains additional statistics related to the query execution. + * This should be inspected or logged, because the contents are intended to be + * human-readable. Contents are subject to change, and it is advised to not + * program against this object. + */ + readonly debugStats: Record; + } + /** + * ExplainMetrics contains information about planning and execution of a query. + */ + export interface ExplainMetrics { + /** + * Information about the query plan. + */ + readonly planSummary: PlanSummary; + /** + * Information about the execution of the query, or null if the query was + * not executed. + */ + readonly executionStats: ExecutionStats | null; + } + /** + * ExplainResults contains information about planning, execution, and results + * of a query. + */ + export interface ExplainResults { + /** + * Information about planning and execution of the query. + */ + readonly metrics: ExplainMetrics; + /** + * The snapshot that contains the results of executing the query, or null + * if the query was not executed. + */ + readonly snapshot: T | null; + } + /** + * Specifies the behavior of the {@link VectorQuery} generated by a call to {@link Query.findNearest:VectorQueryOptions}. + */ + export interface VectorQueryOptions { + /** + * A string or {@link FieldPath} specifying the vector field to search on. + */ + vectorField: string | FieldPath; + /** + * The {@link VectorValue} used to measure the distance from `vectorField` values in the documents. + */ + queryVector: VectorValue | Array; + /** + * Specifies the upper bound of documents to return, must be a positive integer with a maximum value of 1000. + */ + limit: number; + /** + * Specifies what type of distance is calculated when performing the query. + */ + distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; + /** + * Optionally specifies the name of a field that will be set on each returned DocumentSnapshot, + * which will contain the computed distance for the document. + */ + distanceResultField?: string | FieldPath; + /** + * Specifies a threshold for which no less similar documents will be returned. The behavior + * of the specified `distanceMeasure` will affect the meaning of the distance threshold. + * + * - For `distanceMeasure: "EUCLIDEAN"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE euclidean_distance <= distanceThreshold + * - For `distanceMeasure: "COSINE"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE cosine_distance <= distanceThreshold + * - For `distanceMeasure: "DOT_PRODUCT"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE dot_product_distance >= distanceThreshold + */ + distanceThreshold?: number; + } + export namespace Pipelines { + /** + * @beta + * Represents an expression that has been assigned an alias using the `.as()` method. + * + * This class wraps an existing `Expression` and associates it with a user-defined alias, + * allowing the expression's result to be referred to by a different name in the output + * of a Firestore pipeline query, particularly within `select()` operations. + * + * @internal + */ + export type ExpressionType = + | 'Field' + | 'Constant' + | 'Function' + | 'AggregateFunction' + | 'ListOfExprs' + | 'AliasedExpression'; + /** + * @beta + * Represents an expression that can be evaluated to a value within the execution of a {@link + * Pipeline}. + * + * Expressions are the building blocks for creating complex queries and transformations in + * Firestore pipelines. They can represent: + * + * - **Field references:** Access values from document fields. + * - **Literals:** Represent constant values (strings, numbers, booleans). + * - **Function calls:** Apply functions to one or more expressions. + * + * The `Expression` class provides a fluent API for building expressions. You can chain together + * method calls to create complex expressions. + */ + export abstract class Expression { + abstract readonly expressionType: ExpressionType; + /** + * @beta + * Creates an expression that adds this expression to another expression. + * + * @example + * ```typescript + * // Add the value of the 'quantity' field and the 'reserve' field. + * field("quantity").add(field("reserve")); + * ``` + * + * @param second The expression or literal to add to this expression. + * @param others Optional additional expressions or literals to add to this expression. + * @returns A new `Expression` representing the addition operation. + */ + add( + second: Expression | unknown, + ...others: Array + ): FunctionExpression; + /** + * @beta + * Wraps the expression in a [BooleanExpression]. + * + * @returns A [BooleanExpression] representing the same expression. + */ + asBoolean(): BooleanExpression; + /** + * @beta + * Creates an expression that subtracts another expression from this expression. + * + * @example + * ```typescript + * // Subtract the 'discount' field from the 'price' field + * field("price").subtract(field("discount")); + * ``` + * + * @param subtrahend The expression to subtract from this expression. + * @returns A new `Expression` representing the subtraction operation. + */ + subtract(subtrahend: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that subtracts a constant value from this expression. + * + * @example + * ```typescript + * // Subtract 20 from the value of the 'total' field + * field("total").subtract(20); + * ``` + * + * @param subtrahend The constant value to subtract. + * @returns A new `Expression` representing the subtraction operation. + */ + subtract(subtrahend: number): FunctionExpression; + /** + * @beta + * Creates an expression that multiplies this expression by another expression. + * + * @example + * ```typescript + * // Multiply the 'quantity' field by the 'price' field + * field("quantity").multiply(field("price")); + * ``` + * + * @param second The second expression or literal to multiply by. + * @param others Optional additional expressions or literals to multiply by. + * @returns A new `Expression` representing the multiplication operation. + */ + multiply( + second: Expression | number, + ...others: Array + ): FunctionExpression; + /** + * @beta + * Creates an expression that divides this expression by another expression. + * + * @example + * ```typescript + * // Divide the 'total' field by the 'count' field + * field("total").divide(field("count")); + * ``` + * + * @param divisor The expression to divide by. + * @returns A new `Expression` representing the division operation. + */ + divide(divisor: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that divides this expression by a constant value. + * + * @example + * ```typescript + * // Divide the 'value' field by 10 + * field("value").divide(10); + * ``` + * + * @param divisor The constant value to divide by. + * @returns A new `Expression` representing the division operation. + */ + divide(divisor: number): FunctionExpression; + /** + * @beta + * Creates an expression that calculates the modulo (remainder) of dividing this expression by another expression. + * + * @example + * ```typescript + * // Calculate the remainder of dividing the 'value' field by the 'divisor' field + * field("value").mod(field("divisor")); + * ``` + * + * @param expression The expression to divide by. + * @returns A new `Expression` representing the modulo operation. + */ + mod(expression: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that calculates the modulo (remainder) of dividing this expression by a constant value. + * + * @example + * ```typescript + * // Calculate the remainder of dividing the 'value' field by 10 + * field("value").mod(10); + * ``` + * + * @param value The constant value to divide by. + * @returns A new `Expression` representing the modulo operation. + */ + mod(value: number): FunctionExpression; + + /** + * @beta + * Creates an expression that checks if this expression is equal to another expression. + * + * @example + * ```typescript + * // Check if the 'age' field is equal to the value of another field named 'otherAge'. + * field("age").equal(field("otherAge")); + * + * // Check if the 'status' field is equal to a string literal. + * field("status").equal("active"); + * ``` + * + * @param expression The expression to compare for equality. + * @returns A new `BooleanExpression` representing the equality comparison. + */ + equal(expression: Expression): BooleanExpression; + /** + * @beta + * Creates an expression that checks if this expression is equal to a constant value. + * + * @example + * ```typescript + * // Check if the 'city' field is equal to "London" + * field("city").equal("London"); + * ``` + * + * @param value The constant value to compare for equality. + * @returns A new `Expression` representing the equality comparison. + */ + equal(value: unknown): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if this expression is not equal to another expression. + * + * @example + * ```typescript + * // Check if the 'status' field is not equal to "completed" + * field("status").notEqual("completed"); + * ``` + * + * @param expression The expression to compare for inequality. + * @returns A new `BooleanExpression` representing the inequality comparison. + */ + notEqual(expression: Expression): BooleanExpression; + /** + * @beta + * Creates an expression that checks if this expression is not equal to a constant value. + * + * @example + * ```typescript + * // Check if the 'country' field is not equal to "USA" + * field("country").notEqual("USA"); + * ``` + * + * @param value The constant value to compare for inequality. + * @returns A new `Expression` representing the inequality comparison. + */ + notEqual(value: unknown): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if this expression is less than another expression. + * + * @example + * ```typescript + * // Check if the 'age' field is less than 'limit' + * field("age").lessThan(field('limit')); + * ``` + * + * @param expression The expression to compare against. + * @returns A new `BooleanExpression` representing the less than comparison. + */ + lessThan(expression: Expression): BooleanExpression; + /** + * @beta + * Creates an expression that checks if this expression is less than a constant value. + * + * @example + * ```typescript + * // Check if the 'price' field is less than 50 + * field("price").lessThan(50); + * ``` + * + * @param value The constant value to compare for less than. + * @returns A new `Expression` representing the less than comparison. + */ + lessThan(value: unknown): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if the current expression's value is less than or equal to the value of another expression. + * + * @example + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * field("quantity").lessThanOrEqual(constant(20)); + * ``` + * + * @param expression The expression to compare against. + * @returns A new `BooleanExpression` representing the less than or equal to comparison. + */ + lessThanOrEqual(expression: Expression): BooleanExpression; + /** + * @beta + * Creates an expression that checks if this expression is less than or equal to a constant value. + * + * @example + * ```typescript + * // Check if the 'score' field is less than or equal to 70 + * field("score").lessThanOrEqual(70); + * ``` + * + * @param value The constant value to compare for less than or equal to. + * @returns A new `Expression` representing the less than or equal to comparison. + */ + lessThanOrEqual(value: unknown): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if this expression is greater than another expression. + * + * @example + * ```typescript + * // Check if the 'age' field is greater than the 'limit' field + * field("age").greaterThan(field("limit")); + * ``` + * + * @param expression The expression to compare for greater than. + * @returns A new `BooleanExpression` representing the greater than comparison. + */ + greaterThan(expression: Expression): BooleanExpression; + /** + * @beta + * Creates an expression that checks if this expression is greater than a constant value. + * + * @example + * ```typescript + * // Check if the 'price' field is greater than 100 + * field("price").greaterThan(100); + * ``` + * + * @param value The constant value to compare for greater than. + * @returns A new `Expression` representing the greater than comparison. + */ + greaterThan(value: unknown): BooleanExpression; + /** + * @beta + * Creates an expression that checks if this expression is greater than or equal to another + * expression. + * + * @example + * ```typescript + * // Check if the 'quantity' field is greater than or equal to field 'requirement' plus 1 + * field("quantity").greaterThanOrEqual(field('requirement').add(1)); + * ``` + * + * @param expression The expression to compare for greater than or equal to. + * @returns A new `Expression` representing the greater than or equal to comparison. + */ + greaterThanOrEqual(expression: Expression): BooleanExpression; + /** + * @beta + * Creates an expression that checks if this expression is greater than or equal to a constant + * value. + * + * @example + * ```typescript + * // Check if the 'score' field is greater than or equal to 80 + * field("score").greaterThanOrEqual(80); + * ``` + * + * @param value The constant value to compare for greater than or equal to. + * @returns A new `Expression` representing the greater than or equal to comparison. + */ + greaterThanOrEqual(value: unknown): BooleanExpression; + + /** + * @beta + * Creates an expression that concatenates an array expression with one or more other arrays. + * + * @example + * ```typescript + * // Combine the 'items' array with another array field. + * field("items").arrayConcat(field("otherItems")); + * ``` + * @param secondArray Second array expression or array literal to concatenate. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @returns A new `Expr` representing the concatenated array. + */ + arrayConcat( + secondArray: Expression | unknown[], + ...otherArrays: Array + ): FunctionExpression; + + /** + * @beta + * Creates an expression that checks if an array contains a specific element. + * + * @example + * ```typescript + * // Check if the 'sizes' array contains the value from the 'selectedSize' field + * field("sizes").arrayContains(field("selectedSize")); + * ``` + * + * @param expression The element to search for in the array. + * @returns A new `Expression` representing the 'array_contains' comparison. + */ + arrayContains(expression: Expression): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an array contains a specific value. + * + * @example + * ```typescript + * // Check if the 'colors' array contains "red" + * field("colors").arrayContains("red"); + * ``` + * + * @param value The element to search for in the array. + * @returns A new `Expression` representing the 'array_contains' comparison. + */ + arrayContains(value: unknown): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an array contains all the specified elements. + * + * @example + * ```typescript + * // Check if the 'tags' array contains both the value in field "tag1" and the literal value "tag2" + * field("tags").arrayContainsAll([field("tag1"), "tag2"]); + * ``` + * + * @param values The elements to check for in the array. + * @returns A new `Expression` representing the 'array_contains_all' comparison. + */ + arrayContainsAll(values: Array): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an array contains all the specified elements. + * + * @example + * ```typescript + * // Check if the 'tags' array contains both of the values from field "tag1" and the literal value "tag2" + * field("tags").arrayContainsAll(array([field("tag1"), "tag2"])); + * ``` + * + * @param arrayExpression The elements to check for in the array. + * @returns A new `Expression` representing the 'array_contains_all' comparison. + */ + arrayContainsAll(arrayExpression: Expression): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an array contains any of the specified elements. + * + * @example + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "cate2" + * field("categories").arrayContainsAny([field("cate1"), field("cate2")]); + * ``` + * + * @param values The elements to check for in the array. + * @returns A new `Expression` representing the 'array_contains_any' comparison. + */ + arrayContainsAny(values: Array): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an array contains any of the specified elements. + * + * @example + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * field("groups").arrayContainsAny(array([field("userGroup"), "guest"])); + * ``` + * + * @param arrayExpression The elements to check for in the array. + * @returns A new `Expression` representing the 'array_contains_any' comparison. + */ + arrayContainsAny(arrayExpression: Expression): BooleanExpression; + /** + * @beta + * Creates an expression that calculates the length of an array. + * + * @example + * ```typescript + * // Get the number of items in the 'cart' array + * field("cart").arrayLength(); + * ``` + * + * @returns A new `Expression` representing the length of the array. + */ + arrayLength(): FunctionExpression; + + /** + * @beta + * Creates an expression that checks if this expression is equal to any of the provided values or + * expressions. + * + * @example + * ```typescript + * // Check if the 'category' field is either "Electronics" or the value of field 'primaryType' + * field("category").equalAny(["Electronics", field("primaryType")]); + * ``` + * + * @param values An array of values or expressions to check against. + * @returns A new `BooleanExpression` representing the 'IN' comparison. + */ + equalAny(values: Array): BooleanExpression; + /** + * @beta + * Creates an expression that checks if this expression is equal to any of the provided values or + * expressions. + * + * @example + * ```typescript + * // Check if the 'category' field is either "Electronics" or the value of field 'primaryType' + * field("category").equalAny(array(["Electronics", field("primaryType")])); + * ``` + * + * @param arrayExpression An expression that evaluates to an array of values to check against. + * @returns A new `Expression` representing the 'IN' comparison. + */ + equalAny(arrayExpression: Expression): BooleanExpression; + /** + * @beta + * Creates an expression that checks if this expression is not equal to any of the provided values or + * expressions. + * + * @example + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * field("status").notEqualAny(["pending", field("rejectedStatus")]); + * ``` + * + * @param values The values or expressions to check against. + * @returns A new `Expression` representing the 'NotEqAny' comparison. + */ + notEqualAny(values: Array): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if the current expression's value is not equal to any of the values within the array produced by the `arrayExpression`. + * + * @example + * ```typescript + * // Check if the 'status' field is not equal to any value in the array returned by the 'rejectedStatuses' field. + * field("status").notEqualAny(field('rejectedStatuses')); + * ``` + * + * @param arrayExpression An `Expression` that evaluates to an array of values to compare against. + * @returns A new `BooleanExpression` representing the result of the 'not equal to any' comparison. + */ + notEqualAny(arrayExpression: Expression): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a field exists in the document. + * + * @example + * ```typescript + * // Check if the document has a field named "phoneNumber" + * field("phoneNumber").exists(); + * ``` + * + * @returns A new `BooleanExpression` representing the 'exists' check. + */ + exists(): BooleanExpression; + /** + * @beta + * Creates an expression that calculates the character length of a string in UTF-8. + * + * @example + * ```typescript + * // Get the character length of the 'name' field in its UTF-8 form. + * field("name").charLength(); + * ``` + * + * @returns A new `Expression` representing the length of the string. + */ + charLength(): FunctionExpression; + + /** + * @beta + * Creates an expression that performs a case-sensitive string comparison. + * + * @example + * ```typescript + * // Check if the 'title' field contains the word "guide" (case-sensitive) + * field("title").like("%guide%"); + * ``` + * + * @param pattern The string pattern to search for. You can use "%" as a wildcard character within the pattern. + * @returns A new `BooleanExpression` representing the 'like' comparison. + */ + like(pattern: string): BooleanExpression; + + /** + * @beta + * Creates an expression that performs a case-sensitive string comparison. + * + * @example + * ```typescript + * // Check if the 'description' field matches a pattern from another field + * field("description").like(field("searchPattern")); + * ``` + * + * @param pattern An `Expression` that evaluates to the string pattern to search for. You can use "%" as a wildcard character within the pattern. + * @returns A new `BooleanExpression` representing the 'like' comparison. + */ + like(pattern: Expression): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a string contains a specified regular expression as a + * substring. + * + * @example + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * field("description").regexContains("(?i)example"); + * ``` + * + * @param pattern The regular expression to use for the search. + * @returns A new `BooleanExpression` representing the 'contains' comparison. + */ + regexContains(pattern: string): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a string contains a specified regular expression as a + * substring. + * + * @example + * ```typescript + * // Check if the 'description' field contains the regular expression stored in field 'regex' + * field("description").regexContains(field("regex")); + * ``` + * + * @param pattern The regular expression to use for the search. + * @returns A new `BooleanExpression` representing the 'contains' comparison. + */ + regexContains(pattern: Expression): BooleanExpression; + + /** + * @beta + * Creates an expression that returns the first substring of a string expression that matches + * a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract the domain from an email address + * field("email").regexFind("@.+") + * ``` + * + * @param pattern - The regular expression to search for. + * @returns A new {@link Expression} representing the regular expression find function. + */ + regexFind(pattern: string): FunctionExpression; + /** + * @beta + * Creates an expression that returns the first substring of a string expression that matches + * a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract the domain from an email address + * field("email").regexFind(field("domain")) + * ``` + * + * @param pattern - The regular expression to search for. + * @returns A new {@link Expression} representing the regular expression find function. + */ + regexFind(pattern: Expression): FunctionExpression; + /** + * @beta + * + * Creates an expression that evaluates to a list of all substrings in this string expression that + * match a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract all hashtags from a post content field + * field("content").regexFindAll("#[A-Za-z0-9_]+") + * ``` + * + * @param pattern - The regular expression to search for. + * @returns A new {@link Expression} that evaluates to an array of matched substrings. + */ + regexFindAll(pattern: string): FunctionExpression; + /** + * @beta + * + * Creates an expression that evaluates to a list of all substrings in this string expression that + * match a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract all names from a post content field + * field("content").regexFindAll(field("names")) + * ``` + * + * @param pattern - The regular expression to search for. + * @returns A new {@link Expression} that evaluates to an array of matched substrings. + */ + regexFindAll(pattern: Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that checks if a string matches a specified regular expression. + * + * @example + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * field("email").regexMatch("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * ``` + * + * @param pattern The regular expression to use for the match. + * @returns A new `Expression` representing the regular expression match. + */ + regexMatch(pattern: string): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a string matches a specified regular expression. + * + * @example + * ```typescript + * // Check if the 'email' field matches a regular expression stored in another field. + * field("email").regexMatch(field("regexPattern")); + * ``` + * + * @param pattern An expression that evaluates to the regular expression string to use for the match. + * @returns A new `BooleanExpression` representing the result of the regular expression match. + */ + regexMatch(pattern: Expression): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a string contains a specified substring. + * + * @example + * ```typescript + * // Check if the 'description' field contains "example". + * field("description").stringContains("example"); + * ``` + * + * @param substring The substring to search for. + * @returns A new `Expression` representing the 'contains' comparison. + */ + stringContains(substring: string): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a string contains the string represented by another expression. + * + * @example + * ```typescript + * // Check if the 'description' field contains the value of the 'keyword' field. + * field("description").stringContains(field("keyword")); + * ``` + * + * @param expr The expression representing the substring to search for. + * @returns A new `BooleanExpression` representing the 'contains' comparison. + */ + stringContains(expr: Expression): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a string starts with a given prefix. + * + * @example + * ```typescript + * // Check if the 'name' field starts with "Mr." + * field("name").startsWith("Mr."); + * ``` + * + * @param prefix The prefix to check for. + * @returns A new `Expression` representing the 'starts with' comparison. + */ + startsWith(prefix: string): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if the string value of the current expression starts with the string value of the given prefix expression. + * + * @example + * ```typescript + * // Check if the 'fullName' field starts with the value of the 'firstName' field + * field("fullName").startsWith(field("firstName")); + * ``` + * + * @param prefix An expression whose string value will be used as the prefix to check against. + * @returns A new `BooleanExpression` representing the 'starts with' comparison result. + */ + startsWith(prefix: Expression): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a string ends with a given postfix. + * + * @example + * ```typescript + * // Check if the 'filename' field ends with ".txt" + * field("filename").endsWith(".txt"); + * ``` + * + * @param suffix The postfix to check for. + * @returns A new `BooleanExpression` representing the 'ends with' comparison. + */ + endsWith(suffix: string): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a string ends with a given postfix (represented as an + * expression). + * + * @example + * ```typescript + * // Check if the 'url' field ends with the value of the 'extension' field + * field("url").endsWith(field("extension")); + * ``` + * + * @param suffix The postfix expression to check for. + * @returns A new `Expression` representing the 'ends with' comparison. + */ + endsWith(suffix: Expression): BooleanExpression; + /** + * @beta + * Creates an expression that converts a string to lowercase. + * + * @example + * ```typescript + * // Convert the 'name' field to lowercase + * field("name").toLower(); + * ``` + * + * @returns A new `Expression` representing the lowercase string. + */ + toLower(): FunctionExpression; + /** + * @beta + * Creates an expression that converts a string to uppercase. + * + * @example + * ```typescript + * // Convert the 'title' field to uppercase + * field("title").toUpper(); + * ``` + * + * @returns A new `Expression` representing the uppercase string. + */ + toUpper(): FunctionExpression; + /** + * @beta + * Creates an expression that removes leading and trailing characters from a string or byte array. + * + * @example + * ```typescript + * // Trim whitespace from the 'userInput' field + * field("userInput").trim(); + * + * // Trim quotes from the 'userInput' field + * field("userInput").trim('"'); + * ``` + * @param valueToTrim Optional This parameter is treated as a set of characters or bytes that will be + * trimmed from the input. If not specified, then whitespace will be trimmed. + * @returns A new `Expr` representing the trimmed string or byte array. + */ + trim( + valueToTrim?: string | Expression | Uint8Array | Buffer, + ): FunctionExpression; + /** + * @beta + * Creates an expression that concatenates string expressions together. + * + * @example + * ```typescript + * // Combine the 'firstName', " ", and 'lastName' fields into a single string + * field("firstName").stringConcat(constant(" "), field("lastName")); + * ``` + * + * @param secondString The additional expression or string literal to concatenate. + * @param otherStrings Optional additional expressions or string literals to concatenate. + * @returns A new `Expression` representing the concatenated string. + */ + stringConcat( + secondString: Expression | string, + ...otherStrings: Array + ): FunctionExpression; + /** + * @beta + * Creates an expression that reverses this string or bytes expression. + * + * @example + * ```typescript + * // Reverse the value of the 'myString' field. + * field("myString").reverse(); + * ``` + * + * @returns A new {@code Expression} representing the reversed string or bytes. + */ + reverse(): FunctionExpression; + /** + * @beta + * Creates an expression that calculates the length of this string expression in bytes. + * + * @example + * ```typescript + * // Calculate the length of the 'myString' field in bytes. + * field("myString").byteLength(); + * ``` + * + * @returns A new {@code Expression} representing the length of the string in bytes. + */ + byteLength(): FunctionExpression; + /** + * @beta + * Creates an expression that computes the ceiling of a numeric value. + * + * @example + * ```typescript + * // Compute the ceiling of the 'price' field. + * field("price").ceil(); + * ``` + * + * @returns A new {@code Expression} representing the ceiling of the numeric value. + */ + ceil(): FunctionExpression; + /** + * @beta + * Creates an expression that computes the floor of a numeric value. + * + * @example + * ```typescript + * // Compute the floor of the 'price' field. + * field("price").floor(); + * ``` + * + * @returns A new {@code Expression} representing the floor of the numeric value. + */ + floor(): FunctionExpression; + + /** + * @beta + * Creates an expression that computes the absolute value of a numeric value. + * + * @example + * ```typescript + * // Compute the absolute value of the 'price' field. + * field("price").abs(); + * ``` + * + * @returns A new {@code Expr} representing the absolute value of the numeric value. + */ + abs(): FunctionExpression; + + /** + * @beta + * Creates an expression that computes `e` (Euler's number) raised to the power of this expression's numeric value. + * + * @example + * ```typescript + * // Compute `e` to the power of the 'value' field. + * field("value").exp(); + * ``` + * + * @returns A new {@code FunctionExpression} representing `e` raised to the power of the numeric value. + */ + exp(): FunctionExpression; + /** + * @beta + * Creates an aggregation that counts the number of distinct values of the expression or field. + * + * @returns A new `AggregateFunction` representing the 'count_distinct' aggregation. + */ + countDistinct(): AggregateFunction; + /** + * @beta + * Accesses a value from a map (object) field using the provided key. + * + * @example + * ```typescript + * // Get the 'city' value from the 'address' map field + * field("address").mapGet("city"); + * ``` + * + * @param subfield The key to access in the map. + * @returns A new `Expression` representing the value associated with the given key in the map. + */ + mapGet(subfield: string): FunctionExpression; + /** + * @beta + * Creates an expression that returns a new map with the specified entries added or updated. + * + * @remarks + * Note that `mapSet` only performs shallow updates to the map. Setting a value to `null` + * will retain the key with a `null` value. To remove a key entirely, use `mapRemove`. + * + * @example + * ```typescript + * // Set the 'city' to "San Francisco" in the 'address' map + * field("address").mapSet("city", "San Francisco"); + * ``` + * + * @param key - The key to set. Must be a string or a constant string expression. + * @param value - The value to set. + * @param moreKeyValues - Additional key-value pairs to set. + * @returns A new `Expression` representing the map with the entries set. + */ + mapSet( + key: string | Expression, + value: unknown, + ...moreKeyValues: unknown[] + ): FunctionExpression; + /** + * @beta + * Creates an expression that returns the keys of a map. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the keys of the 'address' map + * field("address").mapKeys(); + * ``` + * + * @returns A new `Expression` representing the keys of the map. + */ + mapKeys(): FunctionExpression; + /** + * @beta + * Creates an expression that returns the values of a map. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the values of the 'address' map + * field("address").mapValues(); + * ``` + * + * @returns A new `Expression` representing the values of the map. + */ + mapValues(): FunctionExpression; + /** + * @beta + * Creates an expression that returns the entries of a map as an array of maps, + * where each map contains a `"k"` property for the key and a `"v"` property for the value. + * For example: `[{ k: "key1", v: "value1" }, ...]`. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the entries of the 'address' map + * field("address").mapEntries(); + * ``` + * + * @returns A new `Expression` representing the entries of the map. + */ + mapEntries(): FunctionExpression; + /** + * @beta + * Creates an aggregation that counts the number of stage inputs with valid evaluations of the + * expression or field. + * + * @example + * ```typescript + * // Count the total number of products + * field("productId").count().as("totalProducts"); + * ``` + * + * @returns A new `AggregateFunction` representing the 'count' aggregation. + */ + count(): AggregateFunction; + /** + * @beta + * Creates an aggregation that calculates the sum of a numeric field across multiple stage inputs. + * + * @example + * ```typescript + * // Calculate the total revenue from a set of orders + * field("orderAmount").sum().as("totalRevenue"); + * ``` + * + * @returns A new `AggregateFunction` representing the 'sum' aggregation. + */ + sum(): AggregateFunction; + /** + * @beta + * Creates an aggregation that calculates the average (mean) of a numeric field across multiple + * stage inputs. + * + * @example + * ```typescript + * // Calculate the average age of users + * field("age").average().as("averageAge"); + * ``` + * + * @returns A new `AggregateFunction` representing the 'average' aggregation. + */ + average(): AggregateFunction; + /** + * @beta + * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. + * + * @example + * ```typescript + * // Find the lowest price of all products + * field("price").minimum().as("lowestPrice"); + * ``` + * + * @returns A new `AggregateFunction` representing the 'min' aggregation. + */ + minimum(): AggregateFunction; + /** + * @beta + * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. + * + * @example + * ```typescript + * // Find the highest score in a leaderboard + * field("score").maximum().as("highestScore"); + * ``` + * + * @returns A new `AggregateFunction` representing the 'max' aggregation. + */ + maximum(): AggregateFunction; + /** + * @beta + * Creates an expression that returns the larger value between this expression and another expression, based on Firestore's value type ordering. + * + * @example + * ```typescript + * // Returns the larger value between the 'timestamp' field and the current timestamp. + * field("timestamp").logicalMaximum(Function.currentTimestamp()); + * ``` + * + * @param second The second expression or literal to compare with. + * @param others Optional additional expressions or literals to compare with. + * @returns A new {@code Expression} representing the logical max operation. + */ + logicalMaximum( + second: Expression | unknown, + ...others: Array + ): FunctionExpression; + /** + * @beta + * Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering. + * + * @example + * ```typescript + * // Returns the smaller value between the 'timestamp' field and the current timestamp. + * field("timestamp").logicalMinimum(Function.currentTimestamp()); + * ``` + * + * @param second The second expression or literal to compare with. + * @param others Optional additional expressions or literals to compare with. + * @returns A new {@code Expression} representing the logical min operation. + */ + logicalMinimum( + second: Expression | unknown, + ...others: Array + ): FunctionExpression; + /** + * @beta + * Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression. + * + * @example + * ```typescript + * // Get the vector length (dimension) of the field 'embedding'. + * field("embedding").vectorLength(); + * ``` + * + * @returns A new {@code Expression} representing the length of the vector. + */ + vectorLength(): FunctionExpression; + /** + * @beta + * Calculates the cosine distance between two vectors. + * + * @example + * ```typescript + * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field + * field("userVector").cosineDistance(field("itemVector")); + * ``` + * + * @param vectorExpression The other vector (represented as an Expression) to compare against. + * @returns A new `Expression` representing the cosine distance between the two vectors. + */ + cosineDistance(vectorExpression: Expression): FunctionExpression; + + /** + * @beta + * Calculates the Cosine distance between two vectors. + * + * @example + * ```typescript + * // Calculate the Cosine distance between the 'embedding' field and a target vector + * field("embedding").cosineDistance(FieldValue.vector([0.1, 0.2, 0.3])); + * + * // Calculate the Cosine distance using a plain number array + * field("embedding").cosineDistance([0.1, 0.2, 0.3]); + * ``` + * + * @param vector The other vector to compare against, provided as either a `VectorValue` object or a plain `number[]` array. + * @returns A new `FunctionExpression` representing the Cosine distance between the two vectors. + */ + cosineDistance(vector: VectorValue | number[]): FunctionExpression; + /** + * @beta + * Calculates the dot product between the current expression (representing a vector) + * and another expression (representing a second vector). + * + * Both expressions are expected to resolve to an array of numbers (a vector) at runtime. + * + * @example + * ```typescript + * // Calculate the dot product between the 'features' field and the 'targetVector' field. + * field("features").dotProduct(field("targetVector")); + * ``` + * + * @param vectorExpression An `Expression` representing the second vector. + * @returns A new {@link FunctionExpression} representing the dot product of the two vectors. + */ + dotProduct(vectorExpression: Expression): FunctionExpression; + + /** + * @beta + * Calculates the dot product between two vectors. + * + * @example + * ```typescript + * // Calculate the dot product between a feature vector and a target vector + * field("features").dotProduct(FieldValue.vector([0.5, 0.8, 0.2])); + * ``` + * + * @param vector The other vector to calculate the dot product with. This can be a `VectorValue` object or a plain array of numbers. + * @returns A new `Expression` representing the dot product between the two vectors. + */ + dotProduct(vector: VectorValue | number[]): FunctionExpression; + + /** + * @beta + * Calculates the Euclidean distance between the vector represented by this expression and another vector expression. + * + * @example + * ```typescript + * // Calculate the Euclidean distance between two different vector fields. + * field("vectorA").euclideanDistance(field("vectorB")); + * ``` + * + * @param vectorExpression An `Expression` that evaluates to the second vector (an array of numbers) for the distance calculation. + * @returns A new {@link FunctionExpression} representing the Euclidean distance between the two vectors. + */ + euclideanDistance(vectorExpression: Expression): FunctionExpression; + /** + * @beta + * Calculates the Euclidean distance between two vectors. + * + * The `vector` parameter can be either a `VectorValue` object or a `number[]` (array of numbers). + * + * @example + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location using a VectorValue. + * field("location").euclideanDistance(FieldValue.vector([37.7749, -122.4194])); + * + * // Calculate the Euclidean distance between the 'location' field and a target location using a number array. + * field("location").euclideanDistance([37.7749, -122.4194]); + * ``` + * + * @param vector The other vector (as a `VectorValue` or `number[]`) to compare against. + * @returns A new `Expression` representing the Euclidean distance between the two vectors. + */ + euclideanDistance(vector: VectorValue | number[]): FunctionExpression; + /** + * @beta + * Creates an expression that interprets this expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * @example + * ```typescript + * // Interpret the 'microseconds' field as microseconds since epoch. + * field("microseconds").unixMicrosToTimestamp(); + * ``` + * + * @returns A new {@code Expression} representing the timestamp. + */ + unixMicrosToTimestamp(): FunctionExpression; + /** + * @beta + * Creates an expression that converts this timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * @example + * ```typescript + * // Convert the 'timestamp' field to microseconds since epoch. + * field("timestamp").timestampToUnixMicros(); + * ``` + * + * @returns A new {@code Expression} representing the number of microseconds since epoch. + */ + timestampToUnixMicros(): FunctionExpression; + /** + * @beta + * Creates an expression that interprets this expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * @example + * ```typescript + * // Interpret the 'milliseconds' field as milliseconds since epoch. + * field("milliseconds").unixMillisToTimestamp(); + * ``` + * + * @returns A new {@code Expression} representing the timestamp. + */ + unixMillisToTimestamp(): FunctionExpression; + /** + * @beta + * Creates an expression that converts this timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * @example + * ```typescript + * // Convert the 'timestamp' field to milliseconds since epoch. + * field("timestamp").timestampToUnixMillis(); + * ``` + * + * @returns A new {@code Expression} representing the number of milliseconds since epoch. + */ + timestampToUnixMillis(): FunctionExpression; + /** + * @beta + * Creates an expression that interprets this expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * @example + * ```typescript + * // Interpret the 'seconds' field as seconds since epoch. + * field("seconds").unixSecondsToTimestamp(); + * ``` + * + * @returns A new {@code Expression} representing the timestamp. + */ + unixSecondsToTimestamp(): FunctionExpression; + /** + * @beta + * Creates an expression that converts this timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * @example + * ```typescript + * // Convert the 'timestamp' field to seconds since epoch. + * field("timestamp").timestampToUnixSeconds(); + * ``` + * + * @returns A new {@code Expression} representing the number of seconds since epoch. + */ + timestampToUnixSeconds(): FunctionExpression; + /** + * @beta + * Creates an expression that adds a specified amount of time to this timestamp expression. + * + * @example + * ```typescript + * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. + * field("timestamp").timestampAdd(field("unit"), field("amount")); + * ``` + * + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @returns A new {@code Expression} representing the resulting timestamp. + */ + timestampAdd(unit: Expression, amount: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that adds a specified amount of time to this timestamp expression. + * + * @example + * ```typescript + * // Add 1 day to the 'timestamp' field. + * field("timestamp").timestampAdd("day", 1); + * ``` + * + * @param unit The unit of time to add (e.g., "day", "hour"). + * @param amount The amount of time to add. + * @returns A new {@code Expression} representing the resulting timestamp. + */ + timestampAdd( + unit: + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: number, + ): FunctionExpression; + /** + * @beta + * Creates an expression that subtracts a specified amount of time from this timestamp expression. + * + * @example + * ```typescript + * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. + * field("timestamp").timestampSubtract(field("unit"), field("amount")); + * ``` + * + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @returns A new {@code Expression} representing the resulting timestamp. + */ + timestampSubtract( + unit: Expression, + amount: Expression, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that subtracts a specified amount of time from this timestamp expression. + * + * @example + * ```typescript + * // Subtract 1 day from the 'timestamp' field. + * field("timestamp").timestampSubtract("day", 1); + * ``` + * + * @param unit The unit of time to subtract. Supported units are 'microsecond', 'millisecond', 'second', 'minute', 'hour', and 'day'. + * @param amount The amount of time to subtract. + * @returns A new {@code FunctionExpression} representing the resulting timestamp after subtraction. + */ + timestampSubtract( + unit: + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: number, + ): FunctionExpression; + /** + * @beta + * Creates an expression that returns the document ID from a DocumentReference. + * + * @example + * ```typescript + * // Get the document ID for the current document. + * field("__name__").documentId(); + * ``` + * + * @returns A new {@code Expression} representing the documentId operation. + */ + documentId(): FunctionExpression; + /** + * @beta + * Creates an expression that returns a substring of the results of this expression. + * + * @param position Index of the first character of the substring. + * @param length Length of the substring. If not provided, the substring will + * end at the end of the input. + */ + substring(position: number, length?: number): FunctionExpression; + /** + * @beta + * Creates an expression that returns a substring of the results of this expression. + * + * @param position An expression returning the index of the first character of the substring. + * @param length An expression returning the length of the substring. If not provided the + * substring will end at the end of the input. + */ + substring(position: Expression, length?: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and returns the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. + * + * @example + * ```typescript + * // Return the value in the 'tags' field array at index `1`. + * field('tags').arrayGet(1); + * ``` + * + * @param index The index of the element to return. + * @returns A new Expression representing the 'arrayGet' operation. + */ + arrayGet(index: number): FunctionExpression; + /** + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and returns the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. + * + * @example + * ```typescript + * // Return the value in the tags field array at index specified by field + * // 'favoriteTag'. + * field('tags').arrayGet(field('favoriteTag')); + * ``` + * + * @param indexExpr An Expression evaluating to the index of the element to return. + * @returns A new Expression representing the 'arrayGet' operation. + */ + arrayGet(indexExpr: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that checks if a given expression produces an error. + * + * @example + * ```typescript + * // Check if the result of a calculation is an error + * field("title").arrayContains(1).isError(); + * ``` + * + * @returns A new {@code BooleanExpression} representing the 'isError' check. + */ + isError(): BooleanExpression; + /** + * @beta + * Creates an expression that returns the result of the `catchExpr` argument + * if there is an error, else return the result of this expression. + * + * @example + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // the entire title field if the array is empty or the field is another type. + * field("title").arrayGet(0).ifError(field("title")); + * ``` + * + * @param catchExpr The catch expression that will be evaluated and + * returned if this expression produces an error. + * @returns A new {@code Expression} representing the 'ifError' operation. + */ + ifError(catchExpr: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * @example + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // "Default Title" + * field("title").arrayGet(0).ifError("Default Title"); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @returns A new {@code Expression} representing the 'ifError' operation. + */ + ifError(catchValue: unknown): FunctionExpression; + /** + * @beta + * Creates an expression that returns `true` if the result of this expression + * is absent. Otherwise, returns `false` even if the value is `null`. + * + * @example + * ```typescript + * // Check if the field `value` is absent. + * field("value").isAbsent(); + * ``` + * + * @returns A new {@code BooleanExpression} representing the 'isAbsent' check. + */ + isAbsent(): BooleanExpression; + + /** + * @beta + * Creates an expression that removes a key from the map produced by evaluating this expression. + * + * @example + * ```typescript + * // Removes the key 'baz' from the input map. + * map({foo: 'bar', baz: true}).mapRemove('baz'); + * ``` + * + * @param key The name of the key to remove from the input map. + * @returns A new {@code FunctionExpression} representing the 'mapRemove' operation. + */ + mapRemove(key: string): FunctionExpression; + + /** + * @beta + * Creates an expression that removes a key from the map produced by evaluating this expression. + * + * @example + * ```typescript + * // Removes the key 'baz' from the input map. + * map({foo: 'bar', baz: true}).mapRemove(constant('baz')); + * ``` + * + * @param keyExpr An expression that produces the name of the key to remove from the input map. + * @returns A new {@code FunctionExpression} representing the 'mapRemove' operation. + */ + mapRemove(keyExpr: Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that merges multiple map values. + * + * The first map in the merge operation is the expression on which `mapMerge` is called. + * + * @example + * ```typescript + * // Merges the map in the 'settings' field with a literal map and a map + * // conditionally returned by another expression. + * field('settings').mapMerge({ enabled: true }, conditional(field('isAdmin'), { admin: true }, {})) + * ``` + * + * @param secondMap A required second map to merge. This can be a literal object + * or an expression that evaluates to a map. + * @param otherMaps Optional additional maps to merge. Each can be a literal + * object or an expression that evaluates to a map. + * + * @returns A new {@code FunctionExpression} representing the result of the map merge operation. + */ + mapMerge( + secondMap: Record | Expression, + ...otherMaps: Array | Expression> + ): FunctionExpression; + /** + * @beta + * Creates an expression that returns the value of this expression raised to the power of another expression. + * + * @example + * ```typescript + * // Raise the value of the 'base' field to the power of the 'exponent' field. + * field("base").pow(field("exponent")); + * ``` + * + * @param exponent The expression to raise this expression to the power of. + * @returns A new `Expression` representing the power operation. + */ + pow(exponent: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that returns the value of this expression raised to the power of a constant value. + * + * @example + * ```typescript + * // Raise the value of the 'base' field to the power of 2. + * field("base").pow(2); + * ``` + * + * @param exponent The constant value to raise this expression to the power of. + * @returns A new `Expression` representing the power operation. + */ + pow(exponent: number): FunctionExpression; + /** + * @beta + * Creates an expression that truncates the numeric value to an integer. + * + * @example + * ```typescript + * // Truncate the 'rating' field. + * field("rating").trunc(); + * ``` + * + * @returns A new `Expression` representing the truncated value. + */ + trunc(): FunctionExpression; + /** + * @beta + * Creates an expression that truncates a numeric value to the specified number of decimal places. + * + * @example + * ```typescript + * // Truncate the value of the 'rating' field to two decimal places. + * field("rating").trunc(2); + * ``` + * + * @param decimalPlaces A constant specifying the truncation precision in decimal places. + * @returns A new `Expression` representing the truncated value. + */ + trunc(decimalPlaces: number): FunctionExpression; + /** + * @beta + * Creates an expression that truncates a numeric value to the specified number of decimal places. + * + * @example + * ```typescript + * // Truncate the value of the 'rating' field to two decimal places. + * field("rating").trunc(constant(2)); + * ``` + * + * @param decimalPlaces An expression specifying the truncation precision in decimal places. + * @returns A new `Expression` representing the truncated value. + */ + trunc(decimalPlaces: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that rounds a numeric value to the nearest whole number. + * + * @example + * ```typescript + * // Round the value of the 'price' field. + * field("price").round(); + * ``` + * + * @returns A new `Expression` representing the rounded value. + */ + round(): FunctionExpression; + /** + * @beta + * Creates an expression that rounds a numeric value to the nearest whole number. + * + * @example + * ```typescript + * // Round the value of the 'price' field. + * field("price").round(); + * ``` + * + * @returns A new `Expression` representing the rounded value. + */ + round(): FunctionExpression; + /** + * @beta + * Creates an expression that rounds a numeric value to the specified number of decimal places. + * + * @example + * ```typescript + * // Round the value of the 'price' field to two decimal places. + * field("price").round(2); + * ``` + * + * @param decimalPlaces A constant specifying the rounding precision in decimal places. + * + * @returns A new `Expr` representing the rounded value. + */ + round(decimalPlaces: number): FunctionExpression; + /** + * @beta + * Creates an expression that rounds a numeric value to the specified number of decimal places. + * + * @example + * ```typescript + * // Round the value of the 'price' field to two decimal places. + * field("price").round(constant(2)); + * ``` + * + * @param decimalPlaces An expression specifying the rounding precision in decimal places. + * + * @returns A new `Expr` representing the rounded value. + */ + round(decimalPlaces: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that returns the collection ID from a path. + * + * @example + * ```typescript + * // Get the collection ID from a path. + * field("__name__").collectionId(); + * ``` + * + * @returns A new {@code Expression} representing the collectionId operation. + */ + collectionId(): FunctionExpression; + /** + * @beta + * Creates an expression that calculates the length of a string, array, map, vector, or bytes. + * + * @example + * ```typescript + * // Get the length of the 'name' field. + * field("name").length(); + * + * // Get the number of items in the 'cart' array. + * field("cart").length(); + * ``` + * + * @returns A new `Expression` representing the length of the string, array, map, vector, or bytes. + */ + length(): FunctionExpression; + /** + * @beta + * Creates an expression that computes the natural logarithm of a numeric value. + * + * @example + * ```typescript + * // Compute the natural logarithm of the 'value' field. + * field("value").ln(); + * ``` + * + * @returns A new {@code Expression} representing the natural logarithm of the numeric value. + */ + ln(): FunctionExpression; + /** + * @beta + * Creates an expression that computes the square root of a numeric value. + * + * @example + * ```typescript + * // Compute the square root of the 'value' field. + * field("value").sqrt(); + * ``` + * + * @returns A new {@code Expression} representing the square root of the numeric value. + */ + sqrt(): FunctionExpression; + /** + * @beta + * Creates an expression that reverses a string. + * + * @example + * ```typescript + * // Reverse the value of the 'myString' field. + * field("myString").stringReverse(); + * ``` + * + * @returns A new {@code Expression} representing the reversed string. + */ + stringReverse(): FunctionExpression; + + /** + * @beta + * Creates an expression that returns the `elseValue` argument if this expression results in an absent value, else + * return the result of the this expression evaluation. + * + * @example + * ```typescript + * // Returns the value of the optional field 'optional_field', or returns 'default_value' + * // if the field is absent. + * field("optional_field").ifAbsent("default_value") + * ``` + * + * @param elseValue The value that will be returned if this Expression evaluates to an absent value. + * @returns A new [Expression] representing the ifAbsent operation. + */ + ifAbsent(elseValue: unknown): Expression; + + /** + * @beta + * Creates an expression that returns the `elseValue` argument if this expression results in an absent value, else + * return the result of this expression evaluation. + * + * @example + * ```typescript + * // Returns the value of the optional field 'optional_field', or if that is + * // absent, then returns the value of the field ` + * field("optional_field").ifAbsent(field('default_field')) + * ``` + * + * @param elseExpression The Expression that will be evaluated if this Expression evaluates to an absent value. + * @returns A new [Expression] representing the ifAbsent operation. + */ + ifAbsent(elseExpression: unknown): Expression; + + ifAbsent(elseValueOrExpression: Expression | unknown): Expression; + + /** + * @beta + * Creates an expression that joins the elements of an array into a string. + * + * @example + * ```typescript + * // Join the elements of the 'tags' field with the delimiter from the 'separator' field. + * field("tags").join(field("separator")) + * ``` + * + * @param delimiterExpression The expression that evaluates to the delimiter string. + * @returns A new Expression representing the join operation. + */ + join(delimiterExpression: Expression): Expression; + + /** + * @beta + * Creates an expression that joins the elements of an array field into a string. + * + * @example + * ```typescript + * // Join the elements of the 'tags' field with a comma and space. + * field("tags").join(", ") + * ``` + * + * @param delimiter The string to use as a delimiter. + * @returns A new Expression representing the join operation. + */ + join(delimiter: string): Expression; + + join(delimeterValueOrExpression: string | Expression): Expression; + + /** + * @beta + * Creates an expression that computes the base-10 logarithm of a numeric value. + * + * @example + * ```typescript + * // Compute the base-10 logarithm of the 'value' field. + * field("value").log10(); + * ``` + * + * @returns A new {@code Expr} representing the base-10 logarithm of the numeric value. + */ + log10(): FunctionExpression; + + /** + * @beta + * Creates an expression that computes the sum of the elements in an array. + * + * @example + * ```typescript + * // Compute the sum of the elements in the 'scores' field. + * field("scores").arraySum(); + * ``` + * + * @returns A new {@code Expr} representing the sum of the elements in the array. + */ + arraySum(): FunctionExpression; + /** + * @beta + * Creates an expression that splits the result of this expression into an + * array of substrings based on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scoresCsv' field on delimiter ',' + * field('scoresCsv').split(',') + * ``` + * + * @returns A new {@code Expression} representing the split function. + */ + split(delimiter: string): FunctionExpression; + + /** + * @beta + * Creates an expression that splits the result of this expression into an + * array of substrings based on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format + * field('scores').split(conditional(field('format').equal('csv'), constant(','), constant(':')) + * ``` + * + * @returns A new {@code Expression} representing the split function. + */ + split(delimiter: Expression): FunctionExpression; + /** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the beginning of the day. + * field('createdAt').timestampTruncate('day') + * ``` + * + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @returns A new {Expression} representing the truncated timestamp. + */ + timestampTruncate( + granularity: TimeGranularity, + timezone?: string | Expression, + ): FunctionExpression; + + /** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'. + * field('createdAt').timestampTruncate(field('granularity')) + * ``` + * + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @returns A new {Expression} representing the truncated timestamp. + */ + timestampTruncate( + granularity: Expression, + timezone?: string | Expression, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that returns the data type of this expression's result, as a string. + * + * @example + * ```typescript + * // Get the data type of the value in field 'title' + * field('title').type() + * ``` + * + * @returns A new {Expression} representing the data type. + */ + type(): FunctionExpression; + + /** + * @beta + * Creates an expression that checks if the result of this expression is of the given type. + * + * @remarks Null or undefined fields evaluate to skip/error. Use `ifAbsent()` / `isAbsent()` to evaluate missing data. + * + * @example + * ```typescript + * // Check if the 'price' field is specifically an integer (not just 'number') + * field('price').isType('int64'); + * ``` + * + * @param type The type to check for. + * @returns A new `BooleanExpression` that evaluates to true if the expression's result is of the given type, false otherwise. + */ + isType(type: Type): BooleanExpression; + + // TODO(new-expression): Add new expression method declarations above this line + /** + * @beta + * Creates an `Ordering` that sorts documents in ascending order based on this expression. + * + * @example + * ```typescript + * // Sort documents by the 'name' field in ascending order + * pipeline().collection("users") + * .sort(field("name").ascending()); + * ``` + * + * @returns A new `Ordering` for ascending sorting. + */ + ascending(): Ordering; + /** + * @beta + * Creates an `Ordering` that sorts documents in descending order based on this expression. + * + * @example + * ```typescript + * // Sort documents by the 'createdAt' field in descending order + * pipeline().collection("users") + * .sort(field("createdAt").descending()); + * ``` + * + * @returns A new `Ordering` for descending sorting. + */ + descending(): Ordering; + /** + * @beta + * Assigns an alias to this expression. + * + * Aliases are useful for renaming fields in the output of a stage or for giving meaningful + * names to calculated values. + * + * @example + * ```typescript + * // Calculate the total price and assign it the alias "totalPrice" and add it to the output. + * pipeline().collection("items") + * .addFields(field("price").multiply(field("quantity")).as("totalPrice")); + * ``` + * + * @param name The alias to assign to this expression. + * @returns A new `AliasedExpression` that wraps this + * expression and associates it with the provided alias. + */ + as(name: string): AliasedExpression; + } + + /** + * @beta + * Time granularity used for timestamp functions. + */ + export type TimeGranularity = + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day' + | 'week' + | 'week(monday)' + | 'week(tuesday)' + | 'week(wednesday)' + | 'week(thursday)' + | 'week(friday)' + | 'week(saturday)' + | 'week(sunday)' + | 'isoWeek' + | 'month' + | 'quarter' + | 'year' + | 'isoYear'; + + /** + * @beta + * An interface that represents a selectable expression. + */ + export interface Selectable { + selectable: true; + /** + * @beta + * @internal + */ + readonly _alias: string; + /** + * @beta + * @internal + */ + readonly _expr: Expression; + } + + /** + * @beta + * Represents an aggregate function used within Firestore pipelines. + * Aggregate functions perform a calculation across a set of documents and return a single result, + * such as counting documents, summing numeric fields, or finding minimum/maximum values. + */ + export class AggregateFunction { + /** + * @beta + * @property expressionType The type of the aggregate expression, indicating the specific aggregate function (e.g., COUNT, SUM, AVG). + */ + expressionType: ExpressionType; + + /** + * @beta + * @private + * @internal + * @param name + * @param params + */ + constructor(name: string, params: Expression[]); + /** + * @beta + * Assigns an alias to this AggregateFunction. The alias specifies the name that + * the aggregated value will have in the output document. + * + * @example + * ```typescript + * // Calculate the average price of all items and assign it the alias "averagePrice". + * pipeline().collection("items") + * .aggregate(field("price").average().as("averagePrice")); + * ``` + * + * @param name The alias to assign to this AggregateFunction. + * @returns A new `AliasedAggregate` that wraps this + * AggregateFunction and associates it with the provided alias. + */ + as(name: string): AliasedAggregate; + } + + /** + * @beta + * Represents an `AggregateFunction` that has been assigned an alias. + * This class is used to associate an aggregate result with a name. + */ + export class AliasedAggregate { + /** + * @beta + * The underlying `AggregateFunction` that this aliased aggregate wraps. + * @internal + */ + readonly _aggregate: AggregateFunction; + + /** + * @beta + * Specifies the name of the property that will contain the aggregate result in the output document. + * @internal + */ + readonly _alias: string; + } + + /** + * @beta + * Represents an expression that has been assigned an alias using the `.as()` method. + * + * This class wraps an existing `Expression` and associates it with a user-defined alias, + * allowing the expression's result to be referred to by name in the output + * of a Firestore pipeline query. + */ + export class AliasedExpression implements Selectable { + /** + * @beta + * @internal + * Specifies that the instance is an AliasedExpression. + */ + expressionType: ExpressionType; + + /** + * @beta + * Specifies that this class is selectable, meaning it contains an `Expression` and an alias, + * and can be provided to the Select stage of a pipeline. + */ + selectable: true; + + /** + * @beta + * @internal + * The underlying expression that is being aliased. + */ + readonly _expr: Expression; + + /** + * @beta + * @internal + * Specifies the name of the property that will contain the aggregate result in the output document. + */ + readonly _alias: string; + } + + /** + * @beta + * Represents a reference to a field within a Firestore document or an output from a `Pipeline` stage. + * + * This class extends `Expression`. It is a type of expression that can be evaluated + * within Firestore Pipelines. It also implements `Selectable`, + * meaning instances of `Field` can be used to specify fields for selection in the {@link Pipeline.select} stage. + * + * `Field` instances are fundamental for constructing expressions that access document field values, + * and for defining criteria for sorting, filtering, and projecting data in Firestore Pipelines. + */ + export class Field extends Expression implements Selectable { + /** + * @beta + * @internal Specifies that the instance is a Field. + */ + readonly expressionType: ExpressionType; + /** + * @beta + * Specifies that this class is selectable, meaning it contains an `Expression` and an alias, + * and can be provided to the Select stage of a pipeline. + */ + selectable: true; + /** + * @beta + * Returns the name of the field. + * + * @example + * ```typescript + * const name = field("price").fieldName; + * console.log(name); // "price" + * ``` + * + * @returns The name of the field. + */ + get fieldName(): string; + /** + * @beta + * @internal + * Returns the alias of the field, which is the field-name itself. + * + * @returns The field name itself. + */ + get _alias(): string; + /** + * @beta + * @internal + * Self-referential getter that returns this. + * + * @returns This `Field` object. + */ + get _expr(): Expression; + } + /** + * @beta + * Creates a {@code Field} instance representing the field at the given path. + * + * The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field + * (e.g., "address.city"). + * + * @example + * ```typescript + * // Create a Field instance for the 'title' field + * const titleField = field("title"); + * + * // Create a Field instance for a nested field 'author.firstName' + * const authorFirstNameField = field("author.firstName"); + * ``` + * + * @param name The path to the field. + * @returns A new {@code Field} instance representing the specified field. + */ + export function field(name: string): Field; + /** + * @beta + * Creates a new Field instance from a given FieldPath. + * + * @param path The FieldPath to convert into a Field. + * @returns A new `Field` instance representing the specified path. + */ + export function field(path: FieldPath): Field; + + /** + * @beta + * @internal + * Represents a constant value that can be used as part of a Firestore pipeline expression. + * + * Instances of `Constant` are typically created via the top-level `constant()` function. + * + * @example + * ```typescript + * // Create a Constant instance for the number 10 + * const ten = constant(10); + * + * // Create a Constant instance for the string "hello" + * const hello = constant("hello"); + * ``` + */ + export class Constant extends Expression { + readonly expressionType: ExpressionType; + } + /** + * @beta + * Creates an `Expression` instance for a number value. + * + * @param value The number value. + * @returns A new `Expression` instance. + */ + export function constant(value: number): Expression; + /** + * @beta + * Creates an `Expression` instance for a string value. + * + * @param value The string value. + * @returns A new `Expression` instance. + */ + export function constant(value: string): Expression; + /** + * @beta + * Creates an `Expression` instance for a boolean value. + * + * @param value The boolean value. + * @returns A new `Expression` instance. + */ + export function constant(value: boolean): BooleanExpression; + /** + * @beta + * Creates an `Expression` instance for a null value. + * + * @param value The null value. + * @returns A new `Expression` instance. + */ + export function constant(value: null): Expression; + /** + * @beta + * Creates an `Expression` instance for a GeoPoint value. + * + * @param value The GeoPoint value. + * @returns A new `Expression` instance. + */ + export function constant(value: GeoPoint): Expression; + /** + * @beta + * Creates an `Expression` instance for a Timestamp value. + * + * @param value The Timestamp value. + * @returns A new `Expression` instance. + */ + export function constant(value: Timestamp): Expression; + /** + * @beta + * Creates an `Expression` instance for a Date value. + * + * @param value The Date value. + * @returns A new `Expression` instance. + */ + export function constant(value: Date): Expression; + /** + * @beta + * Creates an `Expression` instance for a Buffer | Uint8Array value. + * + * @param value The Buffer | Uint8Array value. + * @returns A new `Expression` instance. + */ + export function constant(value: Buffer | Uint8Array): Expression; + /** + * @beta + * Creates an `Expression` instance for a DocumentReference value. + * + * @param value The DocumentReference value. + * @returns A new `Expression` instance. + */ + export function constant(value: DocumentReference): Expression; + /** + * @beta + * Creates an `Expression` instance for a VectorValue value. + * + * @param value The VectorValue value. + * @returns A new `Expression` instance. + */ + export function constant(value: VectorValue): Expression; + + /** + * @beta + * Represents an expression that encapsulates a function call within the Firestore Pipelines. + * + * `FunctionExpression` extends `Expression` and is used to build complex queries and transformations + * by applying various functions (e.g., `and`, `equal`, `ceil`) to fields or other expressions. + * + * You typically do not instantiate `FunctionExpression` directly. Instead, use the provided + * top-level functions (like `and`, `equal`, {@link ceil}) or methods available + * on `Expression` instances (e.g., {@link Expression#equal}, {@link Expression#lessThan}) to construct + * `FunctionExpression` instances. + * + * @example + * ```typescript + * // Example of creating a FunctionExpression indirectly using helper functions: + * const priceGreaterThan10 = field("price").greaterThan(10); + * const combinedCondition = and(priceGreaterThan10, field("category").equal("books")); + * + * // 'priceGreaterThan10' and 'combinedCondition' are instances of FunctionExpression. + * ``` + */ + export class FunctionExpression extends Expression { + /** + * @beta + * @internal + * Indicates that this expression is a `FunctionExpression`. + */ + readonly expressionType: ExpressionType; + /** + * @beta + * @private + * @internal + * + * Initializes a new `FunctionExpression` instance with the given function name and parameters. + * + * @param name The name of the function. + * @param params An array of `Expression` instances representing the parameters of the function. + */ + constructor(name: string, params: Expression[]); + } + /** + * @beta + * An expression that evaluates to a boolean value. + * + * This expression type is useful for filter conditions. + * + */ + export abstract class BooleanExpression extends Expression { + /** + * @beta + * Creates an aggregation that finds the count of input documents satisfying + * this boolean expression. + * + * @example + * ```typescript + * // Find the count of documents with a score greater than 90 + * field("score").greaterThan(90).countIf().as("highestScore"); + * ``` + * + * @returns A new `AggregateFunction` representing the 'countIf' aggregation. + */ + countIf(): AggregateFunction; + + /** + * @beta + * Creates an expression that negates this boolean expression. + * + * @example + * ```typescript + * // Find documents where the 'tags' field does not contain 'completed' + * field("tags").arrayContains("completed").not(); + * ``` + * + * @returns A new {@code Expression} representing the negated filter condition. + */ + not(): BooleanExpression; + + /** + * @beta + * Creates a conditional expression that evaluates to the 'then' expression + * if `this` expression evaluates to `true`, + * or evaluates to the 'else' expression if `this` expressions evaluates `false`. + * + * @example + * ```typescript + * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". + * field("age").greaterThanOrEqual(18).conditional(constant("Adult"), constant("Minor")); + * ``` + * + * @param thenExpr The expression to evaluate if the condition is true. + * @param elseExpr The expression to evaluate if the condition is false. + * @returns A new {@code Expr} representing the conditional expression. + */ + conditional( + thenExpr: Expression, + elseExpr: Expression, + ): FunctionExpression; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * @example + * ```typescript + * // Create an expression that protects against a divide by zero error + * // but always returns a boolean expression. + * constant(50).divide('length').gt(1).ifError(constant(false)); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @returns A new {@code Expr} representing the 'ifError' operation. + */ + ifError(catchValue: BooleanExpression): BooleanExpression; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * @example + * ```typescript + * // Create an expression that protects against a divide by zero error + * // but always returns a boolean expression. + * constant(50).divide('length').gt(1).ifError(false); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @returns A new {@code Expr} representing the 'ifError' operation. + */ + ifError(catchValue: boolean): BooleanExpression; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * @example + * ```typescript + * // Create an expression that protects against a divide by zero error. + * constant(50).divide('length').gt(1).ifError(constant(0)); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @returns A new {@code Expr} representing the 'ifError' operation. + */ + ifError(catchValue: Expression): FunctionExpression; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * @example + * ```typescript + * // Create an expression that protects against a divide by zero error. + * constant(50).divide('length').gt(1).ifError(0); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @returns A new {@code Expr} representing the 'ifError' operation. + */ + ifError(catchValue: unknown): FunctionExpression; + } + /** + * @beta + * Creates an aggregation that counts the number of stage inputs where the provided + * boolean expression evaluates to true. + * + * @example + * ```typescript + * // Count the number of documents where 'is_active' field equals true + * countIf(field("is_active").equal(true)).as("numActiveDocuments"); + * ``` + * + * @param booleanExpr - The boolean expression to evaluate on each input. + * @returns A new `AggregateFunction` representing the 'countIf' aggregation. + */ + export function countIf(booleanExpr: BooleanExpression): AggregateFunction; + /** + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. + * + * @example + * ```typescript + * // Return the value in the tags field array at index 1. + * arrayGet('tags', 1); + * ``` + * + * @param arrayField The name of the array field. + * @param index The index of the element to return. + * @returns A new Expression representing the 'arrayGet' operation. + */ + export function arrayGet( + arrayField: string, + index: number, + ): FunctionExpression; + /** + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. + * + * @example + * ```typescript + * // Return the value in the tags field array at index specified by field + * // 'favoriteTag'. + * arrayGet('tags', field('favoriteTag')); + * ``` + * + * @param arrayField The name of the array field. + * @param indexExpr An Expression evaluating to the index of the element to return. + * @returns A new Expression representing the 'arrayGet' operation. + */ + export function arrayGet( + arrayField: string, + indexExpr: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. + * + * @example + * ```typescript + * // Return the value in the tags field array at index 1. + * arrayGet(field('tags'), 1); + * ``` + * + * @param arrayExpression An Expression evaluating to an array. + * @param index The index of the element to return. + * @returns A new Expression representing the 'arrayGet' operation. + */ + export function arrayGet( + arrayExpression: Expression, + index: number, + ): FunctionExpression; + /** + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. + * + * @example + * ```typescript + * // Return the value in the tags field array at index specified by field + * // 'favoriteTag'. + * arrayGet(field('tags'), field('favoriteTag')); + * ``` + * + * @param arrayExpression An Expression evaluating to an array. + * @param indexExpr An Expression evaluating to the index of the element to return. + * @returns A new Expression representing the 'arrayGet' operation. + */ + export function arrayGet( + arrayExpression: Expression, + indexExpr: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that checks if a given expression produces an error. + * + * @example + * ```typescript + * // Check if the result of a calculation is an error + * isError(field("title").arrayContains(1)); + * ``` + * + * @param value The expression to check. + * @returns A new {@code BooleanExpression} representing the 'isError' check. + */ + export function isError(value: Expression): BooleanExpression; + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of the `try` argument evaluation. + * + * This overload is useful when a BooleanExpression is required. + * + * @example + * ```typescript + * // Create an expression that protects against a divide by zero error + * // but always returns a boolean expression. + * ifError(constant(50).divide('length').gt(1), constant(false)); + * ``` + * + * @param tryExpr The try expression. + * @param catchExpr The catch expression that will be evaluated and + * returned if the tryExpr produces an error. + * @returns A new {@code BooleanExpression} representing the 'ifError' operation. + */ + export function ifError( + tryExpr: BooleanExpression, + catchExpr: BooleanExpression, + ): BooleanExpression; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of the `try` argument evaluation. + * + * @example + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // the entire title field if the array is empty or the field is another type. + * ifError(field("title").arrayGet(0), field("title")); + * ``` + * + * @param tryExpr The try expression. + * @param catchExpr The catch expression that will be evaluated and + * returned if the tryExpr produces an error. + * @returns A new {@code Expression} representing the 'ifError' operation. + */ + export function ifError( + tryExpr: Expression, + catchExpr: Expression, + ): FunctionExpression; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of the `try` argument evaluation. + * + * @example + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // "Default Title" + * ifError(field("title").arrayGet(0), "Default Title"); + * ``` + * + * @param tryExpr The try expression. + * @param catchValue The value that will be returned if the tryExpr produces an + * error. + * @returns A new {@code Expression} representing the 'ifError' operation. + */ + export function ifError( + tryExpr: Expression, + catchValue: unknown, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that returns `true` if a value is absent. Otherwise, + * returns `false` even if the value is `null`. + * + * @example + * ```typescript + * // Check if the field `value` is absent. + * isAbsent(field("value")); + * ``` + * + * @param value The expression to check. + * @returns A new {@code Expression} representing the 'isAbsent' check. + */ + export function isAbsent(value: Expression): BooleanExpression; + /** + * @beta + * Creates an expression that returns `true` if a field is absent. Otherwise, + * returns `false` even if the field value is `null`. + * + * @example + * ```typescript + * // Check if the field `value` is absent. + * isAbsent("value"); + * ``` + * + * @param field The field to check. + * @returns A new {@code Expression} representing the 'isAbsent' check. + */ + export function isAbsent(field: string): BooleanExpression; + + /** + * @beta + * Creates an expression that removes a key from the map at the specified field name. + * + * ``` + * // Removes the key 'city' field from the map in the address field of the input document. + * mapRemove('address', 'city'); + * ``` + * + * @param mapField The name of a field containing a map value. + * @param key The name of the key to remove from the input map. + */ + export function mapRemove( + mapField: string, + key: string, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that removes a key from the map produced by evaluating another expression. + * + * @example + * ```typescript + * // Removes the key 'baz' from the input map. + * mapRemove(map({foo: 'bar', baz: true}), 'baz'); + * ``` + * + * @param mapExpr An expression that evaluates to a map value. + * @param key The name of the key to remove from the input map. + * @returns A new {@link FunctionExpression} representing the map with the specified key removed. + */ + export function mapRemove( + mapExpr: Expression, + key: string, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that removes a key from the map at the specified field name. + * + * @example + * ```typescript + * // Removes the key 'city' field from the map in the address field of the input document. + * mapRemove('address', constant('city')); + * ``` + * + * @param mapField The name of a field containing a map value. + * @param keyExpr An expression that produces the name of the key to remove from the input map. + * @returns A new {@code FunctionExpression} representing the map after the key has been removed. + */ + export function mapRemove( + mapField: string, + keyExpr: Expression, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that removes a key from a map. + * + * The `mapRemove` function takes two expressions: + * 1. An expression that evaluates to a map. + * 2. An expression that evaluates to the string key to be removed from the map. + * + * @example + * ```typescript + * // Removes the key 'baz' from the input map. + * mapRemove(map({foo: 'bar', baz: true}), constant('baz')); + * ``` + * + * @param mapExpr An expression that evaluates to a map value. + * @param keyExpr An expression that evaluates to the string key to remove from the map. + * @returns A new {@link FunctionExpression} representing the map with the specified key removed. + */ + export function mapRemove( + mapExpr: Expression, + keyExpr: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that merges multiple map values. + * + * ``` + * // Merges the map in the settings field with, a map literal, and a map in + * // that is conditionally returned by another expression + * mapMerge('settings', { enabled: true }, conditional(field('isAdmin'), { admin: true}, {}) + * ``` + * + * @param mapField Name of a field containing a map value that will be merged. + * @param secondMap A required second map to merge. Represented as a literal or + * an expression that returns a map. + * @param otherMaps Optional additional maps to merge. Each map is represented + * as a literal or an expression that returns a map. + */ + export function mapMerge( + mapField: string, + secondMap: Record | Expression, + ...otherMaps: Array | Expression> + ): FunctionExpression; + /** + * @beta + * Creates an expression that merges multiple map values. + * + * ``` + * // Merges the map in the settings field with, a map literal, and a map in + * // that is conditionally returned by another expression + * mapMerge(field('settings'), { enabled: true }, conditional(field('isAdmin'), { admin: true}, {}) + * ``` + * + * @param firstMap An expression or literal map value that will be merged. + * @param secondMap A required second map to merge. Represented as a literal or + * an expression that returns a map. + * @param otherMaps Optional additional maps to merge. Each map is represented + * as a literal or an expression that returns a map. + */ + export function mapMerge( + firstMap: Record | Expression, + secondMap: Record | Expression, + ...otherMaps: Array | Expression> + ): FunctionExpression; + + /** + * @beta + * Creates an expression that extracts the document ID from a document reference. + * + * @example + * ```typescript + * // Get the document ID from a document reference. + * documentId(field("__name__")); + * ``` + * + * @param documentPathExpr An expression evaluating to a document path. + * @returns A new {@code FunctionExpression} representing the document ID as a string. + */ + export function documentId( + documentPathExpr: Expression, + ): FunctionExpression; + + /** + * @beta + * + * Creates an expression that returns the document ID from a path. + * + * @example + * ```typescript + * // Get the document ID from a path. + * documentId(myDocumentReference); + * ``` + * + * @returns A new {@code Expr} representing the documentId operation. + */ + export function documentId( + documentPath: string | DocumentReference, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that returns the document ID from a path. + * + * @example + * ```typescript + * // Get the document ID from a path. + * documentId(field("__path__")); + * ``` + * + * @returns A new {@code Expression} representing the documentId operation. + */ + export function documentId( + documentPathExpr: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that returns a substring of a string or byte array. + * + * @param field The name of a field containing a string or byte array to compute the substring from. + * @param position Index of the first character of the substring. + * @param length Length of the substring. + */ + export function substring( + field: string, + position: number, + length?: number, + ): FunctionExpression; + /** + * @beta + * Creates an expression that returns a substring of a string or byte array. + * + * @param input An expression returning a string or byte array to compute the substring from. + * @param position Index of the first character of the substring. + * @param length Length of the substring. + */ + export function substring( + input: Expression, + position: number, + length?: number, + ): FunctionExpression; + /** + * @beta + * Creates an expression that returns a substring of a string or byte array. + * + * @param field The name of a field containing a string or byte array to compute the substring from. + * @param position An expression that returns the index of the first character of the substring. + * @param length An expression that returns the length of the substring. + */ + export function substring( + field: string, + position: Expression, + length?: Expression, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that returns a substring of a string or byte array. + * + * @example + * ```typescript + * // Get a substring of the 'myString' field from index 0 with length 5. + * substring(field("myString"), 0, 5); + * ``` + * + * @param input An expression returning a string or byte array from which to extract the substring. + * @param position An expression that returns the 0-based starting index of the substring. + * @param length Optional. An expression that returns the length of the substring. If omitted, the substring extends to the end of the input. + * @returns A new {@code FunctionExpression} representing the substring operation. + */ + export function substring( + input: Expression, + position: Expression, + length?: Expression, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that performs an addition operation on two or more numeric expressions or literal values. + * + * This function supports adding multiple values. For example, `add(a, b, c)` is equivalent to `add(add(a, b), c)`. + * + * @example + * ```typescript + * // Add the value of the 'quantity' field and the 'reserve' field. + * add(field("quantity"), field("reserve")); + * + * // Add three values: a field, a literal number, and another field. + * add(field("price"), 10, field("tax")); + * ``` + * + * @param first The initial numeric expression or literal value. + * @param second The second numeric expression or literal value to add. + * @param others Optional: Additional numeric expressions or literal values to add. + * @returns A new {@code FunctionExpression} representing the sum of all provided arguments. + */ + export function add( + first: Expression, + second: Expression | unknown, + ...others: Array + ): FunctionExpression; + + /** + * @beta + * Creates an expression that computes the sum of a field's value and one or more other expressions or literals. + * + * @example + * ```typescript + * // Add the value of the 'quantity' field to the value of the 'reserve' field. + * add("quantity", field("reserve")); + * + * // Add the value of the 'price' field to a literal number. + * add("price", 10); + * + * // Add the value of the 'total' field to the values of 'tax' and 'shipping' fields. + * add("total", field("tax"), field("shipping")); + * ``` + * + * @param fieldName The name of the field whose value will be the first operand in the addition. + * @param second The second operand, which can be an {@code Expression} or a literal value. + * @param others Optional additional operands, each of which can be an {@code Expression} or a literal value. + * @returns A new {@code Expression} representing the addition operation. + */ + export function add( + fieldName: string, + second: Expression | unknown, + ...others: Array + ): FunctionExpression; + /** + * @beta + * Creates an expression that subtracts two expressions. + * + * @example + * ```typescript + * // Subtract the 'discount' field from the 'price' field + * subtract(field("price"), field("discount")); + * ``` + * + * @param minuend The expression to subtract from. + * @param subtrahend The expression to subtract. + * @returns A new {@code Expression} representing the subtraction operation. + */ + export function subtract( + minuend: Expression, + subtrahend: Expression, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that subtracts one value from another. + * + * @example + * ```typescript + * // Subtract the constant value 2 from the 'value' field + * subtract(field("value"), 2); + * ``` + * + * @param minuend The expression to subtract from. + * @param subtrahend The value to subtract. + * @returns A new {@code Expression} representing the subtraction operation. + */ + export function subtract( + minuend: Expression, + subtrahend: unknown, + ): FunctionExpression; + /** + * @beta + * Creates an expression that subtracts an expression from a field's value. + * + * @example + * ```typescript + * // Subtract the 'discount' field from the 'price' field + * subtract("price", field("discount")); + * ``` + * + * @param minuendFieldName The field name to subtract from. + * @param subtrahend The expression to subtract. + * @returns A new {@code Expression} representing the subtraction operation. + */ + export function subtract( + minuendFieldName: string, + subtrahend: Expression, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that subtracts a value from a field's value. + * + * + * @example + * ```typescript + * // Subtract 20 from the value of the 'total' field + * subtract("total", 20); + * ``` + * + * @param minuendFieldName The name of the field to subtract from. + * @param subtrahend The value to subtract. + * @returns A new {@code Expression} representing the subtraction operation. + */ + export function subtract( + minuendFieldName: string, + subtrahend: unknown, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that multiplies two or more values together. + * + * @example + * ```typescript + * // Multiply the 'quantity' field by the 'price' field + * multiply(field("quantity"), field("price")); + * + * // Multiply three values together + * multiply(field("a"), 2, field("b")); + * ``` + * + * @param first The first expression to multiply. + * @param second The second expression or literal to multiply. + * @param others Optional additional expressions or literals to multiply. + * @returns A new {@code FunctionExpression} representing the multiplication operation. + */ + export function multiply( + first: Expression, + second: Expression | unknown, + ...others: Array + ): FunctionExpression; + + /** + * @beta + * Creates an expression that multiplies a field's value by one or more other expressions or literal values. + * + * @example + * ```typescript + * // Multiply the 'quantity' field by the 'price' field + * multiply("quantity", field("price")); + * ``` + * + * @param fieldName The name of the field whose value will be the initial operand of the multiplication. + * @param second The second operand, which can be an `Expression` or a literal value, to be multiplied. + * @param others Optional additional operands (`Expression` or literal values) to be included in the multiplication. + * @returns A new {@link FunctionExpression} representing the multiplication operation. + */ + export function multiply( + fieldName: string, + second: Expression | unknown, + ...others: Array + ): FunctionExpression; + /** + * @beta + * Creates an expression that divides two expressions. + * + * @example + * ```typescript + * // Divide the 'total' field by the 'count' field + * divide(field("total"), field("count")); + * ``` + * + * @param dividend The expression to be divided. + * @param divisor The expression to divide by. + * @returns A new {@code Expression} representing the division operation. + */ + export function divide( + dividend: Expression, + divisor: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that divides an expression by a constant value. + * + * @example + * ```typescript + * // Divide the 'value' field by 10 + * divide(field("value"), 10); + * ``` + * + * @param dividend The expression to be divided. + * @param divisor The constant value to divide by. + * @returns A new {@code Expression} representing the division operation. + */ + export function divide( + dividend: Expression, + divisor: unknown, + ): FunctionExpression; + /** + * @beta + * Creates an expression that divides a field's value by an expression. + * + * @example + * ```typescript + * // Divide the 'total' field by the 'count' field + * divide("total", field("count")); + * ``` + * + * @param dividend The field name to be divided. + * @param divisor The expression to divide by. + * @returns A new {@code Expression} representing the division operation. + */ + export function divide( + dividend: string, + divisor: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that divides a field's value by a constant value. + * + * @example + * ```typescript + * // Divide the 'value' field by 10 + * divide("value", 10); + * ``` + * + * @param dividend The field name to be divided. + * @param divisor The constant value to divide by. + * @returns A new {@code Expression} representing the division operation. + */ + export function divide( + dividend: string, + divisor: unknown, + ): FunctionExpression; + /** + * @beta + * Creates an expression that calculates the modulo (remainder) of dividing two expressions. + * + * @example + * ```typescript + * // Calculate the remainder of dividing 'field1' by 'field2'. + * mod(field("field1"), field("field2")); + * ``` + * + * @param left The dividend expression. + * @param right The divisor expression. + * @returns A new {@code Expression} representing the modulo operation. + */ + export function mod( + left: Expression, + right: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that calculates the modulo (remainder) of dividing an expression by a constant. + * + * @example + * ```typescript + * // Calculate the remainder of dividing 'field1' by 5. + * mod(field("field1"), 5); + * ``` + * + * @param expression The dividend expression. + * @param value The divisor constant. + * @returns A new {@code Expression} representing the modulo operation. + */ + export function mod( + expression: Expression, + value: unknown, + ): FunctionExpression; + /** + * @beta + * Creates an expression that calculates the modulo (remainder) of dividing a field's value by an expression. + * + * @example + * ```typescript + * // Calculate the remainder of dividing 'field1' by 'field2'. + * mod("field1", field("field2")); + * ``` + * + * @param fieldName The dividend field name. + * @param expression The divisor expression. + * @returns A new {@code Expression} representing the modulo operation. + */ + export function mod( + fieldName: string, + expression: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that calculates the modulo (remainder) of dividing a field's value by a constant. + * + * @example + * ```typescript + * // Calculate the remainder of dividing 'field1' by 5. + * mod("field1", 5); + * ``` + * + * @param fieldName The dividend field name. + * @param value The divisor constant. + * @returns A new {@code Expression} representing the modulo operation. + */ + export function mod(fieldName: string, value: unknown): FunctionExpression; + + /** + * @beta + * Creates an expression that constructs a Firestore map value from a given JavaScript object. + * The keys of the object become the field names in the Firestore map, and the values become the field values. + * Values can be literal values or other expressions (e.g., `Field.of()`). + * + * @example + * ```typescript + * // Create a map from the input object, where 'foo' is a literal string and 'baz' references the value + * // of the 'baz' field from the document currently being processed by the pipeline. + * map({foo: 'bar', baz: Field.of('baz')}).as('data'); + * ``` + * + * @param elements The JavaScript object literal whose properties will be used to create the Firestore map expression. + * @returns A new {@code FunctionExpression} representing the map function. + */ + export function map(elements: Record): FunctionExpression; + /** + * @beta + * Creates an expression that creates a Firestore array value from a given JavaScript array. + * Array values can be literals or other expressions (e.g., `Field.of()`). + * + * @example + * ```typescript + * // Create an array value from the input array and reference the 'baz' field value from the input document. + * array(['bar', Field.of('baz')]).as('foo'); + * ``` + * + * @param elements The input array to evaluate in the expression. + * @returns A new {@code Expression} representing the array function. + */ + export function array(elements: unknown[]): FunctionExpression; + + /** + * @beta + * Creates an expression that checks if two expressions are equal. + * + * @example + * ```typescript + * // Check if the 'age' field is equal to an expression + * equal(field("age"), field("minAge").add(10)); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @returns A new `BooleanExpression` representing the equality comparison. + */ + export function equal( + left: Expression, + right: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an expression is equal to a constant value. + * + * @example + * ```typescript + * // Check if the 'age' field is equal to 21 + * equal(field("age"), 21); + * ``` + * + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the equality comparison. + */ + export function equal( + expression: Expression, + value: unknown, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a field's value is equal to another expression. + * + * @example + * ```typescript + * // Check if the 'age' field is equal to the 'limit' field + * equal("age", field("limit")); + * ``` + * + * @param fieldName The name of the field to compare. + * @param expression The expression to compare the field's value against. + * @returns A new `BooleanExpression` representing the equality comparison. + */ + export function equal( + fieldName: string, + expression: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's value is equal to a constant value. + * + * @example + * ```typescript + * // Check if the 'city' field is equal to string constant "London" + * equal("city", "London"); + * ``` + * + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the equality comparison. + */ + export function equal(fieldName: string, value: unknown): BooleanExpression; + /** + * @beta + * Creates an expression that checks if two expressions are not equal. + * + * @example + * ```typescript + * // Check if the 'status' field is not equal to field 'finalState' + * notEqual(field("status"), field("finalState")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @returns A new `Expression` representing the inequality comparison. + */ + export function notEqual( + left: Expression, + right: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an expression is not equal to a constant value. + * + * @example + * ```typescript + * // Check if the 'status' field is not equal to "completed" + * notEqual(field("status"), "completed"); + * ``` + * + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the inequality comparison. + */ + export function notEqual( + expression: Expression, + value: unknown, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a field's value is not equal to an expression. + * + * @example + * ```typescript + * // Check if the 'status' field is not equal to the value of 'expectedStatus' + * notEqual("status", field("expectedStatus")); + * ``` + * + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @returns A new `BooleanExpression` representing the inequality comparison. + */ + export function notEqual( + fieldName: string, + expression: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's value is not equal to a constant value. + * + * @example + * ```typescript + * // Check if the 'country' field is not equal to "USA" + * notEqual("country", "USA"); + * ``` + * + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the inequality comparison. + */ + export function notEqual( + fieldName: string, + value: unknown, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if the first expression is less than the second expression. + * + * @example + * ```typescript + * // Check if the 'age' field is less than 30 + * lessThan(field("age"), field("limit")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @returns A new `Expression` representing the less than comparison. + */ + export function lessThan( + left: Expression, + right: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an expression is less than a constant value. + * + * @example + * ```typescript + * // Check if the 'age' field is less than 30 + * lessThan(field("age"), 30); + * ``` + * + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the less than comparison. + */ + export function lessThan( + expression: Expression, + value: unknown, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a field's value is less than an expression. + * + * @example + * ```typescript + * // Check if the 'age' field is less than the 'limit' field + * lessThan("age", field("limit")); + * ``` + * + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @returns A new `BooleanExpression` representing the less than comparison. + */ + export function lessThan( + fieldName: string, + expression: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's value is less than a constant value. + * + * @example + * ```typescript + * // Check if the 'price' field is less than 50 + * lessThan("price", 50); + * ``` + * + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the less than comparison. + */ + export function lessThan( + fieldName: string, + value: unknown, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if the first expression is less than or equal to the second + * expression. + * + * @example + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * lessThanOrEqual(field("quantity"), field("limit")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @returns A new `Expression` representing the less than or equal to comparison. + */ + export function lessThanOrEqual( + left: Expression, + right: Expression, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a given expression's value is less than or equal to a constant value. + * + * @example + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * lessThanOrEqual(field("quantity"), 20); + * ``` + * + * @param expression The `Expression` to compare. + * @param value The constant value to compare against. + * @returns A new `BooleanExpression` representing the less than or equal to comparison. + */ + export function lessThanOrEqual( + expression: Expression, + value: unknown, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a field's value is less than or equal to another expression. + * + * @example + * ```typescript + * // Check if the 'quantity' field is less than or equal to the 'limit' field + * lessThanOrEqual("quantity", field("limit")); + * ``` + * + * @param fieldName The name of the field whose value will be compared. + * @param expression The expression to compare against the field's value. + * @returns A new `BooleanExpression` representing the less than or equal to comparison. + */ + export function lessThanOrEqual( + fieldName: string, + expression: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's value is less than or equal to a constant value. + * + * @example + * ```typescript + * // Check if the 'score' field is less than or equal to 70 + * lessThanOrEqual("score", 70); + * ``` + * + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the less than or equal to comparison. + */ + export function lessThanOrEqual( + fieldName: string, + value: unknown, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if the first expression is greater than the second + * expression. + * + * @example + * ```typescript + * // Check if the 'age' field is greater than 18 + * greaterThan(field("age"), constant(9).add(9)); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @returns A new `Expression` representing the greater than comparison. + */ + export function greaterThan( + left: Expression, + right: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an expression is greater than a constant value. + * + * @example + * ```typescript + * // Check if the 'age' field is greater than 18 + * greaterThan(field("age"), 18); + * ``` + * + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the greater than comparison. + */ + export function greaterThan( + expression: Expression, + value: unknown, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a field's value is greater than another expression. + * + * @example + * ```typescript + * // Check if the value of field 'age' is greater than the value of field 'limit' + * greaterThan("age", field("limit")); + * ``` + * + * @param fieldName The name of the field to compare. + * @param expression The expression to compare against. + * @returns A new `BooleanExpression` representing the greater than comparison. + */ + export function greaterThan( + fieldName: string, + expression: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's value is greater than a constant value. + * + * @example + * ```typescript + * // Check if the 'price' field is greater than 100 + * greaterThan("price", 100); + * ``` + * + * @param fieldName The name of the field to compare. + * @param value The constant value to compare to. + * @returns A new `BooleanExpression` representing the greater than comparison. + */ + export function greaterThan( + fieldName: string, + value: unknown, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if the first expression is greater than or equal to the + * second expression. + * + * @example + * ```typescript + * // Check if the 'quantity' field is greater than or equal to the field "threshold" + * greaterThanOrEqual(field("quantity"), field("threshold")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @returns A new `Expression` representing the greater than or equal to comparison. + */ + export function greaterThanOrEqual( + left: Expression, + right: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an expression is greater than or equal to a constant + * value. + * + * @example + * ```typescript + * // Check if the 'quantity' field is greater than or equal to 10 + * greaterThanOrEqual(field("quantity"), 10); + * ``` + * + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the greater than or equal to comparison. + */ + export function greaterThanOrEqual( + expression: Expression, + value: unknown, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's value is greater than or equal to an expression. + * + * @example + * ```typescript + * // Check if the value of field 'age' is greater than or equal to the value of field 'limit' + * greaterThanOrEqual("age", field("limit")); + * ``` + * + * @param fieldName The field name to compare. + * @param value The expression to compare to. + * @returns A new `Expression` representing the greater than or equal to comparison. + */ + export function greaterThanOrEqual( + fieldName: string, + value: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's value is greater than or equal to a constant + * value. + * + * @example + * ```typescript + * // Check if the 'score' field is greater than or equal to 80 + * greaterThanOrEqual("score", 80); + * ``` + * + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @returns A new `Expression` representing the greater than or equal to comparison. + */ + export function greaterThanOrEqual( + fieldName: string, + value: unknown, + ): BooleanExpression; + + /** + * @beta + * + * Creates an expression that concatenates an array expression with other arrays. + * + * @example + * ```typescript + * // Combine the 'items' array with two new item arrays + * arrayConcat(field("items"), [field("newItems"), field("otherItems")]); + * ``` + * + * @param firstArray The first array expression to concatenate to. + * @param secondArray The second array expression or array literal to concatenate to. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @returns A new {@code Expr} representing the concatenated array. + */ + export function arrayConcat( + firstArray: Expression, + secondArray: Expression | unknown[], + ...otherArrays: Array + ): FunctionExpression; + + /** + * @beta + * + * Creates an expression that concatenates a field's array value with other arrays. + * + * @example + * ```typescript + * // Combine the 'items' array with two new item arrays + * arrayConcat("items", [field("newItems"), field("otherItems")]); + * ``` + * + * @param firstArrayField The first array to concatenate to. + * @param secondArray The second array expression or array literal to concatenate to. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @returns A new {@code Expr} representing the concatenated array. + */ + export function arrayConcat( + firstArrayField: string, + secondArray: Expression | unknown[], + ...otherArrays: Array + ): FunctionExpression; + + /** + * @beta + * Creates an expression that checks if an array expression contains a specific element. + * + * @example + * ```typescript + * // Check if the 'colors' array contains the value of field 'selectedColor' + * arrayContains(field("colors"), field("selectedColor")); + * ``` + * + * @param array The array expression to check. + * @param element The element to search for in the array. + * @returns A new {@code Expression} representing the 'array_contains' comparison. + */ + export function arrayContains( + array: Expression, + element: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an array expression contains a specific element. + * + * @example + * ```typescript + * // Check if the 'colors' array contains "red" + * arrayContains(field("colors"), "red"); + * ``` + * + * @param array The array expression to check. + * @param element The element to search for in the array. + * @returns A new {@code Expression} representing the 'array_contains' comparison. + */ + export function arrayContains( + array: Expression, + element: unknown, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's array value contains a specific element. + * + * @example + * ```typescript + * // Check if the 'colors' array contains the value of field 'selectedColor' + * arrayContains("colors", field("selectedColor")); + * ``` + * + * @param fieldName The field name to check. + * @param element The element to search for in the array. + * @returns A new {@code Expression} representing the 'array_contains' comparison. + */ + export function arrayContains( + fieldName: string, + element: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's array value contains a specific value. + * + * @example + * ```typescript + * // Check if the 'colors' array contains "red" + * arrayContains("colors", "red"); + * ``` + * + * @param fieldName The field name to check. + * @param element The element to search for in the array. + * @returns A new {@code Expression} representing the 'array_contains' comparison. + */ + export function arrayContains( + fieldName: string, + element: unknown, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an array expression contains any of the specified + * elements. + * + * @example + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "Science" + * arrayContainsAny(field("categories"), [field("cate1"), "Science"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @returns A new {@code Expression} representing the 'array_contains_any' comparison. + */ + export function arrayContainsAny( + array: Expression, + values: Array, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's array value contains any of the specified + * elements. + * + * @example + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * arrayContainsAny("categories", [field("cate1"), "Science"]); + * ``` + * + * @param fieldName The field name to check. + * @param values The elements to check for in the array. + * @returns A new {@code Expression} representing the 'array_contains_any' comparison. + */ + export function arrayContainsAny( + fieldName: string, + values: Array, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an array expression contains any of the specified + * elements. + * + * @example + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "Science" + * arrayContainsAny(field("categories"), array([field("cate1"), "Science"])); + * ``` + * + * @param array The array expression to check. + * @param values An expression that evaluates to an array, whose elements to check for in the array. + * @returns A new {@code Expression} representing the 'array_contains_any' comparison. + */ + export function arrayContainsAny( + array: Expression, + values: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's array value contains any of the specified + * elements. + * + * @example + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * arrayContainsAny("categories", array([field("cate1"), "Science"])); + * ``` + * + * @param fieldName The field name to check. + * @param values An expression that evaluates to an array, whose elements to check for in the array field. + * @returns A new {@code Expression} representing the 'array_contains_any' comparison. + */ + export function arrayContainsAny( + fieldName: string, + values: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an array expression contains all the specified elements. + * + * @example + * ```typescript + * // Check if the "tags" array contains all of the values: "SciFi", "Adventure", and the value from field "tag1" + * arrayContainsAll(field("tags"), [field("tag1"), constant("SciFi"), "Adventure"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @returns A new {@code Expression} representing the 'array_contains_all' comparison. + */ + export function arrayContainsAll( + array: Expression, + values: Array, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's array value contains all the specified values or + * expressions. + * + * @example + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1', the value "SciFi", and "Adventure" + * arrayContainsAll("tags", [field("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param fieldName The field name to check. + * @param values The elements to check for in the array. + * @returns A new {@code Expression} representing the 'array_contains_all' comparison. + */ + export function arrayContainsAll( + fieldName: string, + values: Array, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an array expression contains all the specified elements. + * + * The `array` parameter should be an expression that evaluates to an array. + * The `arrayExpression` parameter should be an expression that evaluates to an array of elements + * to check for within the `array`. + * + * @example + * ```typescript + * // Check if the "tags" array contains all elements from the "requiredTags" field. + * arrayContainsAll(field("tags"), field("requiredTags")); + * + * // Check if the "items" array contains all elements from a constant array. + * arrayContainsAll(field("items"), constant(["apple", "banana"])); + * ``` + * + * @param array An expression evaluating to the array to check. + * @param arrayExpression An expression evaluating to an array of elements to check for. + * @returns A new {@code BooleanExpression} representing the 'array_contains_all' comparison. + */ + export function arrayContainsAll( + array: Expression, + arrayExpression: Expression, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a field's array value contains all the elements specified by another expression. + * + * @example + * ```typescript + * // Check if the 'tags' array contains all values present in the 'requiredTags' field. + * arrayContainsAll("tags", field("requiredTags")); + * ``` + * + * @param fieldName The name of the array field to check. + * @param arrayExpression An expression that evaluates to an array of values to check for. + * @returns A new {@code BooleanExpression} representing the 'array_contains_all' comparison. + */ + export function arrayContainsAll( + fieldName: string, + arrayExpression: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that calculates the length of an array in a specified field. + * + * @example + * ```typescript + * // Get the number of items in field 'cart' + * arrayLength('cart'); + * ``` + * + * @param fieldName The name of the field containing an array to calculate the length of. + * @returns A new {@code Expression} representing the length of the array. + */ + export function arrayLength(fieldName: string): FunctionExpression; + /** + * @beta + * Creates an expression that calculates the length of an array expression. + * + * @example + * ```typescript + * // Get the number of items in the 'cart' array + * arrayLength(field("cart")); + * ``` + * + * @param array The array expression to calculate the length of. + * @returns A new {@code Expression} representing the length of the array. + */ + export function arrayLength(array: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that checks if an expression, when evaluated, is equal to any of the provided values or + * expressions. + * + * @example + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * equalAny(field("category"), [constant("Electronics"), field("primaryType")]); + * ``` + * + * @param expression The expression whose results to compare. + * @param values The values to check against. + * @returns A new {@code Expression} representing the 'IN' comparison. + */ + export function equalAny( + expression: Expression, + values: Array, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an expression is equal to any of the provided values. + * + * ```typescript + * // Check if the 'category' field is set to a value in the disabledCategories field + * equalAny(field("category"), field('disabledCategories')); + * ``` + * + * @param expression The expression whose results to compare. + * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input. + * @returns A new {@code Expression} representing the 'IN' comparison. + */ + export function equalAny( + expression: Expression, + arrayExpression: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's value is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * equalAny("category", [constant("Electronics"), field("primaryType")]); + * ``` + * + * @param fieldName The field to compare. + * @param values The values to check against. + * @returns A new {@code Expression} representing the 'IN' comparison. + */ + export function equalAny( + fieldName: string, + values: Array, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a field's value is equal to any of the elements + * within the array that the provided expression evaluates to. + * + * This is equivalent to an 'IN' comparison in Firestore queries. + * + * ```typescript + * // Check if the 'category' field's value is present in the 'allowedCategories' array field. + * equalAny("category", field("allowedCategories")); + * ``` + * + * @param fieldName The name of the field to compare. + * @param arrayExpression An expression that evaluates to an array. The function checks if the value of `fieldName` is equal to any element within this array. + * @returns A new {@code BooleanExpression} representing the 'IN' comparison. + */ + export function equalAny( + fieldName: string, + arrayExpression: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if an expression is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notEqualAny(field("status"), ["pending", field("rejectedStatus")]); + * ``` + * + * @param element The expression to compare. + * @param values The values to check against. + * @returns A new {@code Expression} representing the 'NOT IN' comparison. + */ + export function notEqualAny( + element: Expression, + values: Array, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's value is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notEqualAny("status", [constant("pending"), field("rejectedStatus")]); + * ``` + * + * @param fieldName The field name to compare. + * @param values The values to check against. + * @returns A new {@code Expression} representing the 'NOT IN' comparison. + */ + export function notEqualAny( + fieldName: string, + values: Array, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a given element expression is not equal to any of the values + * contained within an array expression. This is equivalent to a "NOT IN" operation. + * + * ```typescript + * // Check if the 'status' field is not present in the array stored in the 'invalidStatuses' field. + * notEqualAny(field("status"), field("invalidStatuses")); + * ``` + * + * @param element The expression representing the value to check. + * @param arrayExpression An expression that evaluates to an array of values to check against. + * @returns A new {@code BooleanExpression} representing the 'NOT IN' comparison. + */ + export function notEqualAny( + element: Expression, + arrayExpression: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's value is not equal to any of the values in the evaluated expression. + * + * ```typescript + * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' + * notEqualAny("status", field("rejectedStatuses")); + * ``` + * + * @param fieldName The field name to compare. + * @param arrayExpression The values to check against. + * @returns A new {@code Expression} representing the 'NOT IN' comparison. + */ + export function notEqualAny( + fieldName: string, + arrayExpression: Expression, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on two or more Boolean expressions. + * The result is true if an odd number of the input expressions evaluate to true, and false otherwise. + * + * ```typescript + * // Check if exactly one of the conditions is true: 'age' greater than 18, 'city' is "London", + * // or 'status' is "active". + * const condition = xor( + * greaterThan("age", 18), + * equal("city", "London"), + * equal("status", "active") + * ); + * ``` + * + * @param first The first Boolean expression. + * @param second The second Boolean expression. + * @param additionalConditions Optional: Additional Boolean expressions to include in the XOR operation. + * @returns A new `BooleanExpression` representing the logical 'XOR' operation. + */ + export function xor( + first: BooleanExpression, + second: BooleanExpression, + ...additionalConditions: BooleanExpression[] + ): BooleanExpression; + /** + * @beta + * Creates a conditional expression that evaluates to a 'then' expression if a condition is true + * and an 'else' expression if the condition is false. + * + * ```typescript + * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". + * conditional( + * greaterThan("age", 18), constant("Adult"), constant("Minor")); + * ``` + * + * @param condition The condition to evaluate. + * @param thenExpr The expression to evaluate if the condition is true. + * @param elseExpr The expression to evaluate if the condition is false. + * @returns A new {@code Expression} representing the conditional expression. + */ + export function conditional( + condition: BooleanExpression, + thenExpr: Expression, + elseExpr: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that negates a filter condition. + * + * ```typescript + * // Find documents where the 'completed' field is NOT true + * not(equal("completed", true)); + * ``` + * + * @param booleanExpr The filter condition to negate. + * @returns A new {@code Expression} representing the negated filter condition. + */ + export function not(booleanExpr: BooleanExpression): BooleanExpression; + /** + * @beta + * Creates an expression that returns the largest value between multiple input + * expressions or literal values. Based on Firestore's value type ordering. + * + * ```typescript + * // Returns the largest value between the 'field1' field, the 'field2' field, + * // and 1000 + * logicalMaximum(field("field1"), field("field2"), 1000); + * ``` + * + * @param first The first operand expression. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @returns A new {@code Expression} representing the logical max operation. + */ + export function logicalMaximum( + first: Expression, + second: Expression | unknown, + ...others: Array + ): FunctionExpression; + /** + * @beta + * Creates an expression that returns the largest value between multiple input + * expressions or literal values. Based on Firestore's value type ordering. + * + * ```typescript + * // Returns the largest value between the 'field1' field, the 'field2' field, + * // and 1000. + * logicalMaximum("field1", field("field2"), 1000); + * ``` + * + * @param fieldName The first operand field name. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @returns A new {@code Expression} representing the logical max operation. + */ + export function logicalMaximum( + fieldName: string, + second: Expression | unknown, + ...others: Array + ): FunctionExpression; + /** + * @beta + * Creates an expression that returns the smallest value between multiple input + * expressions and literal values. Based on Firestore's value type ordering. + * + * ```typescript + * // Returns the smallest value between the 'field1' field, the 'field2' field, + * // and 1000. + * logicalMinimum(field("field1"), field("field2"), 1000); + * ``` + * + * @param first The first operand expression. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @returns A new {@code Expression} representing the logical min operation. + */ + export function logicalMinimum( + first: Expression, + second: Expression | unknown, + ...others: Array + ): FunctionExpression; + /** + * @beta + * Creates an expression that returns the smallest value between a field's value + * and other input expressions or literal values. + * Based on Firestore's value type ordering. + * + * ```typescript + * // Returns the smallest value between the 'field1' field, the 'field2' field, + * // and 1000. + * logicalMinimum("field1", field("field2"), 1000); + * ``` + * + * @param fieldName The first operand field name. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @returns A new {@code Expression} representing the logical min operation. + */ + export function logicalMinimum( + fieldName: string, + second: Expression | unknown, + ...others: Array + ): FunctionExpression; + + /** + * @beta + * Creates an expression that checks if a field exists. + * + * ```typescript + * // Check if the document has a field named "phoneNumber" + * exists(field("phoneNumber")); + * ``` + * + * @param value An expression representing the field to check for existence. + * @returns A new {@code BooleanExpression} representing the 'exists' check. + */ + export function exists(value: Expression): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field exists. + * + * ```typescript + * // Check if the document has a field named "phoneNumber" + * exists("phoneNumber"); + * ``` + * + * @param fieldName The field name to check. + * @returns A new {@code Expression} representing the 'exists' check. + */ + export function exists(fieldName: string): BooleanExpression; + + /** + * @beta + * Creates an expression that reverses a string. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * reverse(field("myString")); + * ``` + * + * @param stringExpression An expression evaluating to a string value, which will be reversed. + * @returns A new {@code Expression} representing the reversed string. + */ + export function reverse(stringExpression: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that reverses a string value in the specified field. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * reverse("myString"); + * ``` + * + * @param field The name of the field representing the string to reverse. + * @returns A new {@code Expression} representing the reversed string. + */ + export function reverse(field: string): FunctionExpression; + /** + * @beta + * Creates an expression that reverses an array. + * + * ```typescript + * // Reverse the value of the 'myArray' field. + * arrayReverse(field("myArray")); + * ``` + * + * @param arrayExpression An expression evaluating to an array value, which will be reversed. + * @returns A new {@code Expression} representing the reversed array. + */ + export function arrayReverse( + arrayExpression: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that reverses an array. + * + * ```typescript + * // Reverse the value of the 'myArray' field. + * arrayReverse("myArray"); + * ``` + * + * @param fieldName The name of the field to reverse. + * @returns A new {@code Expression} representing the reversed array. + */ + export function arrayReverse(fieldName: string): FunctionExpression; + /** + * @beta + * Creates an expression that computes the ceiling of a numeric value. + * + * ```typescript + * // Compute the ceiling of the 'price' field. + * ceil(field("price")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the ceiling will be computed for. + * @returns A new {@code Expression} representing the ceiling of the numeric value. + */ + export function ceil(expression: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that computes the ceiling of a numeric value. + * + * ```typescript + * // Compute the ceiling of the 'price' field. + * ceil("price"); + * ``` + * + * @param fieldName The name of the field to compute the ceiling of. + * @returns A new {@code Expression} representing the ceiling of the numeric value. + */ + export function ceil(fieldName: string): FunctionExpression; + + /** + * @beta + * Creates an expression that computes `e` (Euler's number) raised to the power of the given expression's result. + * + * This function is equivalent to `Math.exp()` in JavaScript. + * + * ```typescript + * // Compute e to the power of 2. + * exp(constant(2)); + * ``` + * + * @param expression An expression evaluating to a numeric value, which will be used as the exponent for `e`. + * @returns A new {@link FunctionExpression} representing `e` raised to the power of the input expression's result. + */ + export function exp(expression: Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that computes 'e' (Euler's number) raised to the power of the specified field's numeric value. + * + * ```typescript + * // Compute 'e' to the power of the 'value' field. + * exp('value'); + * ``` + * + * @param fieldName The name of the field whose numeric value will be used as the exponent. + * @returns A new {@code FunctionExpression} representing 'e' raised to the power of the numeric value. + */ + export function exp(fieldName: string): FunctionExpression; + /** + * @beta + * Creates an aggregation that counts the number of distinct values of an evaluated expression. + * + * @param expression The expression to count distinct values of. + * @returns A new `AggregateFunction` representing the 'count_distinct' aggregation. + */ + export function countDistinct(expression: Expression): AggregateFunction; + /** + * @beta + * Creates an aggregation that counts the number of distinct values of a field. + * + * @param fieldName The field to count distinct values of. + * @returns A new `AggregateFunction` representing the 'count_distinct' aggregation. + */ + export function countDistinct(fieldName: string): AggregateFunction; + /** + * @beta + * Creates an expression that calculates the byte length of a string in UTF-8, or just the length of a Blob. + * + * ```typescript + * // Calculate the length of the 'myString' field in bytes. + * byteLength(field("myString")); + * ``` + * + * @param expr The expression representing the string. + * @returns A new {@code Expression} representing the length of the string in bytes. + */ + export function byteLength(expr: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that calculates the length of a string represented by a field in UTF-8 bytes, or just the length of a Blob. + * + * ```typescript + * // Calculate the length of the 'myString' field in bytes. + * byteLength("myString"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @returns A new {@code Expression} representing the length of the string in bytes. + */ + export function byteLength(fieldName: string): FunctionExpression; + + /** + * @beta + * Creates an expression that calculates the character length of a string field in UTF8. + * + * ```typescript + * // Get the character length of the 'name' field in UTF-8. + * charLength("name"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @returns A new {@code Expression} representing the length of the string. + */ + export function charLength(fieldName: string): FunctionExpression; + + /** + * @beta + * Creates an expression that calculates the character length of a string expression in UTF-8. + * + * ```typescript + * // Get the character length of the 'name' field in UTF-8. + * charLength(field("name")); + * ``` + * + * @param stringExpression The expression representing the string to calculate the length of. + * @returns A new {@code Expression} representing the length of the string. + */ + export function charLength( + stringExpression: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that performs a case-sensitive wildcard string comparison against a + * field. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like("title", "%guide%"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @returns A new {@code Expression} representing the 'like' comparison. + */ + export function like(fieldName: string, pattern: string): BooleanExpression; + /** + * @beta + * Creates an expression that performs a case-sensitive wildcard string comparison against a + * field. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like("title", field("pattern")); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @returns A new {@code Expression} representing the 'like' comparison. + */ + export function like( + fieldName: string, + pattern: Expression, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that performs a case-sensitive wildcard string comparison. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like(field("title"), "%guide%"); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @returns A new {@code BooleanExpression} representing the 'like' comparison. + */ + export function like( + stringExpression: Expression, + pattern: string, + ): BooleanExpression; + /** + * @beta + * Creates an expression that performs a case-sensitive wildcard string comparison. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like(field("title"), field("pattern")); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @returns A new {@code Expression} representing the 'like' comparison. + */ + export function like( + stringExpression: Expression, + pattern: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a string field contains a specified regular expression as + * a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains("description", "(?i)example"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The regular expression to use for the search. + * @returns A new {@code Expression} representing the 'contains' comparison. + */ + export function regexContains( + fieldName: string, + pattern: string, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a string field contains a specified regular expression as + * a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains("description", field("pattern")); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The regular expression to use for the search. + * @returns A new {@code Expression} representing the 'contains' comparison. + */ + export function regexContains( + fieldName: string, + pattern: Expression, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a string expression contains a specified regular + * expression as a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains(field("description"), "(?i)example"); + * ``` + * + * @param stringExpression The expression representing the string to perform the regex comparison on. + * @param pattern The regular expression string to search for within the `stringExpression`. + * @returns A new {@code BooleanExpression} representing the result of the regex contains comparison. + */ + export function regexContains( + stringExpression: Expression, + pattern: string, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a string expression contains a specified regular + * expression as a substring. + * + * ```typescript + * // Check if the 'description' field contains a pattern from another field. + * regexContains(field("description"), field("searchPattern")); + * + * // Check if the 'productName' field contains "apple" or "orange". + * regexContains(field("productName"), "apple|orange"); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param pattern The regular expression to use for the search. + * @returns A new {@code BooleanExpression} representing the 'contains' comparison. + */ + export function regexContains( + stringExpression: Expression, + pattern: Expression, + ): BooleanExpression; + + /** + * @beta + * + * Creates an expression that returns the first substring of a string field that matches a + * specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract the domain name from an email field + * regexFind("email", "@[A-Za-z0-9.-]+"); + * ``` + * + * @param fieldName - The name of the field containing the string to search. + * @param pattern - The regular expression to search for. + * @returns A new {@link Expression} representing the regular expression find function. + */ + export function regexFind( + fieldName: string, + pattern: string, + ): FunctionExpression; + /** + * @beta + * + * Creates an expression that returns the first substring of a string field that matches a + * specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract a substring from 'email' based on a pattern stored in another field + * regexFind("email", field("pattern")); + * ``` + * + * @param fieldName - The name of the field containing the string to search. + * @param pattern - The regular expression to search for. + * @returns A new {@link Expression} representing the regular expression find function. + */ + export function regexFind( + fieldName: string, + pattern: Expression, + ): FunctionExpression; + /** + * @beta + * + * Creates an expression that returns the first substring of a string expression that matches + * a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract the domain from a lower-cased email address + * regexFind(field("email"), "@[A-Za-z0-9.-]+"); + * ``` + * + * @param stringExpression - The expression representing the string to search. + * @param pattern - The regular expression to search for. + * @returns A new {@link Expression} representing the regular expression find function. + */ + export function regexFind( + stringExpression: Expression, + pattern: string, + ): FunctionExpression; + /** + * @beta + * + * Creates an expression that returns the first substring of a string expression that matches + * a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract a substring based on a dynamic pattern field + * regexFind(field("email"), field("pattern")); + * ``` + * + * @param stringExpression - The expression representing the string to search. + * @param pattern - The regular expression to search for. + * @returns A new {@link Expression} representing the regular expression find function. + */ + export function regexFind( + stringExpression: Expression, + pattern: Expression, + ): FunctionExpression; + /** + * @beta + * + * Creates an expression that evaluates to a list of all substrings in a string field that + * match a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract all hashtags from a post content field + * regexFindAll("content", "#[A-Za-z0-9_]+"); + * ``` + * + * @param fieldName - The name of the field containing the string to search. + * @param pattern - The regular expression to search for. + * @returns A new {@link Expression} that evaluates to an array of matched substrings. + */ + export function regexFindAll( + fieldName: string, + pattern: string, + ): FunctionExpression; + /** + * @beta + * + * Creates an expression that evaluates to a list of all substrings in a string field that + * match a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract all matches from 'content' based on a pattern stored in another field + * regexFindAll("content", field("pattern")); + * ``` + * + * @param fieldName - The name of the field containing the string to search. + * @param pattern - The regular expression to search for. + * @returns A new {@link Expression} that evaluates to an array of matched substrings. + */ + export function regexFindAll( + fieldName: string, + pattern: Expression, + ): FunctionExpression; + /** + * @beta + * + * Creates an expression that evaluates to a list of all substrings in a string expression + * that match a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract all mentions from a lower-cased comment + * regexFindAll(field("comment"), "@[A-Za-z0-9_]+"); + * ``` + * + * @param stringExpression - The expression representing the string to search. + * @param pattern - The regular expression to search for. + * @returns A new {@link Expression} that evaluates to an array of matched substrings. + */ + export function regexFindAll( + stringExpression: Expression, + pattern: string, + ): FunctionExpression; + /** + * @beta + * + * Creates an expression that evaluates to a list of all substrings in a string expression + * that match a specified regular expression. + * + * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. + * + * @example + * ```typescript + * // Extract all matches based on a dynamic pattern expression + * regexFindAll(field("comment"), field("pattern")); + * ``` + * + * @param stringExpression - The expression representing the string to search. + * @param pattern - The regular expression to search for. + * @returns A new {@link Expression} that evaluates to an array of matched substrings. + */ + export function regexFindAll( + stringExpression: Expression, + pattern: Expression, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that checks if a string field matches a specified regular expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch("email", "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The regular expression to use for the match. + * @returns A new {@code Expression} representing the regular expression match. + */ + export function regexMatch( + fieldName: string, + pattern: string, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a string field matches a specified regular expression. + * + * The `pattern` parameter is an `Expression` that evaluates to the regular expression string. + * This allows for dynamic regex patterns, such as those stored in other fields. + * + * ```typescript + * // Check if the 'email' field matches a regex pattern stored in the 'emailValidationRegex' field. + * regexMatch("email", field("emailValidationRegex")); + * ``` + * + * @param fieldName The name of the field containing the string value to be matched. + * @param pattern An `Expression` that evaluates to the regular expression string to use for the match. + * @returns A new `BooleanExpression` representing the result of the regular expression match. + */ + export function regexMatch( + fieldName: string, + pattern: Expression, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a string expression matches a specified regular + * expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch(field("email"), "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * ``` + * + * @param stringExpression An expression that evaluates to the string to match against. + * @param pattern The regular expression to use for the match. + * @returns A new `BooleanExpression` representing the result of the regular expression match. + */ + export function regexMatch( + stringExpression: Expression, + pattern: string, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a string expression matches a specified regular + * expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch(field("email"), field("pattern")); + * ``` + * + * @param stringExpression The expression representing the string to match against. + * @param pattern The regular expression to use for the match. + * @returns A new {@code Expression} representing the regular expression match. + */ + export function regexMatch( + stringExpression: Expression, + pattern: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a string field contains a specified substring. + * + * ```typescript + * // Check if the 'description' field contains "example". + * stringContains("description", "example"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param substring The substring to search for. + * @returns A new {@code Expression} representing the 'contains' comparison. + */ + export function stringContains( + fieldName: string, + substring: string, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a string field contains a substring specified by an expression. + * + * ```typescript + * // Check if the 'description' field contains the value of the 'keyword' field. + * stringContains("description", field("keyword")); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param substring The expression representing the substring to search for. + * @returns A new {@code Expression} representing the 'contains' comparison. + */ + export function stringContains( + fieldName: string, + substring: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a string expression contains a specified substring. + * + * ```typescript + * // Check if the 'description' field contains "example". + * stringContains(field("description"), "example"); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param substring The substring to search for. + * @returns A new {@code Expression} representing the 'contains' comparison. + */ + export function stringContains( + stringExpression: Expression, + substring: string, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a string expression contains a substring specified by another expression. + * + * ```typescript + * // Check if the 'description' field contains the value of the 'keyword' field. + * stringContains(field("description"), field("keyword")); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param substring The expression representing the substring to search for. + * @returns A new {@code Expression} representing the 'contains' comparison. + */ + export function stringContains( + stringExpression: Expression, + substring: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's value starts with a given prefix. + * + * ```typescript + * // Check if the 'name' field starts with "Mr." + * startsWith("name", "Mr."); + * ``` + * + * @param fieldName The field name to check. + * @param prefix The prefix to check for. + * @returns A new {@code Expression} representing the 'starts with' comparison. + */ + export function startsWith( + fieldName: string, + prefix: string, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's value starts with a given prefix. + * + * ```typescript + * // Check if the 'fullName' field starts with the value of the 'firstName' field + * startsWith("fullName", field("firstName")); + * ``` + * + * @param fieldName The field name to check. + * @param prefix The expression representing the prefix. + * @returns A new {@code Expression} representing the 'starts with' comparison. + */ + export function startsWith( + fieldName: string, + prefix: Expression, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a string value, represented by an expression, starts with a given prefix. + * + * ```typescript + * // Check if the 'name' field starts with "Mr." + * startsWith(field("name"), "Mr."); + * ``` + * + * @param stringExpression An expression that evaluates to a string, which will be checked for the prefix. + * @param prefix The string prefix to check for. + * @returns A new {@code BooleanExpression} representing the 'starts with' comparison. + */ + export function startsWith( + stringExpression: Expression, + prefix: string, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a string expression starts with a given prefix expression. + * + * ```typescript + * // Check if the 'fullName' field starts with the value of the 'prefix' field. + * startsWith(field("fullName"), field("prefix")); + * ``` + * + * @param stringExpression The string expression to check. + * @param prefix The prefix expression to check for. + * @returns A new {@code BooleanExpression} representing the 'starts with' comparison. + */ + export function startsWith( + stringExpression: Expression, + prefix: Expression, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that checks if a field's value ends with a given suffix. + * + * ```typescript + * // Check if the 'filename' field ends with ".txt" + * endsWith("filename", ".txt"); + * ``` + * + * @param fieldName The field name to check. + * @param suffix The suffix to check for. + * @returns A new `BooleanExpression` representing the 'ends with' comparison. + */ + export function endsWith( + fieldName: string, + suffix: string, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a field's value ends with a given postfix. + * + * ```typescript + * // Check if the 'url' field ends with the value of the 'extension' field + * endsWith("url", field("extension")); + * ``` + * + * @param fieldName The field name to check. + * @param suffix The expression representing the postfix. + * @returns A new {@code Expression} representing the 'ends with' comparison. + */ + export function endsWith( + fieldName: string, + suffix: Expression, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a string expression ends with a given postfix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." + * endsWith(field("fullName"), "Jr."); + * ``` + * + * @param stringExpression The expression to check. + * @param suffix The postfix to check for. + * @returns A new {@code Expression} representing the 'ends with' comparison. + */ + export function endsWith( + stringExpression: Expression, + suffix: string, + ): BooleanExpression; + /** + * @beta + * Creates an expression that checks if a string expression ends with a given postfix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." + * endsWith(field("fullName"), constant("Jr.")); + * ``` + * + * @param stringExpression The expression to check. + * @param suffix The postfix to check for. + * @returns A new {@code Expression} representing the 'ends with' comparison. + */ + export function endsWith( + stringExpression: Expression, + suffix: Expression, + ): BooleanExpression; + + /** + * @beta + * Creates an expression that converts a string field to lowercase. + * + * ```typescript + * // Convert the 'name' field to lowercase + * toLower("name"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @returns A new {@code Expression} representing the lowercase string. + */ + export function toLower(fieldName: string): FunctionExpression; + + /** + * @beta + * Creates an expression that converts a string expression to lowercase. + * + * ```typescript + * // Convert the 'name' field to lowercase + * toLower(field("name")); + * ``` + * + * @param stringExpression The expression representing the string to convert to lowercase. + * @returns A new {@code Expression} representing the lowercase string. + */ + export function toLower(stringExpression: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that converts a string field to uppercase. + * + * ```typescript + * // Convert the 'title' field to uppercase + * toUpper("title"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @returns A new {@code Expression} representing the uppercase string. + */ + export function toUpper(fieldName: string): FunctionExpression; + + /** + * @beta + * Creates an expression that converts a string expression to uppercase. + * + * ```typescript + * // Convert the 'title' field to uppercase + * toUpper(field("title")); + * ``` + * + * @param stringExpression The expression representing the string to convert to uppercase. + * @returns A new {@code FunctionExpression} representing the uppercase string. + */ + export function toUpper(stringExpression: Expression): FunctionExpression; + /** + * @beta + * + * Creates an expression that removes leading and trailing whitespace from a string or byte array. + * + * ```typescript + * // Trim whitespace from the 'userInput' field + * trim("userInput"); + * + * // Trim quotes from the 'userInput' field + * trim("userInput", '"'); + * ``` + * + * @param fieldName The name of the field containing the string or byte array. + * @param valueToTrim Optional This parameter is treated as a set of characters or bytes that will be + * trimmed from the input. If not specified, then whitespace will be trimmed. + * @returns A new {@code Expr} representing the trimmed string. + */ + export function trim( + fieldName: string, + valueToTrim?: string | Expression, + ): FunctionExpression; + + /** + * @beta + * + * Creates an expression that removes leading and trailing characters from a string or byte array expression. + * + * ```typescript + * // Trim whitespace from the 'userInput' field + * trim(field("userInput")); + * + * // Trim quotes from the 'userInput' field + * trim(field("userInput"), '"'); + * ``` + * + * @param stringExpression The expression representing the string or byte array to trim. + * @param valueToTrim Optional This parameter is treated as a set of characters or bytes that will be + * trimmed from the input. If not specified, then whitespace will be trimmed. + * @returns A new {@code Expr} representing the trimmed string or byte array. + */ + export function trim( + stringExpression: Expression, + valueToTrim?: string | Expression, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that concatenates multiple string values, which can be field names or other expressions that evaluate to strings, along with string literals. + * + * ```typescript + * // Combine the 'firstName' field, a space, and the 'lastName' field into a single string. + * stringConcat("firstName", " ", field("lastName")); + * ``` + * + * @param fieldName The name of the field to use as the initial string value for concatenation. + * @param secondString An expression or string literal to concatenate. + * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. + * @returns A new {@code FunctionExpression} representing the concatenated string. + */ + export function stringConcat( + fieldName: string, + secondString: Expression | string, + ...otherStrings: Array + ): FunctionExpression; + /** + * @beta + * Creates an expression that concatenates string expressions together. + * + * ```typescript + * // Combine the 'firstName', " ", and 'lastName' fields into a single string + * stringConcat(field("firstName"), " ", field("lastName")); + * ``` + * + * @param firstString The initial string expression to concatenate to. + * @param secondString An expression or string literal to concatenate. + * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. + * @returns A new {@code Expression} representing the concatenated string. + */ + export function stringConcat( + firstString: Expression, + secondString: Expression | string, + ...otherStrings: Array + ): FunctionExpression; + /** + * @beta + * Accesses a value from a map (object) field using the provided key. + * + * ```typescript + * // Get the 'city' value from the 'address' map field + * mapGet("address", "city"); + * ``` + * + * @param fieldName The field name of the map field. + * @param subField The key to access in the map. + * @returns A new {@code Expression} representing the value associated with the given key in the map. + */ + export function mapGet( + fieldName: string, + subField: string, + ): FunctionExpression; + /** + * @beta + * Accesses a value from a map (object) expression using the provided key. + * + * ```typescript + * // Get the 'city' value from the 'address' map field + * mapGet(field("address"), "city"); + * ``` + * + * @param mapExpression The expression representing the map. + * @param subField The key to access in the map. + * @returns A new {@code Expression} representing the value associated with the given key in the map. + */ + export function mapGet( + mapExpression: Expression, + subField: string, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that returns a new map with the specified entries added or updated. + * + * @remarks + * This only performs shallow updates to the map. Setting a value to `null` + * will retain the key with a `null` value. To remove a key entirely, use `mapRemove`. + * + * @example + * ```typescript + * // Set the 'city' to 'San Francisco' in the 'address' map field + * mapSet("address", "city", "San Francisco"); + * ``` + * + * @param mapField - The map field to set entries in. + * @param key - The key to set. Must be a string or a constant string expression. + * @param value - The value to set. + * @param moreKeyValues - Additional key-value pairs to set. + * @returns A new `Expression` representing the map with the entries set. + */ + export function mapSet( + mapField: string, + key: string | Expression, + value: unknown, + ...moreKeyValues: unknown[] + ): FunctionExpression; + /** + * @beta + * Creates an expression that returns a new map with the specified entries added or updated. + * + * @remarks + * This only performs shallow updates to the map. Setting a value to `null` + * will retain the key with a `null` value. To remove a key entirely, use `mapRemove`. + * + * @example + * ```typescript + * // Set the 'city' to "San Francisco" + * mapSet(map({"state": "California"}), "city", "San Francisco"); + * ``` + * + * @param mapExpression - The expression representing the map. + * @param key - The key to set. Must be a string or a constant string expression. + * @param value - The value to set. + * @param moreKeyValues - Additional key-value pairs to set. + * @returns A new `Expression` representing the map with the entries set. + */ + export function mapSet( + mapExpression: Expression, + key: string | Expression, + value: unknown, + ...moreKeyValues: unknown[] + ): FunctionExpression; + + /** + * @beta + * Creates an expression that returns the keys of a map. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the keys of the 'address' map field + * mapKeys("address"); + * ``` + * + * @param mapField - The map field to get the keys of. + * @returns A new `Expression` representing the keys of the map. + */ + export function mapKeys(mapField: string): FunctionExpression; + /** + * @beta + * Creates an expression that returns the keys of a map. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the keys of the map expression + * mapKeys(map({"city": "San Francisco"})); + * ``` + * + * @param mapExpression - The expression representing the map to get the keys of. + * @returns A new `Expression` representing the keys of the map. + */ + export function mapKeys(mapExpression: Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that returns the values of a map. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the values of the 'address' map field + * mapValues("address"); + * ``` + * + * @param mapField - The map field to get the values of. + * @returns A new `Expression` representing the values of the map. + */ + export function mapValues(mapField: string): FunctionExpression; + /** + * @beta + * Creates an expression that returns the values of a map. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the values of the map expression + * mapValues(map({"city": "San Francisco"})); + * ``` + * + * @param mapExpression - The expression representing the map to get the values of. + * @returns A new `Expression` representing the values of the map. + */ + export function mapValues(mapExpression: Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that returns the entries of a map as an array of maps, + * where each map contains a `"k"` property for the key and a `"v"` property for the value. + * For example: `[{ k: "key1", v: "value1" }, ...]`. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the entries of the 'address' map field + * mapEntries("address"); + * ``` + * + * @param mapField - The map field to get the entries of. + * @returns A new `Expression` representing the entries of the map. + */ + export function mapEntries(mapField: string): FunctionExpression; + /** + * @beta + * Creates an expression that returns the entries of a map as an array of maps, + * where each map contains a `"k"` property for the key and a `"v"` property for the value. + * For example: `[{ k: "key1", v: "value1" }, ...]`. + * + * @remarks + * While the backend generally preserves insertion order, relying on the + * order of the output array is not guaranteed and should be avoided. + * + * @example + * ```typescript + * // Get the entries of the map expression + * mapEntries(map({"city": "San Francisco"})); + * ``` + * + * @param mapExpression - The expression representing the map to get the entries of. + * @returns A new `Expression` representing the entries of the map. + */ + export function mapEntries(mapExpression: Expression): FunctionExpression; + + /** + * @beta + * Creates an aggregation that counts the total number of stage inputs. + * + * ```typescript + * // Count the total number of input documents + * countAll().as("totalDocument"); + * ``` + * + * @returns A new {@code AggregateFunction} representing the 'countAll' aggregation. + */ + export function countAll(): AggregateFunction; + /** + * @beta + * Creates an aggregation that counts the number of stage inputs with valid evaluations of the + * provided expression. + * + * ```typescript + * // Count the number of items where the price is greater than 10 + * count(field("price").greaterThan(10)).as("expensiveItemCount"); + * ``` + * + * @param expression The expression to count. + * @returns A new {@code AggregateFunction} representing the 'count' aggregation. + */ + export function count(expression: Expression): AggregateFunction; + /** + * @beta + * Creates an aggregation that counts the number of stage inputs where the input field exists. + * + * ```typescript + * // Count the total number of products + * count("productId").as("totalProducts"); + * ``` + * + * @param fieldName The name of the field to count. + * @returns A new {@code AggregateFunction} representing the 'count' aggregation. + */ + export function count(fieldName: string): AggregateFunction; + /** + * @beta + * Creates an aggregation that calculates the sum of values from an expression across multiple + * stage inputs. + * + * ```typescript + * // Calculate the total revenue from a set of orders + * sum(field("orderAmount")).as("totalRevenue"); + * ``` + * + * @param expression The expression to sum up. + * @returns A new {@code AggregateFunction} representing the 'sum' aggregation. + */ + export function sum(expression: Expression): AggregateFunction; + /** + * @beta + * Creates an aggregation that calculates the sum of a field's values across multiple stage + * inputs. + * + * ```typescript + * // Calculate the total revenue from a set of orders + * sum("orderAmount").as("totalRevenue"); + * ``` + * + * @param fieldName The name of the field containing numeric values to sum up. + * @returns A new {@code AggregateFunction} representing the 'sum' aggregation. + */ + export function sum(fieldName: string): AggregateFunction; + /** + * @beta + * Creates an aggregation that calculates the average (mean) of values from an expression across + * multiple stage inputs. + * + * ```typescript + * // Calculate the average age of users + * average(field("age")).as("averageAge"); + * ``` + * + * @param expression The expression representing the values to average. + * @returns A new {@code AggregateFunction} representing the 'average' aggregation. + */ + export function average(expression: Expression): AggregateFunction; + /** + * @beta + * Creates an aggregation that calculates the average (mean) of a field's values across multiple + * stage inputs. + * + * ```typescript + * // Calculate the average age of users + * average("age").as("averageAge"); + * ``` + * + * @param fieldName The name of the field containing numeric values to average. + * @returns A new {@code AggregateFunction} representing the 'average' aggregation. + */ + export function average(fieldName: string): AggregateFunction; + /** + * @beta + * Creates an aggregation that finds the minimum value of an expression across multiple stage + * inputs. + * + * ```typescript + * // Find the lowest price of all products + * minimum(field("price")).as("lowestPrice"); + * ``` + * + * @param expression The expression to find the minimum value of. + * @returns A new {@code AggregateFunction} representing the 'min' aggregation. + */ + export function minimum(expression: Expression): AggregateFunction; + /** + * @beta + * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. + * + * ```typescript + * // Find the lowest price of all products + * minimum("price").as("lowestPrice"); + * ``` + * + * @param fieldName The name of the field to find the minimum value of. + * @returns A new {@code AggregateFunction} representing the 'min' aggregation. + */ + export function minimum(fieldName: string): AggregateFunction; + /** + * @beta + * Creates an aggregation that finds the maximum value of an expression across multiple stage + * inputs. + * + * ```typescript + * // Find the highest score in a leaderboard + * maximum(field("score")).as("highestScore"); + * ``` + * + * @param expression The expression to find the maximum value of. + * @returns A new {@code AggregateFunction} representing the 'max' aggregation. + */ + export function maximum(expression: Expression): AggregateFunction; + /** + * @beta + * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. + * + * ```typescript + * // Find the highest score in a leaderboard + * maximum("score").as("highestScore"); + * ``` + * + * @param fieldName The name of the field to find the maximum value of. + * @returns A new {@code AggregateFunction} representing the 'max' aggregation. + */ + export function maximum(fieldName: string): AggregateFunction; + /** + * @beta + * Calculates the Cosine distance between a field's vector value and a literal vector value. + * + * ```typescript + * // Calculate the Cosine distance between the 'location' field and a target location + * cosineDistance("location", [37.7749, -122.4194]); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles) or {@link VectorValue} to compare against. + * @returns A new {@code Expression} representing the Cosine distance between the two vectors. + */ + export function cosineDistance( + fieldName: string, + vector: number[] | VectorValue, + ): FunctionExpression; + /** + * @beta + * Calculates the Cosine distance between a field's vector value and a vector expression. + * + * ```typescript + * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field + * cosineDistance("userVector", field("itemVector")); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vectorExpression The other vector (represented as an Expression) to compare against. + * @returns A new {@code Expression} representing the cosine distance between the two vectors. + */ + export function cosineDistance( + fieldName: string, + vectorExpression: Expression, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that computes the cosine distance between two vectors. + * + * The second argument can be either a vector literal (an array of numbers) or another vector expression. + * + * ```typescript + * // Calculate the cosine distance between the 'location' field and a target location literal. + * cosineDistance(field("location"), [37.7749, -122.4194]); + * ``` + * + * ```typescript + * // Calculate the cosine distance between two vector fields. + * cosineDistance(field("vector1"), field("vector2")); + * ``` + * + * @param vectorExpression The first vector, represented as an `Expression` (e.g., a field path). + * @param vector The second vector, which can be either a numeric array literal (`number[]`) or another `Expression`. + * @returns A new {@link FunctionExpression} representing the cosine distance. + */ + export function cosineDistance( + vectorExpression: Expression, + vector: number[] | Expression, + ): FunctionExpression; + /** + * @beta + * Calculates the Cosine distance between two vector expressions. + * + * ```typescript + * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field + * cosineDistance(field("userVector"), field("itemVector")); + * ``` + * + * @param vectorExpression The first vector (represented as an Expression) to compare against. + * @param otherVectorExpression The other vector (represented as an Expression) to compare against. + * @returns A new {@code Expression} representing the cosine distance between the two vectors. + */ + export function cosineDistance( + vectorExpression: Expression, + otherVectorExpression: Expression, + ): FunctionExpression; + /** + * @beta + * Calculates the dot product between a field's vector value and a double array. + * + * ```typescript + * // Calculate the dot product distance between a feature vector and a target vector + * dotProduct("features", [0.5, 0.8, 0.2]); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles or VectorValue) to calculate with. + * @returns A new {@code Expression} representing the dot product between the two vectors. + */ + export function dotProduct( + fieldName: string, + vector: number[] | VectorValue, + ): FunctionExpression; + + /** + * @beta + * Calculates the dot product between a field's vector value and a vector expression. + * + * ```typescript + * // Calculate the dot product of 'docVector1' with 'docVector2' + * dotProduct("docVector1", field("docVector2")); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vectorExpression The other vector (represented as an Expression) to calculate with. + * @returns A new {@code Expression} representing the dot product between the two vectors. + */ + export function dotProduct( + fieldName: string, + vectorExpression: Expression, + ): FunctionExpression; + + /** + * @beta + * Calculates the dot product between a vector expression and another vector (either a number array or a VectorValue). + * + * ```typescript + * // Calculate the dot product between a feature vector and a target vector + * dotProduct(field("features"), [0.5, 0.8, 0.2]); + * ``` + * + * @param vectorExpression The first vector (represented as an Expression) to calculate with. + * @param vector The other vector (as an array of numbers or VectorValue) to calculate with. + * @returns A new {@code Expression} representing the dot product between the two vectors. + */ + export function dotProduct( + vectorExpression: Expression, + vector: number[] | VectorValue, + ): FunctionExpression; + /** + * @beta + * Calculates the dot product between two vector expressions. + * + * ```typescript + * // Calculate the dot product between two document vectors: 'docVector1' and 'docVector2' + * dotProduct(field("docVector1"), field("docVector2")); + * ``` + * + * @param vectorExpression The first vector (represented as an Expression) to calculate with. + * @param otherVectorExpression The other vector (represented as an Expression) to calculate with. + * @returns A new {@code Expression} representing the dot product between the two vectors. + */ + export function dotProduct( + vectorExpression: Expression, + otherVectorExpression: Expression, + ): FunctionExpression; + + /** + * @beta + * Calculates the Euclidean distance between a field's vector value and another vector. + * The other vector can be provided as a double array or a {@link VectorValue}. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * euclideanDistance("location", [37.7749, -122.4194]); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles or VectorValue) to compare against. + * @returns A new {@code Expression} representing the Euclidean distance between the two vectors. + */ + export function euclideanDistance( + fieldName: string, + vector: number[] | VectorValue, + ): FunctionExpression; + /** + * @beta + * Calculates the Euclidean distance between a field's vector value and a vector expression. + * + * ```typescript + * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' + * euclideanDistance("pointA", field("pointB")); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vectorExpression The other vector (represented as an Expression) to compare against. + * @returns A new {@code Expression} representing the Euclidean distance between the two vectors. + */ + export function euclideanDistance( + fieldName: string, + vectorExpression: Expression, + ): FunctionExpression; + /** + * @beta + * Calculates the Euclidean distance between a vector expression and a double array. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * + * euclideanDistance(field("location"), [37.7749, -122.4194]); + * ``` + * + * @param vectorExpression The first vector (represented as an Expression) to compare against. + * @param vector The other vector (as an array of doubles or VectorValue) to compare against. + * @returns A new {@code Expression} representing the Euclidean distance between the two vectors. + */ + export function euclideanDistance( + vectorExpression: Expression, + vector: number[] | VectorValue, + ): FunctionExpression; + /** + * @beta + * Calculates the Euclidean distance between two vector expressions. + * + * ```typescript + * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' + * euclideanDistance(field("pointA"), field("pointB")); + * ``` + * + * @param vectorExpression The first vector (represented as an Expression) to compare against. + * @param otherVectorExpression The other vector (represented as an Expression) to compare against. + * @returns A new {@code Expression} representing the Euclidean distance between the two vectors. + */ + export function euclideanDistance( + vectorExpression: Expression, + otherVectorExpression: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that calculates the length of a Firestore Vector. + * + * ```typescript + * // Get the vector length (dimension) of the field 'embedding'. + * vectorLength(field("embedding")); + * ``` + * + * @param vectorExpression The expression representing the Firestore Vector. + * @returns A new {@code Expression} representing the length of the array. + */ + export function vectorLength( + vectorExpression: Expression, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that calculates the length (dimension) of a Firestore Vector represented by a field. + * + * ```typescript + * // Get the vector length (dimension) of the field 'embedding'. + * vectorLength("embedding"); + * ``` + * + * @param fieldName The name of the field representing the Firestore Vector. + * @returns A new {@code FunctionExpression} representing the length (dimension) of the vector. + */ + export function vectorLength(fieldName: string): FunctionExpression; + /** + * @beta + * Creates an expression that interprets an expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'microseconds' field as microseconds since epoch. + * unixMicrosToTimestamp(field("microseconds")); + * ``` + * + * @param expr The expression representing the number of microseconds since epoch. + * @returns A new {@code Expression} representing the timestamp. + */ + export function unixMicrosToTimestamp(expr: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that interprets a field's value as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'microseconds' field as microseconds since epoch. + * unixMicrosToTimestamp("microseconds"); + * ``` + * + * @param fieldName The name of the field representing the number of microseconds since epoch. + * @returns A new {@code Expression} representing the timestamp. + */ + export function unixMicrosToTimestamp( + fieldName: string, + ): FunctionExpression; + /** + * @beta + * Creates an expression that converts a timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to microseconds since epoch. + * timestampToUnixMicros(field("timestamp")); + * ``` + * + * @param expr The expression representing the timestamp. + * @returns A new {@code Expression} representing the number of microseconds since epoch. + */ + export function timestampToUnixMicros(expr: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that converts a timestamp field to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to microseconds since epoch. + * timestampToUnixMicros("timestamp"); + * ``` + * + * @param fieldName The name of the field representing the timestamp. + * @returns A new {@code Expression} representing the number of microseconds since epoch. + */ + export function timestampToUnixMicros( + fieldName: string, + ): FunctionExpression; + /** + * @beta + * Creates an expression that interprets an expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'milliseconds' field as milliseconds since epoch. + * unixMillisToTimestamp(field("milliseconds")); + * ``` + * + * @param expr The expression representing the number of milliseconds since epoch. + * @returns A new {@code Expression} representing the timestamp. + */ + export function unixMillisToTimestamp(expr: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that interprets a field's value as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'milliseconds' field as milliseconds since epoch. + * unixMillisToTimestamp("milliseconds"); + * ``` + * + * @param fieldName The name of the field representing the number of milliseconds since epoch. + * @returns A new {@code Expression} representing the timestamp. + */ + export function unixMillisToTimestamp( + fieldName: string, + ): FunctionExpression; + /** + * @beta + * Creates an expression that converts a timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to milliseconds since epoch. + * timestampToUnixMillis(field("timestamp")); + * ``` + * + * @param expr The expression representing the timestamp. + * @returns A new {@code Expression} representing the number of milliseconds since epoch. + */ + export function timestampToUnixMillis(expr: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that converts a timestamp field to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to milliseconds since epoch. + * timestampToUnixMillis("timestamp"); + * ``` + * + * @param fieldName The name of the field representing the timestamp. + * @returns A new {@code Expression} representing the number of milliseconds since epoch. + */ + export function timestampToUnixMillis( + fieldName: string, + ): FunctionExpression; + /** + * @beta + * Creates an expression that interprets an expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'seconds' field as seconds since epoch. + * unixSecondsToTimestamp(field("seconds")); + * ``` + * + * @param expr The expression representing the number of seconds since epoch. + * @returns A new {@code Expression} representing the timestamp. + */ + export function unixSecondsToTimestamp( + expr: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that interprets a field's value as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'seconds' field as seconds since epoch. + * unixSecondsToTimestamp("seconds"); + * ``` + * + * @param fieldName The name of the field representing the number of seconds since epoch. + * @returns A new {@code Expression} representing the timestamp. + */ + export function unixSecondsToTimestamp( + fieldName: string, + ): FunctionExpression; + /** + * @beta + * Creates an expression that converts a timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to seconds since epoch. + * timestampToUnixSeconds(field("timestamp")); + * ``` + * + * @param expr The expression representing the timestamp. + * @returns A new {@code Expression} representing the number of seconds since epoch. + */ + export function timestampToUnixSeconds( + expr: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that converts a timestamp field to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to seconds since epoch. + * timestampToUnixSeconds("timestamp"); + * ``` + * + * @param fieldName The name of the field representing the timestamp. + * @returns A new {@code Expression} representing the number of seconds since epoch. + */ + export function timestampToUnixSeconds( + fieldName: string, + ): FunctionExpression; + /** + * @beta + * Creates an expression that adds a specified amount of time to a timestamp. + * + * ```typescript + * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. + * timestampAdd(field("timestamp"), field("unit"), field("amount")); + * ``` + * + * @param timestamp The expression representing the timestamp. + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @returns A new {@code Expression} representing the resulting timestamp. + */ + export function timestampAdd( + timestamp: Expression, + unit: Expression, + amount: Expression, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that adds a specified amount of time to a timestamp. + * + * ```typescript + * // Add 1 day to the 'timestamp' field. + * timestampAdd(field("timestamp"), "day", 1); + * ``` + * + * @param timestamp The expression representing the timestamp. + * @param unit The unit of time to add: 'microsecond', 'millisecond', 'second', 'minute', 'hour', or 'day'. + * @param amount The amount of time to add. + * @returns A new {@code Expression} representing the resulting timestamp. + */ + export function timestampAdd( + timestamp: Expression, + unit: + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: number, + ): FunctionExpression; + /** + * @beta + * Creates an expression that adds a specified amount of time to a timestamp represented by a field. + * + * ```typescript + * // Add 1 day to the 'timestamp' field. + * timestampAdd("timestamp", "day", 1); + * ``` + * + * @param fieldName The name of the field representing the timestamp. + * @param unit The unit of time to add (e.g., "day", "hour"). + * @param amount The amount of time to add. + * @returns A new {@code Expression} representing the resulting timestamp. + */ + export function timestampAdd( + fieldName: string, + unit: + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: number, + ): FunctionExpression; + /** + * @beta + * Creates an expression that subtracts a specified amount of time from a timestamp. + * + * ```typescript + * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. + * timestampSubtract(field("timestamp"), field("unit"), field("amount")); + * ``` + * + * @param timestamp The expression representing the timestamp. + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @returns A new {@code Expression} representing the resulting timestamp. + */ + export function timestampSubtract( + timestamp: Expression, + unit: Expression, + amount: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that subtracts a specified amount of time from a timestamp. + * + * ```typescript + * // Subtract 1 day from the 'timestamp' field. + * timestampSubtract(field("timestamp"), "day", 1); + * ``` + * + * @param timestamp The expression representing the timestamp. + * @param unit The unit of time to subtract (e.g., "day", "hour"). + * @param amount The amount of time to subtract. + * @returns A new {@code Expression} representing the resulting timestamp. + */ + export function timestampSubtract( + timestamp: Expression, + unit: + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: number, + ): FunctionExpression; + /** + * @beta + * Creates an expression that subtracts a specified amount of time from a timestamp represented by a field. + * + * ```typescript + * // Subtract 1 day from the 'timestamp' field. + * timestampSubtract("timestamp", "day", 1); + * ``` + * + * @param fieldName The name of the field representing the timestamp. + * @param unit The unit of time to subtract (e.g., "day", "hour"). + * @param amount The amount of time to subtract. + * @returns A new {@code Expression} representing the resulting timestamp. + */ + export function timestampSubtract( + fieldName: string, + unit: + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: number, + ): FunctionExpression; + + /** + * @beta + * + * Creates an expression that evaluates to the current server timestamp. + * + * ```typescript + * // Get the current server timestamp + * currentTimestamp() + * ``` + * + * @returns A new Expression representing the current server timestamp. + */ + export function currentTimestamp(): FunctionExpression; + + /** + * @beta + * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. + * + * ```typescript + * // Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND + * // the 'status' field is "active" + * const condition = and(greaterThan("age", 18), equal("city", "London"), equal("status", "active")); + * ``` + * + * @param first The first filter condition. + * @param second The second filter condition. + * @param more Additional filter conditions to 'AND' together. + * @returns A new {@code Expression} representing the logical 'AND' operation. + */ + export function and( + first: BooleanExpression, + second: BooleanExpression, + ...more: BooleanExpression[] + ): BooleanExpression; + /** + * @beta + * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. + * + * ```typescript + * // Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR + * // the 'status' field is "active" + * const condition = or(greaterThan("age", 18), equal("city", "London"), equal("status", "active")); + * ``` + * + * @param first The first filter condition. + * @param second The second filter condition. + * @param more Additional filter conditions to 'OR' together. + * @returns A new {@code Expression} representing the logical 'OR' operation. + */ + export function or( + first: BooleanExpression, + second: BooleanExpression, + ...more: BooleanExpression[] + ): BooleanExpression; + /** + * @beta + * Creates an expression that returns the value of the base expression raised to the power of the exponent expression. + * + * ```typescript + * // Raise the value of the 'base' field to the power of the 'exponent' field. + * pow(field("base"), field("exponent")); + * ``` + * + * @param base The expression to raise to the power of the exponent. + * @param exponent The expression to raise the base to the power of. + * @returns A new `Expression` representing the power operation. + */ + export function pow( + base: Expression, + exponent: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that returns the value of the base expression raised to the power of the exponent. + * + * ```typescript + * // Raise the value of the 'base' field to the power of 2. + * pow(field("base"), 2); + * ``` + * + * @param base The expression to raise to the power of the exponent. + * @param exponent The constant value to raise the base to the power of. + * @returns A new `Expression` representing the power operation. + */ + export function pow(base: Expression, exponent: number): FunctionExpression; + /** + * @beta + * Creates an expression that returns the value of the base field raised to the power of the exponent expression. + * + * ```typescript + * // Raise the value of the 'base' field to the power of the 'exponent' field. + * pow("base", field("exponent")); + * ``` + * + * @param base The name of the field to raise to the power of the exponent. + * @param exponent The expression to raise the base to the power of. + * @returns A new `Expression` representing the power operation. + */ + export function pow(base: string, exponent: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that returns the value of the base field raised to the power of the exponent. + * + * ```typescript + * // Raise the value of the 'base' field to the power of 2. + * pow("base", 2); + * ``` + * + * @param base The name of the field to raise to the power of the exponent. + * @param exponent The constant value to raise the base to the power of. + * @returns A new `Expression` representing the power operation. + */ + export function pow(base: string, exponent: number): FunctionExpression; + /** + * @beta + * Creates an expression that returns the collection ID from a path. + * + * ```typescript + * // Get the collection ID from a path. + * collectionId(field("__name__")); + * ``` + * + * @param expression An expression evaluating to a path, which the collection ID will be extracted from. + * @returns A new {@code Expression} representing the collectionId operation. + */ + export function collectionId(expression: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that returns the collection ID from a path. + * + * ```typescript + * // Get the collection ID from a path. + * collectionId("__name__"); + * ``` + * + * @param fieldName The name of the field to get the collection ID from. + * @returns A new {@code Expression} representing the collectionId operation. + */ + export function collectionId(fieldName: string): FunctionExpression; + /** + * @beta + * Creates an expression that calculates the length of a string, array, map, vector, or bytes. + * + * ```typescript + * // Get the length of the 'name' field. + * length(field("name")); + * + * // Get the number of items in the 'cart' array. + * length(field("cart")); + * ``` + * + * @param expression An expression evaluating to a string, array, map, vector, or bytes, which the length will be calculated for. + * @returns A new `Expression` representing the length of the string, array, map, vector, or bytes. + */ + export function length(expression: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that calculates the length of a string, array, map, vector, or bytes. + * + * ```typescript + * // Get the length of the 'name' field. + * length("name"); + * + * // Get the number of items in the 'cart' array. + * length("cart"); + * ``` + * + * @param fieldName The name of the field to calculate the length of. + * @returns A new `Expression` representing the length of the string, array, map, vector, or bytes. + */ + export function length(fieldName: string): FunctionExpression; + /** + * @beta + * Creates an expression that reverses a string. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * stringReverse(field("myString")); + * ``` + * + * @param stringExpression An expression evaluating to a string value, which will be reversed. + * @returns A new {@code Expression} representing the reversed string. + */ + export function stringReverse( + stringExpression: Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that reverses a string value in the specified field. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * stringReverse("myString"); + * ``` + * + * @param field The name of the field representing the string to reverse. + * @returns A new {@code Expression} representing the reversed string. + */ + export function stringReverse(field: string): FunctionExpression; + + /** + * @beta + * Creates an expression that concatenates strings, arrays, or blobs. Types cannot be mixed. + * + * ```typescript + * // Concatenate the 'firstName' and 'lastName' fields with a space in between. + * concat(field("firstName"), " ", field("lastName")) + * ``` + * + * @param first The first expressions to concatenate. + * @param second The second literal or expression to concatenate. + * @param others Additional literals or expressions to concatenate. + * @returns A new `Expression` representing the concatenation. + */ + export function concat( + first: Expression, + second: Expression | unknown, + ...others: Array + ): FunctionExpression; + + /** + * @beta + * Creates an expression that computes the absolute value of a numeric value. + * + * @param expr The expression to compute the absolute value of. + * @returns A new {@code Expr} representing the absolute value of the numeric value. + */ + export function abs(expr: Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that returns the `elseExpr` argument if `ifExpr` is absent, else return + * the result of the `ifExpr` argument evaluation. + * + * ```typescript + * // Returns the value of the optional field 'optional_field', or returns 'default_value' + * // if the field is absent. + * ifAbsent(field("optional_field"), constant("default_value")) + * ``` + * + * @param ifExpr The expression to check for absence. + * @param elseExpr The expression that will be evaluated and returned if [ifExpr] is absent. + * @returns A new Expression representing the ifAbsent operation. + */ + export function ifAbsent( + ifExpr: Expression, + elseExpr: Expression, + ): Expression; + + /** + * @beta + * Creates an expression that returns the `elseValue` argument if `ifExpr` is absent, else + * return the result of the `ifExpr` argument evaluation. + * + * ```typescript + * // Returns the value of the optional field 'optional_field', or returns 'default_value' + * // if the field is absent. + * ifAbsent(field("optional_field"), "default_value") + * ``` + * + * @param ifExpr The expression to check for absence. + * @param elseValue The value that will be returned if `ifExpr` evaluates to an absent value. + * @returns A new [Expression] representing the ifAbsent operation. + */ + export function ifAbsent( + ifExpr: Expression, + elseValue: unknown, + ): Expression; + + /** + * @beta + * Creates an expression that returns the `elseExpr` argument if `ifFieldName` is absent, else + * return the value of the field. + * + * ```typescript + * // Returns the value of the optional field 'optional_field', or returns the value of + * // 'default_field' if 'optional_field' is absent. + * ifAbsent("optional_field", field("default_field")) + * ``` + * + * @param ifFieldName The field to check for absence. + * @param elseExpr The expression that will be evaluated and returned if `ifFieldName` is + * absent. + * @returns A new Expression representing the ifAbsent operation. + */ + export function ifAbsent( + ifFieldName: string, + elseExpr: Expression, + ): Expression; + + /** + * @beta + * Creates an expression that joins the elements of an array into a string. + * + * ```typescript + * // Join the elements of the 'tags' field with a comma and space. + * join("tags", ", ") + * ``` + * + * @param arrayFieldName The name of the field containing the array. + * @param delimiter The string to use as a delimiter. + * @returns A new Expression representing the join operation. + */ + export function join(arrayFieldName: string, delimiter: string): Expression; + + /** + * @beta + * Creates an expression that joins the elements of an array into a string. + * + * ```typescript + * // Join an array of string using the delimiter from the 'separator' field. + * join(array(['foo', 'bar']), field("separator")) + * ``` + * + * @param arrayExpression An expression that evaluates to an array. + * @param delimiterExpression The expression that evaluates to the delimiter string. + * @returns A new Expression representing the join operation. + */ + export function join( + arrayExpression: Expression, + delimiterExpression: Expression, + ): Expression; + + /** + * @beta + * Creates an expression that joins the elements of an array into a string. + * + * ```typescript + * // Join the elements of the 'tags' field with a comma and space. + * join(field("tags"), ", ") + * ``` + * + * @param arrayExpression An expression that evaluates to an array. + * @param delimiter The string to use as a delimiter. + * @returns A new Expression representing the join operation. + */ + export function join( + arrayExpression: Expression, + delimiter: string, + ): Expression; + + /** + * @beta + * Creates an expression that computes the base-10 logarithm of a numeric value. + * + * ```typescript + * // Compute the base-10 logarithm of the 'value' field. + * log10("value"); + * ``` + * + * @param fieldName The name of the field to compute the base-10 logarithm of. + * @returns A new `Expr` representing the base-10 logarithm of the numeric value. + */ + export function log10(fieldName: string): FunctionExpression; + + /** + * @beta + * Creates an expression that computes the base-10 logarithm of a numeric value. + * + * ```typescript + * // Compute the base-10 logarithm of the 'value' field. + * log10(field("value")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the base-10 logarithm will be computed for. + * @returns A new `Expr` representing the base-10 logarithm of the numeric value. + */ + export function log10(expression: Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that computes the sum of the elements in an array. + * + * ```typescript + * // Compute the sum of the elements in the 'scores' field. + * arraySum("scores"); + * ``` + * + * @param fieldName The name of the field to compute the sum of. + * @returns A new `Expr` representing the sum of the elements in the array. + */ + export function arraySum(fieldName: string): FunctionExpression; + + /** + * @beta + * Creates an expression that computes the sum of the elements in an array. + * + * ```typescript + * // Compute the sum of the elements in the 'scores' field. + * arraySum(field("scores")); + * ``` + * + * @param expression An expression evaluating to a numeric array, which the sum will be computed for. + * @returns A new `Expr` representing the sum of the elements in the array. + */ + export function arraySum(expression: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that computes the natural logarithm of a numeric value. + * + * ```typescript + * // Compute the natural logarithm of the 'value' field. + * ln(field("value")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the natural logarithm will be computed for. + * @returns A new {@code Expression} representing the natural logarithm of the numeric value. + */ + export function ln(expression: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that computes the natural logarithm of a numeric value. + * + * ```typescript + * // Compute the natural logarithm of the 'value' field. + * ln("value"); + * ``` + * + * @param fieldName The name of the field to compute the natural logarithm of. + * @returns A new {@code Expression} representing the natural logarithm of the numeric value. + */ + export function ln(fieldName: string): FunctionExpression; + /** + * @beta + * Creates an expression that generates a random number between 0.0 and 1.0 but not including 1.0. + * + * @example + * ```typescript + * // Generate a random number between 0.0 and 1.0. + * rand(); + * ``` + * + * @returns A new {@code Expression} representing the rand operation. + */ + export function rand(): FunctionExpression; + /** + * @beta + * Creates an expression that rounds a numeric value to the nearest whole number. + * + * ```typescript + * // Round the value of the 'price' field. + * round(field("price")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which will be rounded. + * @returns A new `Expression` representing the rounded value. + */ + export function round(expression: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that rounds a numeric value to the nearest whole number. + * + * ```typescript + * // Round the value of the 'price' field. + * round("price"); + * ``` + * + * @param fieldName The name of the field to round. + * @returns A new `Expression` representing the rounded value. + */ + export function round(fieldName: string): FunctionExpression; + /** + * @beta + * Creates an expression that rounds a numeric value to the specified number of decimal places. + * + * ```typescript + * // Round the value of the 'price' field to two decimal places. + * round("price", 2); + * ``` + * + * @param fieldName The name of the field to round. + * @param decimalPlaces A constant or expression specifying the rounding precision in decimal places. + * @returns A new `Expr` representing the rounded value. + */ + export function round( + fieldName: string, + decimalPlaces: number | Expression, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that rounds a numeric value to the specified number of decimal places. + * + * ```typescript + * // Round the value of the 'price' field to two decimal places. + * round(field("price"), constant(2)); + * ``` + * + * @param expression An expression evaluating to a numeric value, which will be rounded. + * @param decimalPlaces A constant or expression specifying the rounding precision in decimal places. + * @returns A new `Expr` representing the rounded value. + */ + export function round( + expression: Expression, + decimalPlaces: number | Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that truncates the numeric value of a field to an integer. + * + * @example + * ```typescript + * // Truncate the value of the 'rating' field. + * trunc("rating"); + * ``` + * + * @param fieldName The name of the field containing the number to truncate. + * @returns A new {@code Expression} representing the truncated value. + */ + export function trunc(fieldName: string): FunctionExpression; + /** + * @beta + * Creates an expression that truncates the numeric value of an expression to an integer. + * + * @example + * ```typescript + * // Truncate the value of the 'rating' field. + * trunc(field("rating")); + * ``` + * + * @param expression - An expression evaluating to a numeric value, which will be truncated. + * @returns A new {@code Expression} representing the truncated value. + */ + export function trunc(expression: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that truncates a numeric value to the specified number of decimal places. + * + * @example + * ```typescript + * // Truncate the value of the 'rating' field to two decimal places. + * trunc("rating", 2); + * ``` + * + * @param fieldName The name of the field to truncate. + * @param decimalPlaces A constant or expression specifying the truncation precision in decimal places. + * @returns A new {@code Expression} representing the truncated value. + */ + export function trunc( + fieldName: string, + decimalPlaces: number | Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that truncates a numeric value to the specified number of decimal places. + * + * @example + * ```typescript + * // Truncate the value of the 'rating' field to two decimal places. + * trunc(field("rating"), constant(2)); + * ``` + * + * @param expression - An expression evaluating to a numeric value, which will be truncated. + * @param decimalPlaces - A constant or expression specifying the truncation precision in decimal places. + * @returns A new {@code Expression} representing the truncated value. + */ + export function trunc( + expression: Expression, + decimalPlaces: number | Expression, + ): FunctionExpression; + /** + * @beta + * Creates an expression that computes the square root of a numeric value. + * + * ```typescript + * // Compute the square root of the 'value' field. + * sqrt(field("value")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the square root will be computed for. + * @returns A new {@code Expression} representing the square root of the numeric value. + */ + export function sqrt(expression: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that computes the square root of a numeric value. + * + * ```typescript + * // Compute the square root of the 'value' field. + * sqrt("value"); + * ``` + * + * @param fieldName The name of the field to compute the square root of. + * @returns A new {@code Expression} representing the square root of the numeric value. + */ + export function sqrt(fieldName: string): FunctionExpression; + /** + * @beta + * Creates an expression that splits the value of a field on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scoresCsv' field on delimiter ',' + * split('scoresCsv', ',') + * ``` + * + * @param fieldName Split the value in this field. + * @param delimiter Split on this delimiter. + * + * @returns A new {@code Expression} representing the split function. + */ + export function split( + fieldName: string, + delimiter: string, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that splits the value of a field on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format + * split('scores', conditional(field('format').equal('csv'), constant(','), constant(':')) + * ``` + * + * @param fieldName Split the value in this field. + * @param delimiter Split on this delimiter returned by evaluating this expression. + * + * @returns A new {@code Expression} representing the split function. + */ + export function split( + fieldName: string, + delimiter: Expression, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that splits a string into an array of substrings based on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scoresCsv' field on delimiter ',' + * split(field('scoresCsv'), ',') + * ``` + * + * @param expression Split the result of this expression. + * @param delimiter Split on this delimiter. + * + * @returns A new {@code Expression} representing the split function. + */ + export function split( + expression: Expression, + delimiter: string, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that splits a string into an array of substrings based on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format + * split(field('scores'), conditional(field('format').equal('csv'), constant(','), constant(':')) + * ``` + * + * @param expression Split the result of this expression. + * @param delimiter Split on this delimiter returned by evaluating this expression. + * + * @returns A new {@code Expression} representing the split function. + */ + export function split( + expression: Expression, + delimiter: Expression, + ): FunctionExpression; + + /** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the beginning of the day. + * field('createdAt').timestampTruncate('day') + * ``` + * + * @param fieldName Truncate the timestamp value contained in this field. + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @returns A new {Expression} representing the truncated timestamp. + */ + export function timestampTruncate( + fieldName: string, + granularity: TimeGranularity, + timezone?: string | Expression, + ): FunctionExpression; + + /** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'. + * field('createdAt').timestampTruncate(field('granularity')) + * ``` + * + * @param fieldName Truncate the timestamp value contained in this field. + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @returns A new {Expression} representing the truncated timestamp. + */ + export function timestampTruncate( + fieldName: string, + granularity: Expression, + timezone?: string | Expression, + ): FunctionExpression; + + /** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the beginning of the day. + * field('createdAt').timestampTruncate('day') + * ``` + * + * @param timestampExpression Truncate the timestamp value that is returned by this expression. + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @returns A new {Expression} representing the truncated timestamp. + */ + export function timestampTruncate( + timestampExpression: Expression, + granularity: TimeGranularity, + timezone?: string | Expression, + ): FunctionExpression; + + /** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'. + * field('createdAt').timestampTruncate(field('granularity')) + * ``` + * + * @param timestampExpression Truncate the timestamp value that is returned by this expression. + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @returns A new {Expression} representing the truncated timestamp. + */ + export function timestampTruncate( + timestampExpression: Expression, + granularity: Expression, + timezone?: string | Expression, + ): FunctionExpression; + + /** + * @beta + * + * An enumeration of the different types generated by the Firestore backend. + * + *
    + *
  • Numerics evaluate directly to backend representation (`int64` or `float64`), not JS `number`.
  • + *
  • JavaScript `Date` and firestore `Timestamp` objects strictly evaluate to `'timestamp'`.
  • + *
  • Advanced configurations parsing backend types (such as `decimal128`, `max_key` or `min_key` from BSON) are also incorporated in this union string type. Note that `decimal128` is a backend-only numeric type that the JavaScript SDK cannot create natively, but can be evaluated in pipelines.
  • + *
+ */ + export type Type = + | 'null' + | 'array' + | 'boolean' + | 'bytes' + | 'timestamp' + | 'geo_point' + | 'number' + | 'int32' + | 'int64' + | 'float64' + | 'decimal128' + | 'map' + | 'reference' + | 'string' + | 'vector' + | 'max_key' + | 'min_key' + | 'object_id' + | 'regex' + | 'request_timestamp'; + + /** + * @beta + * Creates an expression that returns the data type of the data in the specified field. + * + * @example + * ```typescript + * // Get the data type of the value in field 'title' + * type('title') + * ``` + * + * @returns A new {Expression} representing the data type. + */ + export function type(fieldName: string): FunctionExpression; + /** + * @beta + * Creates an expression that returns the data type of an expression's result. + * + * @example + * ```typescript + * // Get the data type of a conditional expression + * type(conditional(exists('foo'), constant(1), constant(true))) + * ``` + * + * @returns A new {Expression} representing the data type. + */ + export function type(expression: Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that checks if the value in the specified field is of the given type. + * + * @remarks Null or undefined fields evaluate to skip/error. Use `ifAbsent()` / `isAbsent()` to evaluate missing data. + * + * @example + * ```typescript + * // Check if the 'price' field is a floating point number (evaluating to true inside pipeline conditionals) + * isType('price', 'float64'); + * ``` + * + * @param fieldName The name of the field to check. + * @param type The type to check for. + * @returns A new `BooleanExpression` that evaluates to true if the field's value is of the given type, false otherwise. + */ + export function isType(fieldName: string, type: Type): BooleanExpression; + /** + * @beta + * Creates an expression that checks if the result of an expression is of the given type. + * + * @remarks Null or undefined fields evaluate to skip/error. Use `ifAbsent()` / `isAbsent()` to evaluate missing data. + * + * @example + * ```typescript + * // Check if the result of a calculation is a number + * isType(add('count', 1), 'number') + * ``` + * + * @param expression The expression to check. + * @param type The type to check for. + * @returns A new `BooleanExpression` that evaluates to true if the expression's result is of the given type, false otherwise. + */ + export function isType( + expression: Expression, + type: Type, + ): BooleanExpression; + + // TODO(new-expression): Add new top-level expression function declarations above this line + /** + * @beta + * Creates an `Ordering` that sorts documents in ascending order based on an expression. + * + * ```typescript + * // Sort documents by the 'name' field in lowercase in ascending order + * pipeline().collection("users") + * .sort(ascending(field("name").toLower())); + * ``` + * + * @param expr The expression to create an ascending ordering for. + * @returns A new `Ordering` for ascending sorting. + */ + export function ascending(expr: Expression): Ordering; + /** + * @beta + * Creates an `Ordering` that sorts documents in ascending order based on a field. + * + * ```typescript + * // Sort documents by the 'name' field in ascending order + * pipeline().collection("users") + * .sort(ascending("name")); + * ``` + * + * @param fieldName The field to create an ascending ordering for. + * @returns A new `Ordering` for ascending sorting. + */ + export function ascending(fieldName: string): Ordering; + /** + * @beta + * Creates an `Ordering` that sorts documents in descending order based on an expression. + * + * ```typescript + * // Sort documents by the 'name' field in lowercase in descending order + * pipeline().collection("users") + * .sort(descending(field("name").toLower())); + * ``` + * + * @param expr The expression to create a descending ordering for. + * @returns A new `Ordering` for descending sorting. + */ + export function descending(expr: Expression): Ordering; + /** + * @beta + * Creates an `Ordering` that sorts documents in descending order based on a field. + * + * ```typescript + * // Sort documents by the 'name' field in descending order + * pipeline().collection("users") + * .sort(descending("name")); + * ``` + * + * @param fieldName The field to create a descending ordering for. + * @returns A new `Ordering` for descending sorting. + */ + export function descending(fieldName: string): Ordering; + /** + * @beta + * Represents an ordering criterion for sorting documents in a Firestore pipeline. + * + * You create `Ordering` instances using the `ascending` and `descending` helper functions. + */ + export class Ordering { + readonly expr: Expression; + readonly direction: 'ascending' | 'descending'; + } + + /** + * @beta + * Provides the entry point for defining the data source of a Firestore `Pipeline`. + * + * Use the methods of this class (e.g., {@link PipelineSource#collection}, {@link PipelineSource#collectionGroup}, + * {@link PipelineSource#database}, or {@link PipelineSource#documents}) to specify the initial data + * for your pipeline, such as a collection, a collection group, the entire database, or a set of specific documents. + */ + export class PipelineSource { + /** + * @beta + * Specifies the source for a new pipeline as a Firestore collection. + * This method allows you to start a data pipeline by defining the collection + * from which documents will be read. + * + * @param collectionPath The path to the collection as a string (e.g., 'users/alovelace/chats') + * or a {@link CollectionReference} object. + * @returns A new `Pipeline` object configured to read from the specified collection. + * + * @example + * ```typescript + * // Using a string path + * const pipeline1 = firestore.pipeline().collection('myCollection'); + * + * // Using a CollectionReference + * const collectionRef = firestore.collection('anotherCollection'); + * const pipeline2 = firestore.pipeline().collection(collectionRef); + * ``` + */ + collection(collectionPath: string | CollectionReference): Pipeline; + /** + * @beta + * Returns all documents from the entire collection. The collection can be nested. + * @param options - Options defining how this CollectionStage is evaluated. + */ + collection(options: CollectionStageOptions): Pipeline; + /** + * @beta + * Specifies the source as a collection group. + * + * @param collectionId The ID of the collection group. + * @returns A new Pipeline object with the collection group as the source. + */ + collectionGroup(collectionId: string): Pipeline; + + /** + * @beta + * Creates a new `Pipeline` stage that queries all documents belonging to a collection + * with the ID specified in the provided `options`, regardless of the document's parent. + * + * A collection group query can be used to query collections that have the same ID but + * are located at different paths. + * + * ```typescript + * // Query all 'cities' collections regardless of their parent document. + * const citiesPipeline = firestore.collectionGroup({ collectionId: 'cities' }); + * ``` + * + * @param options Options defining how this CollectionGroupStage is evaluated, including the `collectionId`. + * @returns A new `Pipeline` instance representing the collection group stage. + */ + collectionGroup(options: CollectionGroupStageOptions): Pipeline; + /** + * @beta + * Specifies the source as a database. + * + * @returns A new Pipeline object with the database as the source. + */ + database(): Pipeline; + /** + * @beta + * Returns all documents from the entire database. + * @param options - Options defining how a DatabaseStage is evaluated. + */ + database(options: DatabaseStageOptions): Pipeline; + /** + * @beta + * Specifies the source as a set of documents. + * + * @param docs The document references. + * @returns A new Pipeline object with the documents as the source. + */ + documents(docs: Array): Pipeline; + /** + * @beta + * Set the pipeline's source to the documents specified by the given paths and DocumentReferences. + * + * @param options - Options defining how this DocumentsStage is evaluated. + * + * @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. + */ + documents(options: DocumentsStageOptions): Pipeline; + /** + * @beta + * Convert the given Query into an equivalent Pipeline. + * + * @param query A Query to be converted into a Pipeline. + * + * @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. + */ + createFrom(query: Query): Pipeline; + } + /** + * @beta + * The Pipeline class provides a flexible and expressive framework for building complex data + * transformation and query pipelines for Firestore. + * + * A pipeline takes data sources, such as Firestore collections or collection groups, and applies + * a series of stages that are chained together. Each stage takes the output from the previous stage + * (or the data source) and produces an output for the next stage (or as the final output of the + * pipeline). + * + * Expressions can be used within each stage to filter and transform data through the stage. + * + * NOTE: The chained stages do not prescribe exactly how Firestore will execute the pipeline. + * Instead, Firestore only guarantees that the result is the same as if the chained stages were + * executed in order. + * + * Usage Examples: + * + * ```typescript + * const db: Firestore; // Assumes a valid firestore instance. + * + * // Example 1: Select specific fields and rename 'rating' to 'bookRating' + * const results1 = await db.pipeline() + * .collection("books") + * .select("title", "author", Field.of("rating").as("bookRating")) + * .execute(); + * + * // Example 2: Filter documents where 'genre' is "Science Fiction" and 'published' is after 1950 + * const results2 = await db.pipeline() + * .collection("books") + * .where(and(Field.of("genre").equal("Science Fiction"), Field.of("published").greaterThan(1950))) + * .execute(); + * + * // Example 3: Calculate the average rating of books published after 1980 + * const results3 = await db.pipeline() + * .collection("books") + * .where(Field.of("published").greaterThan(1980)) + * .aggregate(average(Field.of("rating")).as("averageRating")) + * .execute(); + * ``` + */ + export class Pipeline { + /** + * @beta + * Adds new fields to outputs from previous stages. + * + * This stage allows you to compute values on-the-fly based on existing data from previous + * stages or constants. You can use this to create new fields or overwrite existing ones (if there + * is name overlaps). + * + * The added fields are defined using `Selectable`s, which can be: + * + * - `Field`: References an existing document field. + * - `Expression`: Either a literal value (see {@link constant}) or a computed value + * (see {@FunctionExpression}) with an assigned alias using {@link Expression#as}. + * + * + * ```typescript + * firestore.pipeline().collection("books") + * .addFields( + * field("rating").as("bookRating"), // Rename 'rating' to 'bookRating' + * add(5, field("quantity")).as("totalCost") // Calculate 'totalCost' + * ); + * ``` + * + * @param field The first field to add to the documents, specified as a `Selectable`. + * @param additionalFields Optional additional fields to add to the documents, specified as `Selectable`s. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + addFields(field: Selectable, ...additionalFields: Selectable[]): Pipeline; + /** + * @beta + * Adds new fields to outputs from previous stages. + * + * This stage allows you to compute values on-the-fly based on existing data from previous + * stages or constants. You can use this to create new fields or overwrite existing ones (if there + * is name overlaps). + * + * The added fields are defined using `Selectable`s, which can be: + * + * - `Field`: References an existing document field. + * - `Expression`: Either a literal value (see {@link constant}) or a computed value + * (see {@FunctionExpression}) with an assigned alias using {@link Expression#as}. + * + * + * ```typescript + * firestore.pipeline().collection("books") + * .addFields( + * field("rating").as("bookRating"), // Rename 'rating' to 'bookRating' + * add(5, field("quantity")).as("totalCost") // Calculate 'totalCost' + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + addFields(options: AddFieldsStageOptions): Pipeline; + /** + * @beta + * Remove fields from outputs of previous stages. + * + * + * ```typescript + * firestore.pipeline().collection('books') + * // removes field 'rating' and 'cost' from the previous stage outputs. + * .removeFields( + * field('rating'), + * 'cost' + * ); + * ``` + * + * @param fieldValue The first field to remove. + * @param additionalFields Optional additional fields to remove. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + removeFields( + fieldValue: Field | string, + ...additionalFields: Array + ): Pipeline; + + /** + * @beta + * Creates a stage that removes specified fields from the outputs of previous stages in the pipeline. + * + * This is useful for reducing the data transferred, by excluding fields + * that are no longer needed after certain pipeline operations. + * + * + * ```typescript + * firestore.pipeline().collection('books') + * // Removes the 'rating' and 'cost' fields from the documents + * // processed by the preceding stages. + * .removeFields({ + * fields: [ + * field('rating'), + * 'cost' + * ] + * }); + * ``` + * + * @param options - An object containing the configuration for this stage. + * @param options.fields - An array of field names (strings) or `Expression` objects + * representing the fields to be removed from the output. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + removeFields(options: RemoveFieldsStageOptions): Pipeline; + + /** + * @beta + * Selects or creates a set of fields from the outputs of previous stages. + * + *

The selected fields are defined using `Selectable` expressions, which can be: + * + *

    + *
  • {@code string}: The name of an existing field.
  • + *
  • `Field`: A reference to an existing field.
  • + *
  • `Expression`: An expression (e.g., a {@link FunctionExpression}) that represents the result of an expression., + * The Expression must be aliased using {@link Expression#as}.
  • + *
+ * + * + * ```typescript + * firestore.pipeline().collection("books") + * .select( + * "firstName", + * field("lastName"), + * field("address").toUppercase().as("upperAddress"), + * ); + * ``` + * + * @param selection The first field to include in the output documents, specified as a {@link + * Pipelines.Selectable} expression or a string value representing the field name. + * @param additionalSelections Optional additional fields to include in the output documents, specified as {@link + * Pipelines.Selectable} expressions or {@code string} values representing field names. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + select( + selection: Selectable | string, + ...additionalSelections: Array + ): Pipeline; + + /** + * @beta + * Selects or creates a set of fields from the outputs of previous stages. + * + *

The selected fields are defined using `Selectable` expressions, which can be: + * + *

    + *
  • {@code string}: The name of an existing field.
  • + *
  • `Field`: A reference to an existing field.
  • + *
  • `Expression`: An expression (e.g., a {@link FunctionExpression}) that represents the result of an expression., + * The Expression must be aliased using {@link Expression#as}.
  • + *
+ * + * If no selections are provided within the `options` (i.e., the `fields` array is empty), + * the output of this stage will be an empty document. If the intention is to add new fields + * without replacing existing ones, consider using {@link Pipeline#addFields} instead. + * + * + * ```typescript + * db.pipeline().collection("books") + * .select({ + * fields: [ + * "firstName", + * field("lastName"), + * field("address").toUppercase().as("upperAddress"), + * ] + * }); + * ``` + * + * @param options An object of type {@link SelectStageOptions} that defines the selection criteria for this stage. + * It is expected to contain a `fields` property, which is an array of `Selectable` expressions. + * @returns A new `Pipeline` object with this select stage appended to its list of stages. + */ + select(options: SelectStageOptions): Pipeline; + /** + * @beta + * Filters the documents from previous stages to only include those matching the specified {@link + * BooleanExpression}. + * + *

This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. + * You can filter documents based on their field values, using implementations of {@link + * BooleanExpression}, typically including but not limited to: + * + *

    + *
  • field comparators: {@link Function#equal}, {@link Function#lessThan} (less than), {@link + * Function#greaterThan} (greater than), etc.
  • + *
  • logical operators: {@link Function#and}, {@link Function#or}, {@link Function#not}, etc.
  • + *
  • advanced functions: {@link Function#regexMatch}, {@link + * Function#arrayContains}, etc.
  • + *
+ * + * + * ```typescript + * firestore.pipeline().collection("books") + * .where( + * and( + * greaterThan(field("rating"), 4.0), // Filter for ratings greater than 4.0 + * field("genre").equal("Science Fiction") // Equivalent to greaterThan("genre", "Science Fiction") + * ) + * ); + * ``` + * + * @param condition The `BooleanExpression` to apply. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + where(condition: BooleanExpression): Pipeline; + /** + * @beta + * Filters the documents from previous stages to only include those matching the specified {@link + * BooleanExpression}. + * + *

This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. + * You can filter documents based on their field values, using implementations of {@link + * BooleanExpression}, typically including but not limited to: + * + *

    + *
  • field comparators: {@link Function#equal}, {@link Function#lessThan} (less than), {@link + * Function#greaterThan} (greater than), etc.
  • + *
  • logical operators: {@link Function#and}, {@link Function#or}, {@link Function#not}, etc.
  • + *
  • advanced functions: {@link Function#regexMatch}, {@link + * Function#arrayContains}, etc.
  • + *
+ * + * + * ```typescript + * firestore.pipeline().collection("books") + * .where({ + * filter: and( + * greaterThan(field("rating"), 4.0), // Filter for ratings greater than 4.0 + * field("genre").equal("Science Fiction") // Equivalent to greaterThan("genre", "Science Fiction") + * ) + * }); + * ``` + * + * @param options An object that specifies the filtering criteria. It is expected to contain a `filter` property of type `BooleanExpression`. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + where(options: WhereStageOptions): Pipeline; + /** + * @beta + * Skips the first `offset` number of documents from the results of previous stages. + * + *

This stage is useful for implementing pagination in your pipelines, allowing you to retrieve + * results in chunks. It is typically used in conjunction with `limit` to control the + * size of each page. + * + * + * ```typescript + * // Retrieve the second page of 20 results + * firestore.pipeline().collection("books") + * .sort(Field.of("published").descending()) + * .offset(20) // Skip the first 20 results + * .limit(20); // Take the next 20 results + * ``` + * + * @param offset The number of documents to skip. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + offset(offset: number): Pipeline; + + /** + * @beta + * Skips a specified number of documents from the results of previous stages. + * + * This stage is useful for implementing pagination in your pipelines, enabling you to + * retrieve results in manageable chunks. It is commonly used alongside {@link Pipeline.limit} + * to define the size of each page. + * + * ```typescript + * // Retrieve the second page of 20 results + * firestore.pipeline().collection('books') + * .sort(field('published').descending()) + * .offset(20) // Skip the first 20 results + * .limit(20); // Take the next 20 results + * ``` + * + * @param options An object containing the configuration for the offset stage, + * including the number of documents to skip. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + offset(options: OffsetStageOptions): Pipeline; + /** + * @beta + * Limits the maximum number of documents returned by previous stages to `limit`. + * + *

This stage is particularly useful when you want to retrieve a controlled subset of data from + * a potentially large result set. It's often used for: + * + *

    + *
  • **Pagination:** In combination with `offset` to retrieve specific pages of + * results.
  • + *
  • **Limiting Data Retrieval:** To prevent excessive data transfer and improve performance, + * especially when dealing with large collections.
  • + *
+ * + * + * ```typescript + * // Limit the results to the top 10 highest-rated books + * firestore.pipeline().collection("books") + * .sort(Field.of("rating").descending()) + * .limit(10); + * ``` + * + * @param limit The maximum number of documents to return. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + limit(limit: number): Pipeline; + + /** + * @beta + * Limits the maximum number of documents returned by previous stages. + * + *

This stage is particularly useful when you want to retrieve a controlled subset of data from + * a potentially large result set. It's often used for: + * + *

    + *
  • Pagination: In combination with `offset` to retrieve specific pages of + * results.
  • + *
  • Limiting Data Retrieval: To prevent excessive data transfer and improve performance, + * especially when dealing with large collections.
  • + *
+ * + * + * ```typescript + * // Limit the results to the top 10 highest-rated books + * firestore.pipeline().collection('books') + * .sort(field('rating').descending()) + * .limit({ limit: 10 }); + * ``` + * + * @param options - An object that specifies the limit. It must contain a `limit` property, which is a number representing the maximum number of documents to return. + * @returns A new `Pipeline` object with this stage appended to the stage list. + */ + limit(options: LimitStageOptions): Pipeline; + /** + * @beta + * Returns a set of distinct values from the inputs to this stage. + * + * This stage runs through the results from previous stages to include only results with + * unique combinations of `Expression` values. + * + * The parameters to this stage are defined using `Selectable` expressions or strings: + * + * - {@code string}: Name of an existing field + * - `Field`: References an existing document field. + * - `AliasedExpression`: Represents the result of a function with an assigned alias name + * using {@link Expression#as}. + * + * + * ```typescript + * // Get a list of unique author names in uppercase and genre combinations. + * firestore.pipeline().collection("books") + * .distinct(toUppercase(field("author")).as("authorName"), field("genre"), "publishedAt") + * .select("authorName"); + * ``` + * + * @param group The `Selectable` expression or field name to consider when determining + * distinct value combinations. + * @param additionalGroups Optional additional `Selectable` expressions to consider when determining distinct + * value combinations or strings representing field names. + * @returns A new {@code Pipeline} object with this stage appended to the stage list. + */ + distinct( + group: string | Selectable, + ...additionalGroups: Array + ): Pipeline; + /** + * @beta + * Returns a set of distinct values from the inputs to this stage. + * + * This stage runs through the results from previous stages to include only results with + * unique combinations of `Expression` values (`Field`, {@link Function}, etc). + * + * The parameters to this stage are defined using `Selectable` expressions or strings: + * + * - {@code string}: Name of an existing field + * - `Field`: References an existing document field. + * - `AliasedExpression`: Represents the result of a function with an assigned alias name + * using {@link Expression#as}. + * + * + * ```typescript + * // Get a list of unique author names in uppercase and genre combinations. + * firestore.pipeline().collection("books") + * .distinct(toUppercase(field("author")).as("authorName"), field("genre"), "publishedAt") + * .select("authorName"); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new {@code Pipeline} object with this stage appended to the stage list. + */ + distinct(options: DistinctStageOptions): Pipeline; + /** + * @beta + * Performs aggregation operations on the documents from previous stages. + * + *

This stage allows you to calculate aggregate values over a set of documents. You define the + * aggregations to perform using `AliasedAggregate` expressions which are typically results of + * calling {@link Expression#as} on `AggregateFunction` instances. + * + * + * ```typescript + * // Calculate the average rating and the total number of books + * firestore.pipeline().collection("books") + * .aggregate( + * field("rating").average().as("averageRating"), + * countAll().as("totalBooks") + * ); + * ``` + * + * @param accumulator The first `AliasedAggregate`, wrapping an `AggregateFunction` + * and providing a name for the accumulated results. + * @param additionalAccumulators Optional additional `AliasedAggregate`, each wrapping an `AggregateFunction` + * and providing a name for the accumulated results. + * @returns A new Pipeline object with this stage appended to the stage list. + */ + aggregate( + accumulator: AliasedAggregate, + ...additionalAccumulators: AliasedAggregate[] + ): Pipeline; + /** + * @beta + * Performs optionally grouped aggregation operations on the documents from previous stages. + * + *

This stage allows you to calculate aggregate values over a set of documents, optionally + * grouped by one or more fields or functions. You can specify: + * + *

    + *
  • **Grouping Fields or Functions:** One or more fields or functions to group the documents + * by. For each distinct combination of values in these fields, a separate group is created. + * If no grouping fields are provided, a single group containing all documents is used. Not + * specifying groups is the same as putting the entire inputs into one group.
  • + *
  • **Accumulators:** One or more accumulation operations to perform within each group. These + * are defined using `AliasedAggregate` expressions, which are typically created by + * calling {@link Expression#as} on `AggregateFunction` instances. Each aggregation + * calculates a value (e.g., sum, average, count) based on the documents within its group.
  • + *
+ * + * + * ```typescript + * // Calculate the average rating for each genre. + * firestore.pipeline().collection("books") + * .aggregate({ + * accumulators: [average(field("rating")).as("avg_rating")] + * groups: ["genre"] + * }); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new {@code Pipeline} object with this stage appended to the stage + * list. + */ + aggregate(options: AggregateStageOptions): Pipeline; + /** + * @beta + * Performs a vector proximity search on the documents from the previous stage, returning the + * K-nearest documents based on the specified query `vectorValue` and `distanceMeasure`. The + * returned documents will be sorted in order from nearest to furthest from the query `vectorValue`. + * + * + * ```typescript + * // Find the 10 most similar books based on the book description. + * const bookDescription = "Lorem ipsum..."; + * const queryVector: number[] = ...; // compute embedding of `bookDescription` + * + * firestore.pipeline().collection("books") + * .findNearest({ + * field: 'embedding', + * vectorValue: queryVector, + * distanceMeasure: 'euclidean', + * limit: 10, // optional + * distanceField: 'computedDistance' // optional + * }); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new {@code Pipeline} object with this stage appended to the stage list. + */ + findNearest(options: FindNearestStageOptions): Pipeline; + + /** + * @beta + * Fully overwrites all fields in a document with those coming from a nested map. + * + *

This stage allows you to emit a map value as a document. Each key of the map becomes a field + * on the document that contains the corresponding value. + * + * + * ```typescript + * // Input. + * // { + * // 'name': 'John Doe Jr.', + * // 'parents': { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * // } + * + * // Emit parents as document. + * firestore.pipeline().collection('people').replaceWith('parents'); + * + * // Output + * // { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * ``` + * + * @param fieldName The name of the field containing the nested map. + * @returns A new {@code Pipeline} object with this stage appended to the stage list. + */ + replaceWith(fieldName: string): Pipeline; + + /** + * @beta + * Fully replaces all fields in a document with the fields from a map expression. + * + *

This stage allows you to transform the current document into a new one + * by providing an `Expression` that evaluates to a map. Each key-value pair + * in the resulting map will become a field-value pair in the document. + * + * + * ```typescript + * // Input document: + * // { + * // 'firstName': 'John', + * // 'lastName': 'Doe', + * // 'age': 30 + * // } + * + * // Replace the document's fields with a new map. + * // The 'fullName' field will be created by concatenating 'firstName' and 'lastName'. + * // The 'status' field will be a new static value. + * firestore.pipeline().collection('users').replaceWith(map({ + * fullName: concat(field('firstName'), ' ', field('lastName')), + * status: 'active' + * })); + * + * // Output document: + * // { + * // 'fullName': 'John Doe', + * // 'status': 'active' + * // } + * ``` + * + * @param expr An `Expression` that evaluates to a map. The key-value pairs of this map will replace the document's fields. + * @returns A new {@code Pipeline} object with this stage appended to the stage list. + */ + replaceWith(expr: Expression): Pipeline; + + /** + * @beta + * Fully overwrites all fields in a document with those coming from a map. + * + *

This stage allows you to transform the current document into a new one + * by defining its new structure using a map expression. Each key in the + * provided map expression becomes a field in the new document, with its + * corresponding value. Values within the map can be literal values or + * expressions that refer to fields from the input document. + * + * + * ```typescript + * // Input document: + * // { + * // 'productId': 'P123', + * // 'itemName': 'Laptop', + * // 'price': 1200, + * // 'details': { + * // 'weight': '2kg', + * // 'color': 'silver' + * // } + * // } + * + * // Replace the document with a new structure, selecting and renaming fields, + * // and adding new literal values. + * firestore.pipeline().collection('products').replaceWith(map({ + * id: field('productId'), + * productName: field('itemName'), + * displayPrice: concat('$', field('price')), + * category: 'Electronics', + * weightInKg: field('details.weight') + * })); + * + * // Output document: + * // { + * // 'id': 'P123', + * // 'productName': 'Laptop', + * // 'displayPrice': '$1200', + * // 'category': 'Electronics', + * // 'weightInKg': '2kg' + * // } + * ``` + * + * @param options - An object that specifies the map expression to use for replacement. + * @returns A new {@code Pipeline} object with this stage appended to the stage list. + */ + replaceWith(options: ReplaceWithStageOptions): Pipeline; + + /** + * @beta + * Performs a pseudo-random sampling of documents from the previous stage in the pipeline. + * + * This stage filters documents pseudo-randomly, returning a specified number of documents. + * + * Examples: + * + * ```typescript + * // Sample 25 books, if available. + * firestore.pipeline().collection('books') + * .sample(25); + * ``` + * + * @param documents The maximum number of documents to sample. + * @returns A new {@code Pipeline} object with this stage appended to the stage list. + */ + sample(documents: number): Pipeline; + /** + * @beta + * Performs a pseudo-random sampling of the documents from the previous stage. + * + *

This stage will filter documents pseudo-randomly. The 'options' parameter specifies how + * sampling will be performed. See {@code SampleOptions} for more information. + * + *

Examples: + * + * // Sample 10 books, if available. + * firestore.pipeline().collection("books") + * .sample({ documents: 10 }); + * + * // Sample 50% of books. + * firestore.pipeline().collection("books") + * .sample({ percentage: 0.5 }); + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new {@code Pipeline} object with this stage appended to the stage list. + */ + sample(options: SampleStageOptions): Pipeline; + /** + * @beta + * Performs union of all documents from two pipelines, including duplicates. + * + *

This stage will pass through documents from previous stage, and also pass through documents + * from previous stage of the `other` {@code Pipeline} given in parameter. The order of documents + * emitted from this stage is undefined. + * + * + * ```typescript + * // Emit documents from books collection and magazines collection. + * firestore.pipeline().collection('books') + * .union(firestore.pipeline().collection('magazines')); + * ``` + * + * @param other The other {@code Pipeline} that is part of union. + * @returns A new {@code Pipeline} object with this stage appended to the stage list. + */ + union(other: Pipeline): Pipeline; + /** + * @beta + * Performs union of all documents from two pipelines, including duplicates. + * + *

This stage will pass through documents from previous stage, and also pass through documents + * from previous stage of the `other` {@code Pipeline} given in parameter. The order of documents + * emitted from this stage is undefined. + * + * + * ```typescript + * // Emit documents from books collection and magazines collection. + * firestore.pipeline().collection('books') + * .union(firestore.pipeline().collection('magazines')); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new {@code Pipeline} object with this stage appended to the stage list. + */ + union(options: UnionStageOptions): Pipeline; + /** + * @beta + * Produces a document for each element in an input array. + * + * For each previous stage document, this stage will emit zero or more augmented documents. The + * input array specified by the `selectable` parameter, will emit an augmented document for each input array element. The input array element will + * augment the previous stage document by setting the `alias` field with the array element value. + * + * When `selectable` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for + * the current input document, returning it as is with the `alias` field absent. + * + * No documents are emitted when `selectable` evaluates to an empty array. + * + * + * ```typescript + * // Input: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tags": [ "comedy", "space", "adventure" ], ... } + * + * // Emit a book document for each tag of the book. + * firestore.pipeline().collection("books") + * .unnest(field("tags").as('tag'), 'tagIndex'); + * + * // Output: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", "tagIndex": 0, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", "tagIndex": 1, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", "tagIndex": 2, ... } + * ``` + * + * @param selectable A selectable expression defining the field to unnest and the alias to use for each un-nested element in the output documents. + * @param indexField An optional string value specifying the field path to write the offset (starting at zero) into the array the un-nested element is from + * @returns A new {@code Pipeline} object with this stage appended to the stage list. + */ + unnest(selectable: Selectable, indexField?: string): Pipeline; + /** + * @beta + * Produces a document for each element in an input array. + * + * For each previous stage document, this stage will emit zero or more augmented documents. The + * input array specified by the `selectable` parameter, will emit an augmented document for each input array element. The input array element will + * augment the previous stage document by setting the `alias` field with the array element value. + * + * When `selectable` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for + * the current input document, returning it as is with the `alias` field absent. + * + * No documents are emitted when `selectable` evaluates to an empty array. + * + * + * ```typescript + * // Input: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tags": [ "comedy", "space", "adventure" ], ... } + * + * // Emit a book document for each tag of the book. + * firestore.pipeline().collection("books") + * .unnest(field("tags").as('tag'), 'tagIndex'); + * + * // Output: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", "tagIndex": 0, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", "tagIndex": 1, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", "tagIndex": 2, ... } + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new {@code Pipeline} object with this stage appended to the stage list. + */ + unnest(options: UnnestStageOptions): Pipeline; + /** + * @beta + * Sorts the documents from previous stages based on one or more `Ordering` criteria. + * + *

This stage allows you to order the results of your pipeline. You can specify multiple {@link + * Ordering} instances to sort by multiple fields in ascending or descending order. If documents + * have the same value for a field used for sorting, the next specified ordering will be used. If + * all orderings result in equal comparison, the documents are considered equal and the order is + * unspecified. + * + * + * ```typescript + * // Sort books by rating in descending order, and then by title in ascending order for books + * // with the same rating + * firestore.pipeline().collection("books") + * .sort( + * Ordering.of(field("rating")).descending(), + * Ordering.of(field("title")) // Ascending order is the default + * ); + * ``` + * + * @param ordering The first `Ordering` instance specifying the sorting criteria. + * @param additionalOrderings Optional additional `Ordering` instances specifying the additional sorting criteria. + * @returns A new {@code Pipeline} object with this stage appended to the stage list. + */ + sort(ordering: Ordering, ...additionalOrderings: Ordering[]): Pipeline; + /** + * @beta + * Sorts the documents from previous stages based on one or more `Ordering` criteria. + * + *

This stage allows you to order the results of your pipeline. You can specify multiple {@link + * Ordering} instances to sort by multiple fields in ascending or descending order. If documents + * have the same value for a field used for sorting, the next specified ordering will be used. If + * all orderings result in equal comparison, the documents are considered equal and the order is + * unspecified. + * + * + * ```typescript + * // Sort books by rating in descending order, and then by title in ascending order for books + * // with the same rating + * firestore.pipeline().collection("books") + * .sort( + * Ordering.of(field("rating")).descending(), + * Ordering.of(field("title")) // Ascending order is the default + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @returns A new {@code Pipeline} object with this stage appended to the stage list. + */ + sort(options: SortStageOptions): Pipeline; + /** + * @beta + * Adds a raw stage to the pipeline. + * + *

This method provides a flexible way to extend the pipeline's functionality by adding custom + * stages. Each raw stage is defined by a unique `name` and a set of `params` that control its + * behavior. + * + *

Example (Assuming there is no "where" stage available in SDK): + * + * ```typescript + * // Assume we don't have a built-in "where" stage + * firestore.pipeline().collection("books") + * .rawStage("where", [Field.of("published").lessThan(1900)]) // Custom "where" stage + * .select("title", "author"); + * ``` + * + * @param name The unique name of the raw stage to add. + * @param params A list of parameters to configure the raw stage's behavior. + * @returns A new {@code Pipeline} object with this stage appended to the stage list. + */ + rawStage(name: string, params: any[]): Pipeline; + /** + * @beta + * Executes this pipeline and returns a Promise to represent the asynchronous operation. + * + *

The returned Promise can be used to track the progress of the pipeline execution + * and retrieve the results (or handle any errors) asynchronously. + * + *

The pipeline results are returned in a `PipelineSnapshot` object, which contains a list of + * `PipelineResult` objects. Each `PipelineResult` typically represents a single key/value map that + * has passed through all the stages of the pipeline, however this might differ depending on the stages involved + * in the pipeline. For example: + * + *

    + *
  • If there are no stages or only transformation stages, each `PipelineResult` + * represents a single document.
  • + *
  • If there is an aggregation, only a single `PipelineResult` is returned, + * representing the aggregated results over the entire dataset .
  • + *
  • If there is an aggregation stage with grouping, each `PipelineResult` represents a + * distinct group and its associated aggregated values.
  • + *
+ * + * + * ```typescript + * const futureResults = await firestore.pipeline().collection("books") + * .where(greaterThan(Field.of("rating"), 4.5)) + * .select("title", "author", "rating") + * .execute(); + * ``` + * + * @param pipelineExecuteOptions - Optionally specify pipeline execution behavior. + * @returns A Promise representing the asynchronous pipeline execution. + */ + execute( + pipelineExecuteOptions?: PipelineExecuteOptions, + ): Promise; + + /** + * @beta + * Executes this pipeline and streams the results as `PipelineResult`s. + * + * @returns {NodeJS.ReadableStream} A Node.js ReadableStream that emits `PipelineResult` objects. + * + * @example + * ```typescript + * firestore.pipeline().collection("books") + * .where(greaterThan(Field.of("rating"), 4.5)) + * .select("title", "author", "rating") + * .stream() + * .on('data', (pipelineResult) => { + * console.log(pipelineResult); + * }) + * .on('end', () => { + * console.log('Stream ended.'); + * }); + * ``` + */ + stream(): NodeJS.ReadableStream; + } + /** + * @beta + * Options defining how a Pipeline is evaluated. + */ + export type PipelineExecuteOptions = { + /** + * @beta + * Specifies the index mode for the query. + */ + indexMode?: 'recommended'; + /** + * @beta Options used to configure explain queries. */ + explainOptions?: { + /** + * @beta + * The explain mode configures what explain data + * and query results are returned from the Pipeline query. + * + * `"execute"` - [DEFAULT] Execute the Pipeline and return results + * `"analyze"` - Plan the query and execute, returning both the planner + * information and the Pipeline query results. + */ + mode?: 'execute' | 'analyze'; + /** + * @beta + * Specifies the output format of the query planner information. + */ + outputFormat?: 'text'; + }; + /** + * @beta + * An escape hatch to set options not known at SDK build time. These values + * will be passed directly to the Firestore backend and not used by the SDK. + * + * The option name will be used as provided. And must match the name + * format used by the backend (hint: use a snake_case_name). + * + * Custom option values can be any type supported + * by Firestore (for example: string, boolean, number, map, …). Value types + * not known to the SDK will be rejected. + * + * Values specified in rawOptions will take precedence over any options + * with the same name set by the SDK. + * + * Override the `example_option`: + * ``` + * execute({ + * pipeline: myPipeline, + * rawOptions: { + * // Override `example_option`. This will not + * // merge with the existing `example_option` object. + * "example_option": { + * foo: "bar" + * } + * } + * } + * ``` + * + * `rawOptions` supports dot notation, if you want to override + * a nested option. + * ``` + * execute({ + * pipeline: myPipeline, + * rawOptions: { + * // Override `example_option.foo` and do not override + * // any other properties of `example_option`. + * "example_option.foo": "bar" + * } + * } + * ``` + */ + rawOptions?: { + [name: string]: unknown; + }; + }; + /** + * @beta + * Options defining how a Stage is evaluated. + */ + export type StageOptions = { + /** + * @beta + * An escape hatch to set options not known at SDK build time. These values + * will be passed directly to the Firestore backend and not used by the SDK. + * + * The option name will be used as provided. And must match the name + * format used by the backend (hint: use a snake_case_name). + * + * Raw option values can be any type supported + * by Firestore (for example: string, boolean, number, map, …). Value types + * not known to the SDK will be rejected. + * + * Values specified in rawOptions will take precedence over any options + * with the same name set by the SDK. + * + * `rawOptions` supports dot notation, if you want to override + * a nested option. + */ + rawOptions?: { + [name: string]: unknown; + }; + }; + /** + * @beta + * Options defining how a CollectionStage is evaluated. See {@link PipelineSource.collection}. + */ + export type CollectionStageOptions = StageOptions & { + /** + * @beta + * Name or reference to the collection that will be used as the Pipeline source. + */ + collection: string | CollectionReference; + + /** + * @beta + * Specifies the name of an index to be used for a query, overriding the query optimizer's default choice. + * This can be useful for performance tuning in specific scenarios where the default index selection + * does not yield optimal performance. + * + * @remarks This property is optional. When provided, it should be the exact name of the index to force. + */ + forceIndex?: string; + }; + + /** + * @beta + * Defines the configuration options for a {@link CollectionGroupStage} within a pipeline. + * This type extends {@link StageOptions} and provides specific settings for how a collection group + * is identified and processed during pipeline execution. + * + * @see {@link PipelineSource.collectionGroup} to create a collection group stage. + */ + export type CollectionGroupStageOptions = StageOptions & { + /** + * @beta + * ID of the collection group to use as the Pipeline source. + */ + collectionId: string; + + /** + * @beta + * Specifies the name of an index to be used for a query, overriding the query optimizer's default choice. + * This can be useful for performance tuning in specific scenarios where the default index selection + * does not yield optimal performance. + * + * @remarks This property is optional. When provided, it should be the exact name of the index to force. + */ + forceIndex?: string; + }; + /** + * @beta + * Options defining how a DatabaseStage is evaluated. See {@link PipelineSource.database}. + */ + export type DatabaseStageOptions = StageOptions & {}; + /** + * @beta + * Options defining how a DocumentsStage is evaluated. See {@link PipelineSource.documents}. + */ + export type DocumentsStageOptions = StageOptions & { + /** + * @beta + * An array of paths and DocumentReferences specifying the individual documents that will be the source of this pipeline. + * The converters for these DocumentReferences will be ignored and not have an effect on this pipeline. + * There must be at least one document specified in the array. + */ + docs: Array; + }; + /** + * @beta + * Options defining how an AddFieldsStage is evaluated. See {@link Pipeline.addFields}. + */ + export type AddFieldsStageOptions = StageOptions & { + /** + * @beta + * The fields to add to each document, specified as a `Selectable`. + * At least one field is required. + */ + fields: Selectable[]; + }; + /** + * @beta + * Options defining how a RemoveFieldsStage is evaluated. See {@link Pipeline.removeFields}. + */ + export type RemoveFieldsStageOptions = StageOptions & { + /** + * @beta + * The fields to remove from each document. + */ + fields: Array; + }; + /** + * @beta + * Options defining how a SelectStage is evaluated. See {@link Pipeline.select}. + */ + export type SelectStageOptions = StageOptions & { + /** + * @beta + * The fields to include in the output documents, specified as `Selectable` expression + * or as a string value indicating the field name. + */ + selections: Array; + }; + /** + * @beta + * Options defining how a WhereStage is evaluated. See {@link Pipeline.where}. + */ + export type WhereStageOptions = StageOptions & { + /** + * @beta + * The `BooleanExpression` to apply as a filter for each input document to this stage. + */ + condition: BooleanExpression; + }; + /** + * @beta + * Options defining how an OffsetStage is evaluated. See {@link Pipeline.offset}. + */ + export type OffsetStageOptions = StageOptions & { + /** + * @beta + * The number of documents to skip. + */ + offset: number; + }; + /** + * @beta + * Options defining how a LimitStage is evaluated. See {@link Pipeline.limit}. + */ + export type LimitStageOptions = StageOptions & { + /** + * @beta + * The maximum number of documents to return. + */ + limit: number; + }; + /** + * @beta + * Options defining how a DistinctStage is evaluated. See {@link Pipeline.distinct}. + */ + export type DistinctStageOptions = StageOptions & { + /** + * @beta + * The `Selectable` expressions or field names to consider when determining + * distinct value combinations (groups). + */ + groups: Array; + }; + /** + * @beta + * Options defining how an AggregateStage is evaluated. See {@link Pipeline.aggregate}. + */ + export type AggregateStageOptions = StageOptions & { + /** + * @beta + * The `AliasedAggregate` values specifying aggregate operations to + * perform on the input documents. + */ + accumulators: AliasedAggregate[]; + /** + * @beta + * The `Selectable` expressions or field names to consider when determining + * distinct value combinations (groups), which will be aggregated over. + */ + groups?: Array; + }; + /** + * @beta + * Options defining how a FindNearestStage is evaluated. See {@link Pipeline.findNearest:VectorQueryOptions}. + */ + export type FindNearestStageOptions = StageOptions & { + /** + * @beta + * Specifies the field to be used. This can be a string representing the field path + * (e.g., 'fieldName', 'nested.fieldName') or an object of type `Field` + * representing a more complex field expression. + */ + field: Field | string; + /** + * @beta + * Specifies the query vector value, to which the vector distance will be computed. + */ + vectorValue: VectorValue | number[]; + /** + * @beta + * Specifies the method used to compute the distance between vectors. + * + * Possible values are: + * - `'euclidean'`: Euclidean distance. + * - `'cosine'`: Cosine similarity. + * - `'dot_product'`: Dot product. + */ + distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; + /** + * @beta + * The maximum number of documents to return from the FindNearest stage. + */ + limit?: number; + /** + * @beta + * If set, specifies the field on the output documents that will contain + * the computed vector distance for the document. If not set, the computed + * vector distance will not be returned. + */ + distanceField?: string; + }; + /** + * @beta + * Options defining how a ReplaceWithStage is evaluated. See {@link Pipeline.replaceWith}. + */ + export type ReplaceWithStageOptions = StageOptions & { + /** + * @beta + * The name of a field that contains a map or an `Expression` that + * evaluates to a map. + */ + map: Expression | string; + }; + /** + * @beta + * Defines the options for evaluating a sample stage within a pipeline. + * This type combines common {@link StageOptions} with a specific configuration + * where only one of the defined sampling methods can be applied. + * + * See {@link Pipeline.sample} to create a sample stage.. + */ + export type SampleStageOptions = StageOptions & + OneOf<{ + /** + * @beta + * If set, specifies the sample rate as a percentage of the + * input documents. + * + * Cannot be set when `documents: number` is set. + */ + percentage: number; + /** + * @beta + * If set, specifies the sample rate as a total number of + * documents to sample from the input documents. + * + * Cannot be set when `percentage: number` is set. + */ + documents: number; + }>; + /** + * @beta + * Options defining how a UnionStage is evaluated. See {@link Pipeline.union}. + */ + export type UnionStageOptions = StageOptions & { + /** + * @beta + * Specifies the other Pipeline to union with. + */ + other: Pipeline; + }; + + /** + * @beta + * Represents the specific options available for configuring an `UnnestStage` within a pipeline. + */ + export type UnnestStageOptions = StageOptions & { + /** + * @beta + * A `Selectable` object that defines an array expression to be un-nested + * and the alias for the un-nested field. + */ + selectable: Selectable; + /** + * @beta + * If set, specifies the field on the output documents that will contain the + * offset (starting at zero) that the element is from the original array. + */ + indexField?: string; + }; + /** + * @beta + * Options defining how a SortStage is evaluated. See {@link Pipeline.sort}. + */ + export type SortStageOptions = StageOptions & { + /** + * @beta + * Orderings specify how the input documents are sorted. + * One or more ordering are required. + */ + orderings: Ordering[]; + }; + + /** + * @beta + * Represents a field value within the explain statistics, which can be a primitive type (null, string, number, boolean) + * or a recursively defined object where keys are strings and values are also `ExplainStatsFieldValue`. + */ + export type ExplainStatsFieldValue = + | null + | string + | number + | boolean + | { + [key: string]: ExplainStatsFieldValue; + } + | ExplainStatsFieldValue[]; + + /** + * @beta + * Represents the explanation statistics for a `Pipeline` query execution. + * These statistics are available when the query is executed with explain or analyze + * options enabled, providing insights into the query's performance and execution plan. + */ + export class ExplainStats { + /** + * @beta + * When explain stats were requested with `outputFormat = 'text'`, this returns + * the explain stats string verbatium as returned from the Firestore backend. + * + * If explain stats were requested with `outputFormat = 'json'`, this returns + * the explain stats as stringified JSON, which was returned from the Firestore backend. + */ + get text(): string; + /** + * @beta + * Returns the explain stats as an encoded protocol buffer message, typically wrapped in a `google.protobuf.Any` format. + * This object includes a `type_url` field that identifies the specific type of the serialized message. + * The caller is responsible for deserializing and unpacking this proto message to access the explain stats. + */ + get rawData(): { + type_url?: string | null; + value?: Uint8Array | null; + }; + } + + /** + * @beta + * Represents the results of a Firestore pipeline execution. + * + * A `PipelineSnapshot` contains zero or more `PipelineResult` objects + * representing the documents returned by a pipeline query. It provides methods + * to iterate over the documents and access metadata about the query results. + * + * @example + * ```typescript + * const snapshot = await firestore + * .pipeline() + * .collection('myCollection') + * .where(field('value').greaterThan(10)) + * .execute(); + * + * snapshot.results.forEach(doc => { + * console.log(doc.id, '=>', doc.data()); + * }); + * ``` + */ + export class PipelineSnapshot { + /** + * @beta + * The Pipeline on which you called `execute()` in order to get this + * `PipelineSnapshot`. + */ + get pipeline(): Pipeline; + + /** + * @beta An array of all the results in the `PipelineSnapshot`. */ + get results(): PipelineResult[]; + + /** + * @beta + * The time at which the pipeline producing this result was executed. + */ + get executionTime(): Timestamp; + + /** + * @beta + * Return stats from query explain. + * + * If `explainOptions.mode` was set to `execute` or left unset, then this returns `undefined`. + */ + get explainStats(): ExplainStats | undefined; + } + + /** + * @beta + * A PipelineResult contains data read from a Firestore Pipeline. The data can be extracted with the + * `data()` or `get(String)` methods. + * + *

If the PipelineResult represents a non-document result, `ref` will return a undefined + * value. + */ + export class PipelineResult { + readonly createTime: Timestamp | undefined; + readonly updateTime: Timestamp | undefined; + /** + * @beta + * The reference of the document, if it is a document; otherwise `undefined`. + */ + get ref(): DocumentReference | undefined; + + /** + * @beta + * The ID of the document for which this PipelineResult contains data. + * Returns `undefined` if the PipelineResult does not represent a document. + */ + get id(): string | undefined; + + /** + * @beta + * Retrieves all fields of the document from the query result as a plain JavaScript object. + * + * @returns {DocumentData} An object containing all fields in the document. + * + * @example + * ``` + * let p = firestore.pipeline().collection('col'); + * + * p.execute().then(results => { + * let data = results[0].data(); + * console.log(`Retrieved data: ${JSON.stringify(data)}`); + * }); + * ``` + */ + data(): DocumentData; + /** + * @beta + * Retrieves the field specified by `field`. + * + * @param {string|FieldPath} fieldPath The field path + * (e.g. 'foo' or 'foo.bar') to a specific field. + * @returns {*} The data at the specified field location or undefined if no + * such field exists. + * + * @example + * ``` + * let p = firestore.pipeline().collection('col'); + * + * p.execute().then(results => { + * let field = results[0].get('a.b'); + * console.log(`Retrieved field value: ${field}`); + * }); + * ``` + */ + // We deliberately use `any` in the external API to not impose type-checking + // on end users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(fieldPath: string | FieldPath): any; + + /** + * @beta + * Checks if this `PipelineResult` is equal to the provided `other` object. + * Equality is determined by comparing the document's data and path. + * + * @param other The `PipelineResult` to compare against. + * @returns `true` if this `PipelineResult` is equal to the provided value; `false` otherwise. + */ + isEqual(other: PipelineResult): boolean; + } + } +} +declare module '@google-cloud/firestore' { + export = FirebaseFirestore; +} diff --git a/handwritten/firestore/types/pipelines.d.ts b/handwritten/firestore/types/pipelines.d.ts new file mode 100644 index 00000000000..226ca963d6c --- /dev/null +++ b/handwritten/firestore/types/pipelines.d.ts @@ -0,0 +1,28 @@ +/*! + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// We deliberately use `any` in the external API to not impose type-checking +// on end users. +/* eslint-disable @typescript-eslint/no-explicit-any */ + +// Declare a global (ambient) namespace +// (used when not using import statement, but just script include). + +import './firestore'; + +declare module '@google-cloud/firestore/pipelines' { + export = FirebaseFirestore.Pipelines; +} diff --git a/handwritten/firestore/types/protos/firestore_admin_v1_proto_api.d.ts b/handwritten/firestore/types/protos/firestore_admin_v1_proto_api.d.ts new file mode 100644 index 00000000000..4c92456901b --- /dev/null +++ b/handwritten/firestore/types/protos/firestore_admin_v1_proto_api.d.ts @@ -0,0 +1,10845 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as $protobuf from "protobufjs"; + +/** Namespace google. */ +export namespace google { + + /** Namespace firestore. */ + namespace firestore { + + /** Namespace admin. */ + namespace admin { + + /** Namespace v1. */ + namespace v1 { + + /** Properties of a Backup. */ + interface IBackup { + + /** Backup name */ + name?: (string|null); + + /** Backup database */ + database?: (string|null); + + /** Backup databaseUid */ + databaseUid?: (string|null); + + /** Backup snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + + /** Backup expireTime */ + expireTime?: (google.protobuf.ITimestamp|null); + + /** Backup stats */ + stats?: (google.firestore.admin.v1.Backup.IStats|null); + + /** Backup state */ + state?: (google.firestore.admin.v1.Backup.State|null); + } + + /** Represents a Backup. */ + class Backup implements IBackup { + + /** + * Constructs a new Backup. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBackup); + + /** Backup name. */ + public name: string; + + /** Backup database. */ + public database: string; + + /** Backup databaseUid. */ + public databaseUid: string; + + /** Backup snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** Backup expireTime. */ + public expireTime?: (google.protobuf.ITimestamp|null); + + /** Backup stats. */ + public stats?: (google.firestore.admin.v1.Backup.IStats|null); + + /** Backup state. */ + public state: google.firestore.admin.v1.Backup.State; + + /** + * Creates a Backup message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Backup + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Backup; + + /** + * Creates a plain object from a Backup message. Also converts values to other types if specified. + * @param message Backup + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Backup, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Backup to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Backup + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Backup { + + /** Properties of a Stats. */ + interface IStats { + + /** Stats sizeBytes */ + sizeBytes?: (number|string|null); + + /** Stats documentCount */ + documentCount?: (number|string|null); + + /** Stats indexCount */ + indexCount?: (number|string|null); + } + + /** Represents a Stats. */ + class Stats implements IStats { + + /** + * Constructs a new Stats. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Backup.IStats); + + /** Stats sizeBytes. */ + public sizeBytes: (number|string); + + /** Stats documentCount. */ + public documentCount: (number|string); + + /** Stats indexCount. */ + public indexCount: (number|string); + + /** + * Creates a Stats message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Stats + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Backup.Stats; + + /** + * Creates a plain object from a Stats message. Also converts values to other types if specified. + * @param message Stats + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Backup.Stats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Stats to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Stats + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "CREATING"| "READY"| "NOT_AVAILABLE"; + } + + /** Properties of a Database. */ + interface IDatabase { + + /** Database name */ + name?: (string|null); + + /** Database uid */ + uid?: (string|null); + + /** Database createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** Database updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** Database deleteTime */ + deleteTime?: (google.protobuf.ITimestamp|null); + + /** Database locationId */ + locationId?: (string|null); + + /** Database type */ + type?: (google.firestore.admin.v1.Database.DatabaseType|null); + + /** Database concurrencyMode */ + concurrencyMode?: (google.firestore.admin.v1.Database.ConcurrencyMode|null); + + /** Database versionRetentionPeriod */ + versionRetentionPeriod?: (google.protobuf.IDuration|null); + + /** Database earliestVersionTime */ + earliestVersionTime?: (google.protobuf.ITimestamp|null); + + /** Database pointInTimeRecoveryEnablement */ + pointInTimeRecoveryEnablement?: (google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement|null); + + /** Database appEngineIntegrationMode */ + appEngineIntegrationMode?: (google.firestore.admin.v1.Database.AppEngineIntegrationMode|null); + + /** Database keyPrefix */ + keyPrefix?: (string|null); + + /** Database deleteProtectionState */ + deleteProtectionState?: (google.firestore.admin.v1.Database.DeleteProtectionState|null); + + /** Database cmekConfig */ + cmekConfig?: (google.firestore.admin.v1.Database.ICmekConfig|null); + + /** Database previousId */ + previousId?: (string|null); + + /** Database sourceInfo */ + sourceInfo?: (google.firestore.admin.v1.Database.ISourceInfo|null); + + /** Database tags */ + tags?: ({ [k: string]: string }|null); + + /** Database freeTier */ + freeTier?: (boolean|null); + + /** Database etag */ + etag?: (string|null); + + /** Database databaseEdition */ + databaseEdition?: (google.firestore.admin.v1.Database.DatabaseEdition|null); + } + + /** Represents a Database. */ + class Database implements IDatabase { + + /** + * Constructs a new Database. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDatabase); + + /** Database name. */ + public name: string; + + /** Database uid. */ + public uid: string; + + /** Database createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** Database updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** Database deleteTime. */ + public deleteTime?: (google.protobuf.ITimestamp|null); + + /** Database locationId. */ + public locationId: string; + + /** Database type. */ + public type: google.firestore.admin.v1.Database.DatabaseType; + + /** Database concurrencyMode. */ + public concurrencyMode: google.firestore.admin.v1.Database.ConcurrencyMode; + + /** Database versionRetentionPeriod. */ + public versionRetentionPeriod?: (google.protobuf.IDuration|null); + + /** Database earliestVersionTime. */ + public earliestVersionTime?: (google.protobuf.ITimestamp|null); + + /** Database pointInTimeRecoveryEnablement. */ + public pointInTimeRecoveryEnablement: google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement; + + /** Database appEngineIntegrationMode. */ + public appEngineIntegrationMode: google.firestore.admin.v1.Database.AppEngineIntegrationMode; + + /** Database keyPrefix. */ + public keyPrefix: string; + + /** Database deleteProtectionState. */ + public deleteProtectionState: google.firestore.admin.v1.Database.DeleteProtectionState; + + /** Database cmekConfig. */ + public cmekConfig?: (google.firestore.admin.v1.Database.ICmekConfig|null); + + /** Database previousId. */ + public previousId: string; + + /** Database sourceInfo. */ + public sourceInfo?: (google.firestore.admin.v1.Database.ISourceInfo|null); + + /** Database tags. */ + public tags: { [k: string]: string }; + + /** Database freeTier. */ + public freeTier?: (boolean|null); + + /** Database etag. */ + public etag: string; + + /** Database databaseEdition. */ + public databaseEdition: google.firestore.admin.v1.Database.DatabaseEdition; + + /** + * Creates a Database message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Database + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database; + + /** + * Creates a plain object from a Database message. Also converts values to other types if specified. + * @param message Database + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Database to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Database + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Database { + + /** DatabaseType enum. */ + type DatabaseType = + "DATABASE_TYPE_UNSPECIFIED"| "FIRESTORE_NATIVE"| "DATASTORE_MODE"; + + /** ConcurrencyMode enum. */ + type ConcurrencyMode = + "CONCURRENCY_MODE_UNSPECIFIED"| "OPTIMISTIC"| "PESSIMISTIC"| "OPTIMISTIC_WITH_ENTITY_GROUPS"; + + /** PointInTimeRecoveryEnablement enum. */ + type PointInTimeRecoveryEnablement = + "POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED"| "POINT_IN_TIME_RECOVERY_ENABLED"| "POINT_IN_TIME_RECOVERY_DISABLED"; + + /** AppEngineIntegrationMode enum. */ + type AppEngineIntegrationMode = + "APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED"| "ENABLED"| "DISABLED"; + + /** DeleteProtectionState enum. */ + type DeleteProtectionState = + "DELETE_PROTECTION_STATE_UNSPECIFIED"| "DELETE_PROTECTION_DISABLED"| "DELETE_PROTECTION_ENABLED"; + + /** Properties of a CmekConfig. */ + interface ICmekConfig { + + /** CmekConfig kmsKeyName */ + kmsKeyName?: (string|null); + + /** CmekConfig activeKeyVersion */ + activeKeyVersion?: (string[]|null); + } + + /** Represents a CmekConfig. */ + class CmekConfig implements ICmekConfig { + + /** + * Constructs a new CmekConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.ICmekConfig); + + /** CmekConfig kmsKeyName. */ + public kmsKeyName: string; + + /** CmekConfig activeKeyVersion. */ + public activeKeyVersion: string[]; + + /** + * Creates a CmekConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CmekConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.CmekConfig; + + /** + * Creates a plain object from a CmekConfig message. Also converts values to other types if specified. + * @param message CmekConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.CmekConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CmekConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CmekConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SourceInfo. */ + interface ISourceInfo { + + /** SourceInfo backup */ + backup?: (google.firestore.admin.v1.Database.SourceInfo.IBackupSource|null); + + /** SourceInfo operation */ + operation?: (string|null); + } + + /** Represents a SourceInfo. */ + class SourceInfo implements ISourceInfo { + + /** + * Constructs a new SourceInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.ISourceInfo); + + /** SourceInfo backup. */ + public backup?: (google.firestore.admin.v1.Database.SourceInfo.IBackupSource|null); + + /** SourceInfo operation. */ + public operation: string; + + /** SourceInfo source. */ + public source?: "backup"; + + /** + * Creates a SourceInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceInfo + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.SourceInfo; + + /** + * Creates a plain object from a SourceInfo message. Also converts values to other types if specified. + * @param message SourceInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.SourceInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SourceInfo { + + /** Properties of a BackupSource. */ + interface IBackupSource { + + /** BackupSource backup */ + backup?: (string|null); + } + + /** Represents a BackupSource. */ + class BackupSource implements IBackupSource { + + /** + * Constructs a new BackupSource. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.SourceInfo.IBackupSource); + + /** BackupSource backup. */ + public backup: string; + + /** + * Creates a BackupSource message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BackupSource + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.SourceInfo.BackupSource; + + /** + * Creates a plain object from a BackupSource message. Also converts values to other types if specified. + * @param message BackupSource + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.SourceInfo.BackupSource, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BackupSource to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BackupSource + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an EncryptionConfig. */ + interface IEncryptionConfig { + + /** EncryptionConfig googleDefaultEncryption */ + googleDefaultEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.IGoogleDefaultEncryptionOptions|null); + + /** EncryptionConfig useSourceEncryption */ + useSourceEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.ISourceEncryptionOptions|null); + + /** EncryptionConfig customerManagedEncryption */ + customerManagedEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.ICustomerManagedEncryptionOptions|null); + } + + /** Represents an EncryptionConfig. */ + class EncryptionConfig implements IEncryptionConfig { + + /** + * Constructs a new EncryptionConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.IEncryptionConfig); + + /** EncryptionConfig googleDefaultEncryption. */ + public googleDefaultEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.IGoogleDefaultEncryptionOptions|null); + + /** EncryptionConfig useSourceEncryption. */ + public useSourceEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.ISourceEncryptionOptions|null); + + /** EncryptionConfig customerManagedEncryption. */ + public customerManagedEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.ICustomerManagedEncryptionOptions|null); + + /** EncryptionConfig encryptionType. */ + public encryptionType?: ("googleDefaultEncryption"|"useSourceEncryption"|"customerManagedEncryption"); + + /** + * Creates an EncryptionConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EncryptionConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.EncryptionConfig; + + /** + * Creates a plain object from an EncryptionConfig message. Also converts values to other types if specified. + * @param message EncryptionConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.EncryptionConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EncryptionConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EncryptionConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EncryptionConfig { + + /** Properties of a GoogleDefaultEncryptionOptions. */ + interface IGoogleDefaultEncryptionOptions { + } + + /** Represents a GoogleDefaultEncryptionOptions. */ + class GoogleDefaultEncryptionOptions implements IGoogleDefaultEncryptionOptions { + + /** + * Constructs a new GoogleDefaultEncryptionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.EncryptionConfig.IGoogleDefaultEncryptionOptions); + + /** + * Creates a GoogleDefaultEncryptionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoogleDefaultEncryptionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions; + + /** + * Creates a plain object from a GoogleDefaultEncryptionOptions message. Also converts values to other types if specified. + * @param message GoogleDefaultEncryptionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoogleDefaultEncryptionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoogleDefaultEncryptionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SourceEncryptionOptions. */ + interface ISourceEncryptionOptions { + } + + /** Represents a SourceEncryptionOptions. */ + class SourceEncryptionOptions implements ISourceEncryptionOptions { + + /** + * Constructs a new SourceEncryptionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.EncryptionConfig.ISourceEncryptionOptions); + + /** + * Creates a SourceEncryptionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceEncryptionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions; + + /** + * Creates a plain object from a SourceEncryptionOptions message. Also converts values to other types if specified. + * @param message SourceEncryptionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceEncryptionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceEncryptionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomerManagedEncryptionOptions. */ + interface ICustomerManagedEncryptionOptions { + + /** CustomerManagedEncryptionOptions kmsKeyName */ + kmsKeyName?: (string|null); + } + + /** Represents a CustomerManagedEncryptionOptions. */ + class CustomerManagedEncryptionOptions implements ICustomerManagedEncryptionOptions { + + /** + * Constructs a new CustomerManagedEncryptionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.EncryptionConfig.ICustomerManagedEncryptionOptions); + + /** CustomerManagedEncryptionOptions kmsKeyName. */ + public kmsKeyName: string; + + /** + * Creates a CustomerManagedEncryptionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomerManagedEncryptionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions; + + /** + * Creates a plain object from a CustomerManagedEncryptionOptions message. Also converts values to other types if specified. + * @param message CustomerManagedEncryptionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomerManagedEncryptionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomerManagedEncryptionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** DatabaseEdition enum. */ + type DatabaseEdition = + "DATABASE_EDITION_UNSPECIFIED"| "STANDARD"| "ENTERPRISE"; + } + + /** Properties of a Field. */ + interface IField { + + /** Field name */ + name?: (string|null); + + /** Field indexConfig */ + indexConfig?: (google.firestore.admin.v1.Field.IIndexConfig|null); + + /** Field ttlConfig */ + ttlConfig?: (google.firestore.admin.v1.Field.ITtlConfig|null); + } + + /** Represents a Field. */ + class Field implements IField { + + /** + * Constructs a new Field. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IField); + + /** Field name. */ + public name: string; + + /** Field indexConfig. */ + public indexConfig?: (google.firestore.admin.v1.Field.IIndexConfig|null); + + /** Field ttlConfig. */ + public ttlConfig?: (google.firestore.admin.v1.Field.ITtlConfig|null); + + /** + * Creates a Field message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Field + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Field; + + /** + * Creates a plain object from a Field message. Also converts values to other types if specified. + * @param message Field + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Field, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Field to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Field + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Field { + + /** Properties of an IndexConfig. */ + interface IIndexConfig { + + /** IndexConfig indexes */ + indexes?: (google.firestore.admin.v1.IIndex[]|null); + + /** IndexConfig usesAncestorConfig */ + usesAncestorConfig?: (boolean|null); + + /** IndexConfig ancestorField */ + ancestorField?: (string|null); + + /** IndexConfig reverting */ + reverting?: (boolean|null); + } + + /** Represents an IndexConfig. */ + class IndexConfig implements IIndexConfig { + + /** + * Constructs a new IndexConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Field.IIndexConfig); + + /** IndexConfig indexes. */ + public indexes: google.firestore.admin.v1.IIndex[]; + + /** IndexConfig usesAncestorConfig. */ + public usesAncestorConfig: boolean; + + /** IndexConfig ancestorField. */ + public ancestorField: string; + + /** IndexConfig reverting. */ + public reverting: boolean; + + /** + * Creates an IndexConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Field.IndexConfig; + + /** + * Creates a plain object from an IndexConfig message. Also converts values to other types if specified. + * @param message IndexConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Field.IndexConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TtlConfig. */ + interface ITtlConfig { + + /** TtlConfig state */ + state?: (google.firestore.admin.v1.Field.TtlConfig.State|null); + } + + /** Represents a TtlConfig. */ + class TtlConfig implements ITtlConfig { + + /** + * Constructs a new TtlConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Field.ITtlConfig); + + /** TtlConfig state. */ + public state: google.firestore.admin.v1.Field.TtlConfig.State; + + /** + * Creates a TtlConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TtlConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Field.TtlConfig; + + /** + * Creates a plain object from a TtlConfig message. Also converts values to other types if specified. + * @param message TtlConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Field.TtlConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TtlConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TtlConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TtlConfig { + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "CREATING"| "ACTIVE"| "NEEDS_REPAIR"; + } + } + + /** Properties of an Index. */ + interface IIndex { + + /** Index name */ + name?: (string|null); + + /** Index queryScope */ + queryScope?: (google.firestore.admin.v1.Index.QueryScope|null); + + /** Index apiScope */ + apiScope?: (google.firestore.admin.v1.Index.ApiScope|null); + + /** Index fields */ + fields?: (google.firestore.admin.v1.Index.IIndexField[]|null); + + /** Index state */ + state?: (google.firestore.admin.v1.Index.State|null); + + /** Index density */ + density?: (google.firestore.admin.v1.Index.Density|null); + + /** Index multikey */ + multikey?: (boolean|null); + + /** Index shardCount */ + shardCount?: (number|null); + } + + /** Represents an Index. */ + class Index implements IIndex { + + /** + * Constructs a new Index. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IIndex); + + /** Index name. */ + public name: string; + + /** Index queryScope. */ + public queryScope: google.firestore.admin.v1.Index.QueryScope; + + /** Index apiScope. */ + public apiScope: google.firestore.admin.v1.Index.ApiScope; + + /** Index fields. */ + public fields: google.firestore.admin.v1.Index.IIndexField[]; + + /** Index state. */ + public state: google.firestore.admin.v1.Index.State; + + /** Index density. */ + public density: google.firestore.admin.v1.Index.Density; + + /** Index multikey. */ + public multikey: boolean; + + /** Index shardCount. */ + public shardCount: number; + + /** + * Creates an Index message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Index + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index; + + /** + * Creates a plain object from an Index message. Also converts values to other types if specified. + * @param message Index + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Index to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Index + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Index { + + /** QueryScope enum. */ + type QueryScope = + "QUERY_SCOPE_UNSPECIFIED"| "COLLECTION"| "COLLECTION_GROUP"| "COLLECTION_RECURSIVE"; + + /** ApiScope enum. */ + type ApiScope = + "ANY_API"| "DATASTORE_MODE_API"| "MONGODB_COMPATIBLE_API"; + + /** Properties of an IndexField. */ + interface IIndexField { + + /** IndexField fieldPath */ + fieldPath?: (string|null); + + /** IndexField order */ + order?: (google.firestore.admin.v1.Index.IndexField.Order|null); + + /** IndexField arrayConfig */ + arrayConfig?: (google.firestore.admin.v1.Index.IndexField.ArrayConfig|null); + + /** IndexField vectorConfig */ + vectorConfig?: (google.firestore.admin.v1.Index.IndexField.IVectorConfig|null); + } + + /** Represents an IndexField. */ + class IndexField implements IIndexField { + + /** + * Constructs a new IndexField. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Index.IIndexField); + + /** IndexField fieldPath. */ + public fieldPath: string; + + /** IndexField order. */ + public order?: (google.firestore.admin.v1.Index.IndexField.Order|null); + + /** IndexField arrayConfig. */ + public arrayConfig?: (google.firestore.admin.v1.Index.IndexField.ArrayConfig|null); + + /** IndexField vectorConfig. */ + public vectorConfig?: (google.firestore.admin.v1.Index.IndexField.IVectorConfig|null); + + /** IndexField valueMode. */ + public valueMode?: ("order"|"arrayConfig"|"vectorConfig"); + + /** + * Creates an IndexField message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexField + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField; + + /** + * Creates a plain object from an IndexField message. Also converts values to other types if specified. + * @param message IndexField + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index.IndexField, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexField to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexField + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace IndexField { + + /** Order enum. */ + type Order = + "ORDER_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; + + /** ArrayConfig enum. */ + type ArrayConfig = + "ARRAY_CONFIG_UNSPECIFIED"| "CONTAINS"; + + /** Properties of a VectorConfig. */ + interface IVectorConfig { + + /** VectorConfig dimension */ + dimension?: (number|null); + + /** VectorConfig flat */ + flat?: (google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex|null); + } + + /** Represents a VectorConfig. */ + class VectorConfig implements IVectorConfig { + + /** + * Constructs a new VectorConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Index.IndexField.IVectorConfig); + + /** VectorConfig dimension. */ + public dimension: number; + + /** VectorConfig flat. */ + public flat?: (google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex|null); + + /** VectorConfig type. */ + public type?: "flat"; + + /** + * Creates a VectorConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns VectorConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField.VectorConfig; + + /** + * Creates a plain object from a VectorConfig message. Also converts values to other types if specified. + * @param message VectorConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index.IndexField.VectorConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this VectorConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for VectorConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace VectorConfig { + + /** Properties of a FlatIndex. */ + interface IFlatIndex { + } + + /** Represents a FlatIndex. */ + class FlatIndex implements IFlatIndex { + + /** + * Constructs a new FlatIndex. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex); + + /** + * Creates a FlatIndex message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FlatIndex + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex; + + /** + * Creates a plain object from a FlatIndex message. Also converts values to other types if specified. + * @param message FlatIndex + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FlatIndex to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FlatIndex + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "CREATING"| "READY"| "NEEDS_REPAIR"; + + /** Density enum. */ + type Density = + "DENSITY_UNSPECIFIED"| "SPARSE_ALL"| "SPARSE_ANY"| "DENSE"; + } + + /** Represents a FirestoreAdmin */ + class FirestoreAdmin extends $protobuf.rpc.Service { + + /** + * Constructs a new FirestoreAdmin service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls CreateIndex. + * @param request CreateIndexRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public createIndex(request: google.firestore.admin.v1.ICreateIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateIndexCallback): void; + + /** + * Calls CreateIndex. + * @param request CreateIndexRequest message or plain object + * @returns Promise + */ + public createIndex(request: google.firestore.admin.v1.ICreateIndexRequest): Promise; + + /** + * Calls ListIndexes. + * @param request ListIndexesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListIndexesResponse + */ + public listIndexes(request: google.firestore.admin.v1.IListIndexesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListIndexesCallback): void; + + /** + * Calls ListIndexes. + * @param request ListIndexesRequest message or plain object + * @returns Promise + */ + public listIndexes(request: google.firestore.admin.v1.IListIndexesRequest): Promise; + + /** + * Calls GetIndex. + * @param request GetIndexRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Index + */ + public getIndex(request: google.firestore.admin.v1.IGetIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetIndexCallback): void; + + /** + * Calls GetIndex. + * @param request GetIndexRequest message or plain object + * @returns Promise + */ + public getIndex(request: google.firestore.admin.v1.IGetIndexRequest): Promise; + + /** + * Calls DeleteIndex. + * @param request DeleteIndexRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteIndex(request: google.firestore.admin.v1.IDeleteIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteIndexCallback): void; + + /** + * Calls DeleteIndex. + * @param request DeleteIndexRequest message or plain object + * @returns Promise + */ + public deleteIndex(request: google.firestore.admin.v1.IDeleteIndexRequest): Promise; + + /** + * Calls GetField. + * @param request GetFieldRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Field + */ + public getField(request: google.firestore.admin.v1.IGetFieldRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetFieldCallback): void; + + /** + * Calls GetField. + * @param request GetFieldRequest message or plain object + * @returns Promise + */ + public getField(request: google.firestore.admin.v1.IGetFieldRequest): Promise; + + /** + * Calls UpdateField. + * @param request UpdateFieldRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public updateField(request: google.firestore.admin.v1.IUpdateFieldRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateFieldCallback): void; + + /** + * Calls UpdateField. + * @param request UpdateFieldRequest message or plain object + * @returns Promise + */ + public updateField(request: google.firestore.admin.v1.IUpdateFieldRequest): Promise; + + /** + * Calls ListFields. + * @param request ListFieldsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListFieldsResponse + */ + public listFields(request: google.firestore.admin.v1.IListFieldsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListFieldsCallback): void; + + /** + * Calls ListFields. + * @param request ListFieldsRequest message or plain object + * @returns Promise + */ + public listFields(request: google.firestore.admin.v1.IListFieldsRequest): Promise; + + /** + * Calls ExportDocuments. + * @param request ExportDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public exportDocuments(request: google.firestore.admin.v1.IExportDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ExportDocumentsCallback): void; + + /** + * Calls ExportDocuments. + * @param request ExportDocumentsRequest message or plain object + * @returns Promise + */ + public exportDocuments(request: google.firestore.admin.v1.IExportDocumentsRequest): Promise; + + /** + * Calls ImportDocuments. + * @param request ImportDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public importDocuments(request: google.firestore.admin.v1.IImportDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ImportDocumentsCallback): void; + + /** + * Calls ImportDocuments. + * @param request ImportDocumentsRequest message or plain object + * @returns Promise + */ + public importDocuments(request: google.firestore.admin.v1.IImportDocumentsRequest): Promise; + + /** + * Calls BulkDeleteDocuments. + * @param request BulkDeleteDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public bulkDeleteDocuments(request: google.firestore.admin.v1.IBulkDeleteDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocumentsCallback): void; + + /** + * Calls BulkDeleteDocuments. + * @param request BulkDeleteDocumentsRequest message or plain object + * @returns Promise + */ + public bulkDeleteDocuments(request: google.firestore.admin.v1.IBulkDeleteDocumentsRequest): Promise; + + /** + * Calls CreateDatabase. + * @param request CreateDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public createDatabase(request: google.firestore.admin.v1.ICreateDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateDatabaseCallback): void; + + /** + * Calls CreateDatabase. + * @param request CreateDatabaseRequest message or plain object + * @returns Promise + */ + public createDatabase(request: google.firestore.admin.v1.ICreateDatabaseRequest): Promise; + + /** + * Calls GetDatabase. + * @param request GetDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Database + */ + public getDatabase(request: google.firestore.admin.v1.IGetDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetDatabaseCallback): void; + + /** + * Calls GetDatabase. + * @param request GetDatabaseRequest message or plain object + * @returns Promise + */ + public getDatabase(request: google.firestore.admin.v1.IGetDatabaseRequest): Promise; + + /** + * Calls ListDatabases. + * @param request ListDatabasesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDatabasesResponse + */ + public listDatabases(request: google.firestore.admin.v1.IListDatabasesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListDatabasesCallback): void; + + /** + * Calls ListDatabases. + * @param request ListDatabasesRequest message or plain object + * @returns Promise + */ + public listDatabases(request: google.firestore.admin.v1.IListDatabasesRequest): Promise; + + /** + * Calls UpdateDatabase. + * @param request UpdateDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public updateDatabase(request: google.firestore.admin.v1.IUpdateDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateDatabaseCallback): void; + + /** + * Calls UpdateDatabase. + * @param request UpdateDatabaseRequest message or plain object + * @returns Promise + */ + public updateDatabase(request: google.firestore.admin.v1.IUpdateDatabaseRequest): Promise; + + /** + * Calls DeleteDatabase. + * @param request DeleteDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public deleteDatabase(request: google.firestore.admin.v1.IDeleteDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteDatabaseCallback): void; + + /** + * Calls DeleteDatabase. + * @param request DeleteDatabaseRequest message or plain object + * @returns Promise + */ + public deleteDatabase(request: google.firestore.admin.v1.IDeleteDatabaseRequest): Promise; + + /** + * Calls CreateUserCreds. + * @param request CreateUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserCreds + */ + public createUserCreds(request: google.firestore.admin.v1.ICreateUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateUserCredsCallback): void; + + /** + * Calls CreateUserCreds. + * @param request CreateUserCredsRequest message or plain object + * @returns Promise + */ + public createUserCreds(request: google.firestore.admin.v1.ICreateUserCredsRequest): Promise; + + /** + * Calls GetUserCreds. + * @param request GetUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserCreds + */ + public getUserCreds(request: google.firestore.admin.v1.IGetUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetUserCredsCallback): void; + + /** + * Calls GetUserCreds. + * @param request GetUserCredsRequest message or plain object + * @returns Promise + */ + public getUserCreds(request: google.firestore.admin.v1.IGetUserCredsRequest): Promise; + + /** + * Calls ListUserCreds. + * @param request ListUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListUserCredsResponse + */ + public listUserCreds(request: google.firestore.admin.v1.IListUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListUserCredsCallback): void; + + /** + * Calls ListUserCreds. + * @param request ListUserCredsRequest message or plain object + * @returns Promise + */ + public listUserCreds(request: google.firestore.admin.v1.IListUserCredsRequest): Promise; + + /** + * Calls EnableUserCreds. + * @param request EnableUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserCreds + */ + public enableUserCreds(request: google.firestore.admin.v1.IEnableUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.EnableUserCredsCallback): void; + + /** + * Calls EnableUserCreds. + * @param request EnableUserCredsRequest message or plain object + * @returns Promise + */ + public enableUserCreds(request: google.firestore.admin.v1.IEnableUserCredsRequest): Promise; + + /** + * Calls DisableUserCreds. + * @param request DisableUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserCreds + */ + public disableUserCreds(request: google.firestore.admin.v1.IDisableUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DisableUserCredsCallback): void; + + /** + * Calls DisableUserCreds. + * @param request DisableUserCredsRequest message or plain object + * @returns Promise + */ + public disableUserCreds(request: google.firestore.admin.v1.IDisableUserCredsRequest): Promise; + + /** + * Calls ResetUserPassword. + * @param request ResetUserPasswordRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserCreds + */ + public resetUserPassword(request: google.firestore.admin.v1.IResetUserPasswordRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ResetUserPasswordCallback): void; + + /** + * Calls ResetUserPassword. + * @param request ResetUserPasswordRequest message or plain object + * @returns Promise + */ + public resetUserPassword(request: google.firestore.admin.v1.IResetUserPasswordRequest): Promise; + + /** + * Calls DeleteUserCreds. + * @param request DeleteUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteUserCreds(request: google.firestore.admin.v1.IDeleteUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteUserCredsCallback): void; + + /** + * Calls DeleteUserCreds. + * @param request DeleteUserCredsRequest message or plain object + * @returns Promise + */ + public deleteUserCreds(request: google.firestore.admin.v1.IDeleteUserCredsRequest): Promise; + + /** + * Calls GetBackup. + * @param request GetBackupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Backup + */ + public getBackup(request: google.firestore.admin.v1.IGetBackupRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetBackupCallback): void; + + /** + * Calls GetBackup. + * @param request GetBackupRequest message or plain object + * @returns Promise + */ + public getBackup(request: google.firestore.admin.v1.IGetBackupRequest): Promise; + + /** + * Calls ListBackups. + * @param request ListBackupsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListBackupsResponse + */ + public listBackups(request: google.firestore.admin.v1.IListBackupsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListBackupsCallback): void; + + /** + * Calls ListBackups. + * @param request ListBackupsRequest message or plain object + * @returns Promise + */ + public listBackups(request: google.firestore.admin.v1.IListBackupsRequest): Promise; + + /** + * Calls DeleteBackup. + * @param request DeleteBackupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteBackup(request: google.firestore.admin.v1.IDeleteBackupRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteBackupCallback): void; + + /** + * Calls DeleteBackup. + * @param request DeleteBackupRequest message or plain object + * @returns Promise + */ + public deleteBackup(request: google.firestore.admin.v1.IDeleteBackupRequest): Promise; + + /** + * Calls RestoreDatabase. + * @param request RestoreDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public restoreDatabase(request: google.firestore.admin.v1.IRestoreDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.RestoreDatabaseCallback): void; + + /** + * Calls RestoreDatabase. + * @param request RestoreDatabaseRequest message or plain object + * @returns Promise + */ + public restoreDatabase(request: google.firestore.admin.v1.IRestoreDatabaseRequest): Promise; + + /** + * Calls CreateBackupSchedule. + * @param request CreateBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public createBackupSchedule(request: google.firestore.admin.v1.ICreateBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateBackupScheduleCallback): void; + + /** + * Calls CreateBackupSchedule. + * @param request CreateBackupScheduleRequest message or plain object + * @returns Promise + */ + public createBackupSchedule(request: google.firestore.admin.v1.ICreateBackupScheduleRequest): Promise; + + /** + * Calls GetBackupSchedule. + * @param request GetBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public getBackupSchedule(request: google.firestore.admin.v1.IGetBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetBackupScheduleCallback): void; + + /** + * Calls GetBackupSchedule. + * @param request GetBackupScheduleRequest message or plain object + * @returns Promise + */ + public getBackupSchedule(request: google.firestore.admin.v1.IGetBackupScheduleRequest): Promise; + + /** + * Calls ListBackupSchedules. + * @param request ListBackupSchedulesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListBackupSchedulesResponse + */ + public listBackupSchedules(request: google.firestore.admin.v1.IListBackupSchedulesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListBackupSchedulesCallback): void; + + /** + * Calls ListBackupSchedules. + * @param request ListBackupSchedulesRequest message or plain object + * @returns Promise + */ + public listBackupSchedules(request: google.firestore.admin.v1.IListBackupSchedulesRequest): Promise; + + /** + * Calls UpdateBackupSchedule. + * @param request UpdateBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public updateBackupSchedule(request: google.firestore.admin.v1.IUpdateBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateBackupScheduleCallback): void; + + /** + * Calls UpdateBackupSchedule. + * @param request UpdateBackupScheduleRequest message or plain object + * @returns Promise + */ + public updateBackupSchedule(request: google.firestore.admin.v1.IUpdateBackupScheduleRequest): Promise; + + /** + * Calls DeleteBackupSchedule. + * @param request DeleteBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteBackupSchedule(request: google.firestore.admin.v1.IDeleteBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteBackupScheduleCallback): void; + + /** + * Calls DeleteBackupSchedule. + * @param request DeleteBackupScheduleRequest message or plain object + * @returns Promise + */ + public deleteBackupSchedule(request: google.firestore.admin.v1.IDeleteBackupScheduleRequest): Promise; + + /** + * Calls CloneDatabase. + * @param request CloneDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public cloneDatabase(request: google.firestore.admin.v1.ICloneDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CloneDatabaseCallback): void; + + /** + * Calls CloneDatabase. + * @param request CloneDatabaseRequest message or plain object + * @returns Promise + */ + public cloneDatabase(request: google.firestore.admin.v1.ICloneDatabaseRequest): Promise; + } + + namespace FirestoreAdmin { + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createIndex}. + * @param error Error, if any + * @param [response] Operation + */ + type CreateIndexCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listIndexes}. + * @param error Error, if any + * @param [response] ListIndexesResponse + */ + type ListIndexesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListIndexesResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getIndex}. + * @param error Error, if any + * @param [response] Index + */ + type GetIndexCallback = (error: (Error|null), response?: google.firestore.admin.v1.Index) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteIndex}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteIndexCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getField}. + * @param error Error, if any + * @param [response] Field + */ + type GetFieldCallback = (error: (Error|null), response?: google.firestore.admin.v1.Field) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateField}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateFieldCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listFields}. + * @param error Error, if any + * @param [response] ListFieldsResponse + */ + type ListFieldsCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListFieldsResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#exportDocuments}. + * @param error Error, if any + * @param [response] Operation + */ + type ExportDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#importDocuments}. + * @param error Error, if any + * @param [response] Operation + */ + type ImportDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#bulkDeleteDocuments}. + * @param error Error, if any + * @param [response] Operation + */ + type BulkDeleteDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type CreateDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getDatabase}. + * @param error Error, if any + * @param [response] Database + */ + type GetDatabaseCallback = (error: (Error|null), response?: google.firestore.admin.v1.Database) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listDatabases}. + * @param error Error, if any + * @param [response] ListDatabasesResponse + */ + type ListDatabasesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListDatabasesResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type DeleteDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createUserCreds}. + * @param error Error, if any + * @param [response] UserCreds + */ + type CreateUserCredsCallback = (error: (Error|null), response?: google.firestore.admin.v1.UserCreds) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getUserCreds}. + * @param error Error, if any + * @param [response] UserCreds + */ + type GetUserCredsCallback = (error: (Error|null), response?: google.firestore.admin.v1.UserCreds) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listUserCreds}. + * @param error Error, if any + * @param [response] ListUserCredsResponse + */ + type ListUserCredsCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListUserCredsResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#enableUserCreds}. + * @param error Error, if any + * @param [response] UserCreds + */ + type EnableUserCredsCallback = (error: (Error|null), response?: google.firestore.admin.v1.UserCreds) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#disableUserCreds}. + * @param error Error, if any + * @param [response] UserCreds + */ + type DisableUserCredsCallback = (error: (Error|null), response?: google.firestore.admin.v1.UserCreds) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#resetUserPassword}. + * @param error Error, if any + * @param [response] UserCreds + */ + type ResetUserPasswordCallback = (error: (Error|null), response?: google.firestore.admin.v1.UserCreds) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteUserCreds}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteUserCredsCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getBackup}. + * @param error Error, if any + * @param [response] Backup + */ + type GetBackupCallback = (error: (Error|null), response?: google.firestore.admin.v1.Backup) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listBackups}. + * @param error Error, if any + * @param [response] ListBackupsResponse + */ + type ListBackupsCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListBackupsResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteBackup}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteBackupCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#restoreDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type RestoreDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type CreateBackupScheduleCallback = (error: (Error|null), response?: google.firestore.admin.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type GetBackupScheduleCallback = (error: (Error|null), response?: google.firestore.admin.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listBackupSchedules}. + * @param error Error, if any + * @param [response] ListBackupSchedulesResponse + */ + type ListBackupSchedulesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListBackupSchedulesResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type UpdateBackupScheduleCallback = (error: (Error|null), response?: google.firestore.admin.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteBackupSchedule}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteBackupScheduleCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#cloneDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type CloneDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of a ListDatabasesRequest. */ + interface IListDatabasesRequest { + + /** ListDatabasesRequest parent */ + parent?: (string|null); + + /** ListDatabasesRequest showDeleted */ + showDeleted?: (boolean|null); + } + + /** Represents a ListDatabasesRequest. */ + class ListDatabasesRequest implements IListDatabasesRequest { + + /** + * Constructs a new ListDatabasesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListDatabasesRequest); + + /** ListDatabasesRequest parent. */ + public parent: string; + + /** ListDatabasesRequest showDeleted. */ + public showDeleted: boolean; + + /** + * Creates a ListDatabasesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDatabasesRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListDatabasesRequest; + + /** + * Creates a plain object from a ListDatabasesRequest message. Also converts values to other types if specified. + * @param message ListDatabasesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListDatabasesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDatabasesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDatabasesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDatabaseRequest. */ + interface ICreateDatabaseRequest { + + /** CreateDatabaseRequest parent */ + parent?: (string|null); + + /** CreateDatabaseRequest database */ + database?: (google.firestore.admin.v1.IDatabase|null); + + /** CreateDatabaseRequest databaseId */ + databaseId?: (string|null); + } + + /** Represents a CreateDatabaseRequest. */ + class CreateDatabaseRequest implements ICreateDatabaseRequest { + + /** + * Constructs a new CreateDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateDatabaseRequest); + + /** CreateDatabaseRequest parent. */ + public parent: string; + + /** CreateDatabaseRequest database. */ + public database?: (google.firestore.admin.v1.IDatabase|null); + + /** CreateDatabaseRequest databaseId. */ + public databaseId: string; + + /** + * Creates a CreateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateDatabaseRequest; + + /** + * Creates a plain object from a CreateDatabaseRequest message. Also converts values to other types if specified. + * @param message CreateDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDatabaseMetadata. */ + interface ICreateDatabaseMetadata { + } + + /** Represents a CreateDatabaseMetadata. */ + class CreateDatabaseMetadata implements ICreateDatabaseMetadata { + + /** + * Constructs a new CreateDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateDatabaseMetadata); + + /** + * Creates a CreateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateDatabaseMetadata; + + /** + * Creates a plain object from a CreateDatabaseMetadata message. Also converts values to other types if specified. + * @param message CreateDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDatabasesResponse. */ + interface IListDatabasesResponse { + + /** ListDatabasesResponse databases */ + databases?: (google.firestore.admin.v1.IDatabase[]|null); + + /** ListDatabasesResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListDatabasesResponse. */ + class ListDatabasesResponse implements IListDatabasesResponse { + + /** + * Constructs a new ListDatabasesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListDatabasesResponse); + + /** ListDatabasesResponse databases. */ + public databases: google.firestore.admin.v1.IDatabase[]; + + /** ListDatabasesResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a ListDatabasesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDatabasesResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListDatabasesResponse; + + /** + * Creates a plain object from a ListDatabasesResponse message. Also converts values to other types if specified. + * @param message ListDatabasesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListDatabasesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDatabasesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDatabasesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetDatabaseRequest. */ + interface IGetDatabaseRequest { + + /** GetDatabaseRequest name */ + name?: (string|null); + } + + /** Represents a GetDatabaseRequest. */ + class GetDatabaseRequest implements IGetDatabaseRequest { + + /** + * Constructs a new GetDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetDatabaseRequest); + + /** GetDatabaseRequest name. */ + public name: string; + + /** + * Creates a GetDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetDatabaseRequest; + + /** + * Creates a plain object from a GetDatabaseRequest message. Also converts values to other types if specified. + * @param message GetDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDatabaseRequest. */ + interface IUpdateDatabaseRequest { + + /** UpdateDatabaseRequest database */ + database?: (google.firestore.admin.v1.IDatabase|null); + + /** UpdateDatabaseRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateDatabaseRequest. */ + class UpdateDatabaseRequest implements IUpdateDatabaseRequest { + + /** + * Constructs a new UpdateDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateDatabaseRequest); + + /** UpdateDatabaseRequest database. */ + public database?: (google.firestore.admin.v1.IDatabase|null); + + /** UpdateDatabaseRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates an UpdateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateDatabaseRequest; + + /** + * Creates a plain object from an UpdateDatabaseRequest message. Also converts values to other types if specified. + * @param message UpdateDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDatabaseMetadata. */ + interface IUpdateDatabaseMetadata { + } + + /** Represents an UpdateDatabaseMetadata. */ + class UpdateDatabaseMetadata implements IUpdateDatabaseMetadata { + + /** + * Constructs a new UpdateDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateDatabaseMetadata); + + /** + * Creates an UpdateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateDatabaseMetadata; + + /** + * Creates a plain object from an UpdateDatabaseMetadata message. Also converts values to other types if specified. + * @param message UpdateDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDatabaseRequest. */ + interface IDeleteDatabaseRequest { + + /** DeleteDatabaseRequest name */ + name?: (string|null); + + /** DeleteDatabaseRequest etag */ + etag?: (string|null); + } + + /** Represents a DeleteDatabaseRequest. */ + class DeleteDatabaseRequest implements IDeleteDatabaseRequest { + + /** + * Constructs a new DeleteDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteDatabaseRequest); + + /** DeleteDatabaseRequest name. */ + public name: string; + + /** DeleteDatabaseRequest etag. */ + public etag: string; + + /** + * Creates a DeleteDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteDatabaseRequest; + + /** + * Creates a plain object from a DeleteDatabaseRequest message. Also converts values to other types if specified. + * @param message DeleteDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDatabaseMetadata. */ + interface IDeleteDatabaseMetadata { + } + + /** Represents a DeleteDatabaseMetadata. */ + class DeleteDatabaseMetadata implements IDeleteDatabaseMetadata { + + /** + * Constructs a new DeleteDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteDatabaseMetadata); + + /** + * Creates a DeleteDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteDatabaseMetadata; + + /** + * Creates a plain object from a DeleteDatabaseMetadata message. Also converts values to other types if specified. + * @param message DeleteDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateUserCredsRequest. */ + interface ICreateUserCredsRequest { + + /** CreateUserCredsRequest parent */ + parent?: (string|null); + + /** CreateUserCredsRequest userCreds */ + userCreds?: (google.firestore.admin.v1.IUserCreds|null); + + /** CreateUserCredsRequest userCredsId */ + userCredsId?: (string|null); + } + + /** Represents a CreateUserCredsRequest. */ + class CreateUserCredsRequest implements ICreateUserCredsRequest { + + /** + * Constructs a new CreateUserCredsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateUserCredsRequest); + + /** CreateUserCredsRequest parent. */ + public parent: string; + + /** CreateUserCredsRequest userCreds. */ + public userCreds?: (google.firestore.admin.v1.IUserCreds|null); + + /** CreateUserCredsRequest userCredsId. */ + public userCredsId: string; + + /** + * Creates a CreateUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateUserCredsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateUserCredsRequest; + + /** + * Creates a plain object from a CreateUserCredsRequest message. Also converts values to other types if specified. + * @param message CreateUserCredsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateUserCredsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateUserCredsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetUserCredsRequest. */ + interface IGetUserCredsRequest { + + /** GetUserCredsRequest name */ + name?: (string|null); + } + + /** Represents a GetUserCredsRequest. */ + class GetUserCredsRequest implements IGetUserCredsRequest { + + /** + * Constructs a new GetUserCredsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetUserCredsRequest); + + /** GetUserCredsRequest name. */ + public name: string; + + /** + * Creates a GetUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetUserCredsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetUserCredsRequest; + + /** + * Creates a plain object from a GetUserCredsRequest message. Also converts values to other types if specified. + * @param message GetUserCredsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetUserCredsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetUserCredsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListUserCredsRequest. */ + interface IListUserCredsRequest { + + /** ListUserCredsRequest parent */ + parent?: (string|null); + } + + /** Represents a ListUserCredsRequest. */ + class ListUserCredsRequest implements IListUserCredsRequest { + + /** + * Constructs a new ListUserCredsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListUserCredsRequest); + + /** ListUserCredsRequest parent. */ + public parent: string; + + /** + * Creates a ListUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListUserCredsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListUserCredsRequest; + + /** + * Creates a plain object from a ListUserCredsRequest message. Also converts values to other types if specified. + * @param message ListUserCredsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListUserCredsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListUserCredsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListUserCredsResponse. */ + interface IListUserCredsResponse { + + /** ListUserCredsResponse userCreds */ + userCreds?: (google.firestore.admin.v1.IUserCreds[]|null); + } + + /** Represents a ListUserCredsResponse. */ + class ListUserCredsResponse implements IListUserCredsResponse { + + /** + * Constructs a new ListUserCredsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListUserCredsResponse); + + /** ListUserCredsResponse userCreds. */ + public userCreds: google.firestore.admin.v1.IUserCreds[]; + + /** + * Creates a ListUserCredsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListUserCredsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListUserCredsResponse; + + /** + * Creates a plain object from a ListUserCredsResponse message. Also converts values to other types if specified. + * @param message ListUserCredsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListUserCredsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListUserCredsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListUserCredsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnableUserCredsRequest. */ + interface IEnableUserCredsRequest { + + /** EnableUserCredsRequest name */ + name?: (string|null); + } + + /** Represents an EnableUserCredsRequest. */ + class EnableUserCredsRequest implements IEnableUserCredsRequest { + + /** + * Constructs a new EnableUserCredsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IEnableUserCredsRequest); + + /** EnableUserCredsRequest name. */ + public name: string; + + /** + * Creates an EnableUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnableUserCredsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.EnableUserCredsRequest; + + /** + * Creates a plain object from an EnableUserCredsRequest message. Also converts values to other types if specified. + * @param message EnableUserCredsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.EnableUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnableUserCredsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnableUserCredsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DisableUserCredsRequest. */ + interface IDisableUserCredsRequest { + + /** DisableUserCredsRequest name */ + name?: (string|null); + } + + /** Represents a DisableUserCredsRequest. */ + class DisableUserCredsRequest implements IDisableUserCredsRequest { + + /** + * Constructs a new DisableUserCredsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDisableUserCredsRequest); + + /** DisableUserCredsRequest name. */ + public name: string; + + /** + * Creates a DisableUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DisableUserCredsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DisableUserCredsRequest; + + /** + * Creates a plain object from a DisableUserCredsRequest message. Also converts values to other types if specified. + * @param message DisableUserCredsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DisableUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DisableUserCredsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DisableUserCredsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ResetUserPasswordRequest. */ + interface IResetUserPasswordRequest { + + /** ResetUserPasswordRequest name */ + name?: (string|null); + } + + /** Represents a ResetUserPasswordRequest. */ + class ResetUserPasswordRequest implements IResetUserPasswordRequest { + + /** + * Constructs a new ResetUserPasswordRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IResetUserPasswordRequest); + + /** ResetUserPasswordRequest name. */ + public name: string; + + /** + * Creates a ResetUserPasswordRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResetUserPasswordRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ResetUserPasswordRequest; + + /** + * Creates a plain object from a ResetUserPasswordRequest message. Also converts values to other types if specified. + * @param message ResetUserPasswordRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ResetUserPasswordRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResetUserPasswordRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResetUserPasswordRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteUserCredsRequest. */ + interface IDeleteUserCredsRequest { + + /** DeleteUserCredsRequest name */ + name?: (string|null); + } + + /** Represents a DeleteUserCredsRequest. */ + class DeleteUserCredsRequest implements IDeleteUserCredsRequest { + + /** + * Constructs a new DeleteUserCredsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteUserCredsRequest); + + /** DeleteUserCredsRequest name. */ + public name: string; + + /** + * Creates a DeleteUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteUserCredsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteUserCredsRequest; + + /** + * Creates a plain object from a DeleteUserCredsRequest message. Also converts values to other types if specified. + * @param message DeleteUserCredsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteUserCredsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteUserCredsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateBackupScheduleRequest. */ + interface ICreateBackupScheduleRequest { + + /** CreateBackupScheduleRequest parent */ + parent?: (string|null); + + /** CreateBackupScheduleRequest backupSchedule */ + backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + } + + /** Represents a CreateBackupScheduleRequest. */ + class CreateBackupScheduleRequest implements ICreateBackupScheduleRequest { + + /** + * Constructs a new CreateBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateBackupScheduleRequest); + + /** CreateBackupScheduleRequest parent. */ + public parent: string; + + /** CreateBackupScheduleRequest backupSchedule. */ + public backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + + /** + * Creates a CreateBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateBackupScheduleRequest; + + /** + * Creates a plain object from a CreateBackupScheduleRequest message. Also converts values to other types if specified. + * @param message CreateBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetBackupScheduleRequest. */ + interface IGetBackupScheduleRequest { + + /** GetBackupScheduleRequest name */ + name?: (string|null); + } + + /** Represents a GetBackupScheduleRequest. */ + class GetBackupScheduleRequest implements IGetBackupScheduleRequest { + + /** + * Constructs a new GetBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetBackupScheduleRequest); + + /** GetBackupScheduleRequest name. */ + public name: string; + + /** + * Creates a GetBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetBackupScheduleRequest; + + /** + * Creates a plain object from a GetBackupScheduleRequest message. Also converts values to other types if specified. + * @param message GetBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateBackupScheduleRequest. */ + interface IUpdateBackupScheduleRequest { + + /** UpdateBackupScheduleRequest backupSchedule */ + backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + + /** UpdateBackupScheduleRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateBackupScheduleRequest. */ + class UpdateBackupScheduleRequest implements IUpdateBackupScheduleRequest { + + /** + * Constructs a new UpdateBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateBackupScheduleRequest); + + /** UpdateBackupScheduleRequest backupSchedule. */ + public backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + + /** UpdateBackupScheduleRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates an UpdateBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateBackupScheduleRequest; + + /** + * Creates a plain object from an UpdateBackupScheduleRequest message. Also converts values to other types if specified. + * @param message UpdateBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupSchedulesRequest. */ + interface IListBackupSchedulesRequest { + + /** ListBackupSchedulesRequest parent */ + parent?: (string|null); + } + + /** Represents a ListBackupSchedulesRequest. */ + class ListBackupSchedulesRequest implements IListBackupSchedulesRequest { + + /** + * Constructs a new ListBackupSchedulesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupSchedulesRequest); + + /** ListBackupSchedulesRequest parent. */ + public parent: string; + + /** + * Creates a ListBackupSchedulesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupSchedulesRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupSchedulesRequest; + + /** + * Creates a plain object from a ListBackupSchedulesRequest message. Also converts values to other types if specified. + * @param message ListBackupSchedulesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupSchedulesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupSchedulesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupSchedulesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupSchedulesResponse. */ + interface IListBackupSchedulesResponse { + + /** ListBackupSchedulesResponse backupSchedules */ + backupSchedules?: (google.firestore.admin.v1.IBackupSchedule[]|null); + } + + /** Represents a ListBackupSchedulesResponse. */ + class ListBackupSchedulesResponse implements IListBackupSchedulesResponse { + + /** + * Constructs a new ListBackupSchedulesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupSchedulesResponse); + + /** ListBackupSchedulesResponse backupSchedules. */ + public backupSchedules: google.firestore.admin.v1.IBackupSchedule[]; + + /** + * Creates a ListBackupSchedulesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupSchedulesResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupSchedulesResponse; + + /** + * Creates a plain object from a ListBackupSchedulesResponse message. Also converts values to other types if specified. + * @param message ListBackupSchedulesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupSchedulesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupSchedulesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupSchedulesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteBackupScheduleRequest. */ + interface IDeleteBackupScheduleRequest { + + /** DeleteBackupScheduleRequest name */ + name?: (string|null); + } + + /** Represents a DeleteBackupScheduleRequest. */ + class DeleteBackupScheduleRequest implements IDeleteBackupScheduleRequest { + + /** + * Constructs a new DeleteBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteBackupScheduleRequest); + + /** DeleteBackupScheduleRequest name. */ + public name: string; + + /** + * Creates a DeleteBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteBackupScheduleRequest; + + /** + * Creates a plain object from a DeleteBackupScheduleRequest message. Also converts values to other types if specified. + * @param message DeleteBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateIndexRequest. */ + interface ICreateIndexRequest { + + /** CreateIndexRequest parent */ + parent?: (string|null); + + /** CreateIndexRequest index */ + index?: (google.firestore.admin.v1.IIndex|null); + } + + /** Represents a CreateIndexRequest. */ + class CreateIndexRequest implements ICreateIndexRequest { + + /** + * Constructs a new CreateIndexRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateIndexRequest); + + /** CreateIndexRequest parent. */ + public parent: string; + + /** CreateIndexRequest index. */ + public index?: (google.firestore.admin.v1.IIndex|null); + + /** + * Creates a CreateIndexRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateIndexRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateIndexRequest; + + /** + * Creates a plain object from a CreateIndexRequest message. Also converts values to other types if specified. + * @param message CreateIndexRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateIndexRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateIndexRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListIndexesRequest. */ + interface IListIndexesRequest { + + /** ListIndexesRequest parent */ + parent?: (string|null); + + /** ListIndexesRequest filter */ + filter?: (string|null); + + /** ListIndexesRequest pageSize */ + pageSize?: (number|null); + + /** ListIndexesRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListIndexesRequest. */ + class ListIndexesRequest implements IListIndexesRequest { + + /** + * Constructs a new ListIndexesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListIndexesRequest); + + /** ListIndexesRequest parent. */ + public parent: string; + + /** ListIndexesRequest filter. */ + public filter: string; + + /** ListIndexesRequest pageSize. */ + public pageSize: number; + + /** ListIndexesRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListIndexesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListIndexesRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListIndexesRequest; + + /** + * Creates a plain object from a ListIndexesRequest message. Also converts values to other types if specified. + * @param message ListIndexesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListIndexesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListIndexesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListIndexesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListIndexesResponse. */ + interface IListIndexesResponse { + + /** ListIndexesResponse indexes */ + indexes?: (google.firestore.admin.v1.IIndex[]|null); + + /** ListIndexesResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListIndexesResponse. */ + class ListIndexesResponse implements IListIndexesResponse { + + /** + * Constructs a new ListIndexesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListIndexesResponse); + + /** ListIndexesResponse indexes. */ + public indexes: google.firestore.admin.v1.IIndex[]; + + /** ListIndexesResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListIndexesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListIndexesResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListIndexesResponse; + + /** + * Creates a plain object from a ListIndexesResponse message. Also converts values to other types if specified. + * @param message ListIndexesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListIndexesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListIndexesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListIndexesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetIndexRequest. */ + interface IGetIndexRequest { + + /** GetIndexRequest name */ + name?: (string|null); + } + + /** Represents a GetIndexRequest. */ + class GetIndexRequest implements IGetIndexRequest { + + /** + * Constructs a new GetIndexRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetIndexRequest); + + /** GetIndexRequest name. */ + public name: string; + + /** + * Creates a GetIndexRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetIndexRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetIndexRequest; + + /** + * Creates a plain object from a GetIndexRequest message. Also converts values to other types if specified. + * @param message GetIndexRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetIndexRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetIndexRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteIndexRequest. */ + interface IDeleteIndexRequest { + + /** DeleteIndexRequest name */ + name?: (string|null); + } + + /** Represents a DeleteIndexRequest. */ + class DeleteIndexRequest implements IDeleteIndexRequest { + + /** + * Constructs a new DeleteIndexRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteIndexRequest); + + /** DeleteIndexRequest name. */ + public name: string; + + /** + * Creates a DeleteIndexRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteIndexRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteIndexRequest; + + /** + * Creates a plain object from a DeleteIndexRequest message. Also converts values to other types if specified. + * @param message DeleteIndexRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteIndexRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteIndexRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateFieldRequest. */ + interface IUpdateFieldRequest { + + /** UpdateFieldRequest field */ + field?: (google.firestore.admin.v1.IField|null); + + /** UpdateFieldRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateFieldRequest. */ + class UpdateFieldRequest implements IUpdateFieldRequest { + + /** + * Constructs a new UpdateFieldRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateFieldRequest); + + /** UpdateFieldRequest field. */ + public field?: (google.firestore.admin.v1.IField|null); + + /** UpdateFieldRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates an UpdateFieldRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateFieldRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateFieldRequest; + + /** + * Creates a plain object from an UpdateFieldRequest message. Also converts values to other types if specified. + * @param message UpdateFieldRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateFieldRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateFieldRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateFieldRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetFieldRequest. */ + interface IGetFieldRequest { + + /** GetFieldRequest name */ + name?: (string|null); + } + + /** Represents a GetFieldRequest. */ + class GetFieldRequest implements IGetFieldRequest { + + /** + * Constructs a new GetFieldRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetFieldRequest); + + /** GetFieldRequest name. */ + public name: string; + + /** + * Creates a GetFieldRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetFieldRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetFieldRequest; + + /** + * Creates a plain object from a GetFieldRequest message. Also converts values to other types if specified. + * @param message GetFieldRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetFieldRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetFieldRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetFieldRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListFieldsRequest. */ + interface IListFieldsRequest { + + /** ListFieldsRequest parent */ + parent?: (string|null); + + /** ListFieldsRequest filter */ + filter?: (string|null); + + /** ListFieldsRequest pageSize */ + pageSize?: (number|null); + + /** ListFieldsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListFieldsRequest. */ + class ListFieldsRequest implements IListFieldsRequest { + + /** + * Constructs a new ListFieldsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListFieldsRequest); + + /** ListFieldsRequest parent. */ + public parent: string; + + /** ListFieldsRequest filter. */ + public filter: string; + + /** ListFieldsRequest pageSize. */ + public pageSize: number; + + /** ListFieldsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListFieldsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListFieldsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListFieldsRequest; + + /** + * Creates a plain object from a ListFieldsRequest message. Also converts values to other types if specified. + * @param message ListFieldsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListFieldsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListFieldsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListFieldsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListFieldsResponse. */ + interface IListFieldsResponse { + + /** ListFieldsResponse fields */ + fields?: (google.firestore.admin.v1.IField[]|null); + + /** ListFieldsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListFieldsResponse. */ + class ListFieldsResponse implements IListFieldsResponse { + + /** + * Constructs a new ListFieldsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListFieldsResponse); + + /** ListFieldsResponse fields. */ + public fields: google.firestore.admin.v1.IField[]; + + /** ListFieldsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListFieldsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListFieldsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListFieldsResponse; + + /** + * Creates a plain object from a ListFieldsResponse message. Also converts values to other types if specified. + * @param message ListFieldsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListFieldsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListFieldsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListFieldsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExportDocumentsRequest. */ + interface IExportDocumentsRequest { + + /** ExportDocumentsRequest name */ + name?: (string|null); + + /** ExportDocumentsRequest collectionIds */ + collectionIds?: (string[]|null); + + /** ExportDocumentsRequest outputUriPrefix */ + outputUriPrefix?: (string|null); + + /** ExportDocumentsRequest namespaceIds */ + namespaceIds?: (string[]|null); + + /** ExportDocumentsRequest snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an ExportDocumentsRequest. */ + class ExportDocumentsRequest implements IExportDocumentsRequest { + + /** + * Constructs a new ExportDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IExportDocumentsRequest); + + /** ExportDocumentsRequest name. */ + public name: string; + + /** ExportDocumentsRequest collectionIds. */ + public collectionIds: string[]; + + /** ExportDocumentsRequest outputUriPrefix. */ + public outputUriPrefix: string; + + /** ExportDocumentsRequest namespaceIds. */ + public namespaceIds: string[]; + + /** ExportDocumentsRequest snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates an ExportDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExportDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsRequest; + + /** + * Creates a plain object from an ExportDocumentsRequest message. Also converts values to other types if specified. + * @param message ExportDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ExportDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExportDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExportDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ImportDocumentsRequest. */ + interface IImportDocumentsRequest { + + /** ImportDocumentsRequest name */ + name?: (string|null); + + /** ImportDocumentsRequest collectionIds */ + collectionIds?: (string[]|null); + + /** ImportDocumentsRequest inputUriPrefix */ + inputUriPrefix?: (string|null); + + /** ImportDocumentsRequest namespaceIds */ + namespaceIds?: (string[]|null); + } + + /** Represents an ImportDocumentsRequest. */ + class ImportDocumentsRequest implements IImportDocumentsRequest { + + /** + * Constructs a new ImportDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IImportDocumentsRequest); + + /** ImportDocumentsRequest name. */ + public name: string; + + /** ImportDocumentsRequest collectionIds. */ + public collectionIds: string[]; + + /** ImportDocumentsRequest inputUriPrefix. */ + public inputUriPrefix: string; + + /** ImportDocumentsRequest namespaceIds. */ + public namespaceIds: string[]; + + /** + * Creates an ImportDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ImportDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ImportDocumentsRequest; + + /** + * Creates a plain object from an ImportDocumentsRequest message. Also converts values to other types if specified. + * @param message ImportDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ImportDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ImportDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ImportDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BulkDeleteDocumentsRequest. */ + interface IBulkDeleteDocumentsRequest { + + /** BulkDeleteDocumentsRequest name */ + name?: (string|null); + + /** BulkDeleteDocumentsRequest collectionIds */ + collectionIds?: (string[]|null); + + /** BulkDeleteDocumentsRequest namespaceIds */ + namespaceIds?: (string[]|null); + } + + /** Represents a BulkDeleteDocumentsRequest. */ + class BulkDeleteDocumentsRequest implements IBulkDeleteDocumentsRequest { + + /** + * Constructs a new BulkDeleteDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsRequest); + + /** BulkDeleteDocumentsRequest name. */ + public name: string; + + /** BulkDeleteDocumentsRequest collectionIds. */ + public collectionIds: string[]; + + /** BulkDeleteDocumentsRequest namespaceIds. */ + public namespaceIds: string[]; + + /** + * Creates a BulkDeleteDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsRequest; + + /** + * Creates a plain object from a BulkDeleteDocumentsRequest message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BulkDeleteDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BulkDeleteDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BulkDeleteDocumentsResponse. */ + interface IBulkDeleteDocumentsResponse { + } + + /** Represents a BulkDeleteDocumentsResponse. */ + class BulkDeleteDocumentsResponse implements IBulkDeleteDocumentsResponse { + + /** + * Constructs a new BulkDeleteDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsResponse); + + /** + * Creates a BulkDeleteDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsResponse; + + /** + * Creates a plain object from a BulkDeleteDocumentsResponse message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BulkDeleteDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BulkDeleteDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetBackupRequest. */ + interface IGetBackupRequest { + + /** GetBackupRequest name */ + name?: (string|null); + } + + /** Represents a GetBackupRequest. */ + class GetBackupRequest implements IGetBackupRequest { + + /** + * Constructs a new GetBackupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetBackupRequest); + + /** GetBackupRequest name. */ + public name: string; + + /** + * Creates a GetBackupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetBackupRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetBackupRequest; + + /** + * Creates a plain object from a GetBackupRequest message. Also converts values to other types if specified. + * @param message GetBackupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetBackupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetBackupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupsRequest. */ + interface IListBackupsRequest { + + /** ListBackupsRequest parent */ + parent?: (string|null); + + /** ListBackupsRequest filter */ + filter?: (string|null); + } + + /** Represents a ListBackupsRequest. */ + class ListBackupsRequest implements IListBackupsRequest { + + /** + * Constructs a new ListBackupsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupsRequest); + + /** ListBackupsRequest parent. */ + public parent: string; + + /** ListBackupsRequest filter. */ + public filter: string; + + /** + * Creates a ListBackupsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupsRequest; + + /** + * Creates a plain object from a ListBackupsRequest message. Also converts values to other types if specified. + * @param message ListBackupsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupsResponse. */ + interface IListBackupsResponse { + + /** ListBackupsResponse backups */ + backups?: (google.firestore.admin.v1.IBackup[]|null); + + /** ListBackupsResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListBackupsResponse. */ + class ListBackupsResponse implements IListBackupsResponse { + + /** + * Constructs a new ListBackupsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupsResponse); + + /** ListBackupsResponse backups. */ + public backups: google.firestore.admin.v1.IBackup[]; + + /** ListBackupsResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a ListBackupsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupsResponse; + + /** + * Creates a plain object from a ListBackupsResponse message. Also converts values to other types if specified. + * @param message ListBackupsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteBackupRequest. */ + interface IDeleteBackupRequest { + + /** DeleteBackupRequest name */ + name?: (string|null); + } + + /** Represents a DeleteBackupRequest. */ + class DeleteBackupRequest implements IDeleteBackupRequest { + + /** + * Constructs a new DeleteBackupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteBackupRequest); + + /** DeleteBackupRequest name. */ + public name: string; + + /** + * Creates a DeleteBackupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteBackupRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteBackupRequest; + + /** + * Creates a plain object from a DeleteBackupRequest message. Also converts values to other types if specified. + * @param message DeleteBackupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteBackupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteBackupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RestoreDatabaseRequest. */ + interface IRestoreDatabaseRequest { + + /** RestoreDatabaseRequest parent */ + parent?: (string|null); + + /** RestoreDatabaseRequest databaseId */ + databaseId?: (string|null); + + /** RestoreDatabaseRequest backup */ + backup?: (string|null); + + /** RestoreDatabaseRequest encryptionConfig */ + encryptionConfig?: (google.firestore.admin.v1.Database.IEncryptionConfig|null); + + /** RestoreDatabaseRequest tags */ + tags?: ({ [k: string]: string }|null); + } + + /** Represents a RestoreDatabaseRequest. */ + class RestoreDatabaseRequest implements IRestoreDatabaseRequest { + + /** + * Constructs a new RestoreDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IRestoreDatabaseRequest); + + /** RestoreDatabaseRequest parent. */ + public parent: string; + + /** RestoreDatabaseRequest databaseId. */ + public databaseId: string; + + /** RestoreDatabaseRequest backup. */ + public backup: string; + + /** RestoreDatabaseRequest encryptionConfig. */ + public encryptionConfig?: (google.firestore.admin.v1.Database.IEncryptionConfig|null); + + /** RestoreDatabaseRequest tags. */ + public tags: { [k: string]: string }; + + /** + * Creates a RestoreDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RestoreDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.RestoreDatabaseRequest; + + /** + * Creates a plain object from a RestoreDatabaseRequest message. Also converts values to other types if specified. + * @param message RestoreDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.RestoreDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RestoreDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RestoreDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CloneDatabaseRequest. */ + interface ICloneDatabaseRequest { + + /** CloneDatabaseRequest parent */ + parent?: (string|null); + + /** CloneDatabaseRequest databaseId */ + databaseId?: (string|null); + + /** CloneDatabaseRequest pitrSnapshot */ + pitrSnapshot?: (google.firestore.admin.v1.IPitrSnapshot|null); + + /** CloneDatabaseRequest encryptionConfig */ + encryptionConfig?: (google.firestore.admin.v1.Database.IEncryptionConfig|null); + + /** CloneDatabaseRequest tags */ + tags?: ({ [k: string]: string }|null); + } + + /** Represents a CloneDatabaseRequest. */ + class CloneDatabaseRequest implements ICloneDatabaseRequest { + + /** + * Constructs a new CloneDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICloneDatabaseRequest); + + /** CloneDatabaseRequest parent. */ + public parent: string; + + /** CloneDatabaseRequest databaseId. */ + public databaseId: string; + + /** CloneDatabaseRequest pitrSnapshot. */ + public pitrSnapshot?: (google.firestore.admin.v1.IPitrSnapshot|null); + + /** CloneDatabaseRequest encryptionConfig. */ + public encryptionConfig?: (google.firestore.admin.v1.Database.IEncryptionConfig|null); + + /** CloneDatabaseRequest tags. */ + public tags: { [k: string]: string }; + + /** + * Creates a CloneDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CloneDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CloneDatabaseRequest; + + /** + * Creates a plain object from a CloneDatabaseRequest message. Also converts values to other types if specified. + * @param message CloneDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CloneDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CloneDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CloneDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an IndexOperationMetadata. */ + interface IIndexOperationMetadata { + + /** IndexOperationMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata index */ + index?: (string|null); + + /** IndexOperationMetadata state */ + state?: (google.firestore.admin.v1.OperationState|null); + + /** IndexOperationMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** IndexOperationMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + } + + /** Represents an IndexOperationMetadata. */ + class IndexOperationMetadata implements IIndexOperationMetadata { + + /** + * Constructs a new IndexOperationMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IIndexOperationMetadata); + + /** IndexOperationMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata index. */ + public index: string; + + /** IndexOperationMetadata state. */ + public state: google.firestore.admin.v1.OperationState; + + /** IndexOperationMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** IndexOperationMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** + * Creates an IndexOperationMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexOperationMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.IndexOperationMetadata; + + /** + * Creates a plain object from an IndexOperationMetadata message. Also converts values to other types if specified. + * @param message IndexOperationMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.IndexOperationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexOperationMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexOperationMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldOperationMetadata. */ + interface IFieldOperationMetadata { + + /** FieldOperationMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata field */ + field?: (string|null); + + /** FieldOperationMetadata indexConfigDeltas */ + indexConfigDeltas?: (google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta[]|null); + + /** FieldOperationMetadata state */ + state?: (google.firestore.admin.v1.OperationState|null); + + /** FieldOperationMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata ttlConfigDelta */ + ttlConfigDelta?: (google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta|null); + } + + /** Represents a FieldOperationMetadata. */ + class FieldOperationMetadata implements IFieldOperationMetadata { + + /** + * Constructs a new FieldOperationMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IFieldOperationMetadata); + + /** FieldOperationMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata field. */ + public field: string; + + /** FieldOperationMetadata indexConfigDeltas. */ + public indexConfigDeltas: google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta[]; + + /** FieldOperationMetadata state. */ + public state: google.firestore.admin.v1.OperationState; + + /** FieldOperationMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata ttlConfigDelta. */ + public ttlConfigDelta?: (google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta|null); + + /** + * Creates a FieldOperationMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOperationMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata; + + /** + * Creates a plain object from a FieldOperationMetadata message. Also converts values to other types if specified. + * @param message FieldOperationMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOperationMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOperationMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldOperationMetadata { + + /** Properties of an IndexConfigDelta. */ + interface IIndexConfigDelta { + + /** IndexConfigDelta changeType */ + changeType?: (google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType|null); + + /** IndexConfigDelta index */ + index?: (google.firestore.admin.v1.IIndex|null); + } + + /** Represents an IndexConfigDelta. */ + class IndexConfigDelta implements IIndexConfigDelta { + + /** + * Constructs a new IndexConfigDelta. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta); + + /** IndexConfigDelta changeType. */ + public changeType: google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType; + + /** IndexConfigDelta index. */ + public index?: (google.firestore.admin.v1.IIndex|null); + + /** + * Creates an IndexConfigDelta message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexConfigDelta + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta; + + /** + * Creates a plain object from an IndexConfigDelta message. Also converts values to other types if specified. + * @param message IndexConfigDelta + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexConfigDelta to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexConfigDelta + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace IndexConfigDelta { + + /** ChangeType enum. */ + type ChangeType = + "CHANGE_TYPE_UNSPECIFIED"| "ADD"| "REMOVE"; + } + + /** Properties of a TtlConfigDelta. */ + interface ITtlConfigDelta { + + /** TtlConfigDelta changeType */ + changeType?: (google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.ChangeType|null); + } + + /** Represents a TtlConfigDelta. */ + class TtlConfigDelta implements ITtlConfigDelta { + + /** + * Constructs a new TtlConfigDelta. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta); + + /** TtlConfigDelta changeType. */ + public changeType: google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.ChangeType; + + /** + * Creates a TtlConfigDelta message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TtlConfigDelta + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta; + + /** + * Creates a plain object from a TtlConfigDelta message. Also converts values to other types if specified. + * @param message TtlConfigDelta + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TtlConfigDelta to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TtlConfigDelta + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TtlConfigDelta { + + /** ChangeType enum. */ + type ChangeType = + "CHANGE_TYPE_UNSPECIFIED"| "ADD"| "REMOVE"; + } + } + + /** Properties of an ExportDocumentsMetadata. */ + interface IExportDocumentsMetadata { + + /** ExportDocumentsMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** ExportDocumentsMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata collectionIds */ + collectionIds?: (string[]|null); + + /** ExportDocumentsMetadata outputUriPrefix */ + outputUriPrefix?: (string|null); + + /** ExportDocumentsMetadata namespaceIds */ + namespaceIds?: (string[]|null); + + /** ExportDocumentsMetadata snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an ExportDocumentsMetadata. */ + class ExportDocumentsMetadata implements IExportDocumentsMetadata { + + /** + * Constructs a new ExportDocumentsMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IExportDocumentsMetadata); + + /** ExportDocumentsMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** ExportDocumentsMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata collectionIds. */ + public collectionIds: string[]; + + /** ExportDocumentsMetadata outputUriPrefix. */ + public outputUriPrefix: string; + + /** ExportDocumentsMetadata namespaceIds. */ + public namespaceIds: string[]; + + /** ExportDocumentsMetadata snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates an ExportDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExportDocumentsMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsMetadata; + + /** + * Creates a plain object from an ExportDocumentsMetadata message. Also converts values to other types if specified. + * @param message ExportDocumentsMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ExportDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExportDocumentsMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExportDocumentsMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ImportDocumentsMetadata. */ + interface IImportDocumentsMetadata { + + /** ImportDocumentsMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** ImportDocumentsMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata collectionIds */ + collectionIds?: (string[]|null); + + /** ImportDocumentsMetadata inputUriPrefix */ + inputUriPrefix?: (string|null); + + /** ImportDocumentsMetadata namespaceIds */ + namespaceIds?: (string[]|null); + } + + /** Represents an ImportDocumentsMetadata. */ + class ImportDocumentsMetadata implements IImportDocumentsMetadata { + + /** + * Constructs a new ImportDocumentsMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IImportDocumentsMetadata); + + /** ImportDocumentsMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** ImportDocumentsMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata collectionIds. */ + public collectionIds: string[]; + + /** ImportDocumentsMetadata inputUriPrefix. */ + public inputUriPrefix: string; + + /** ImportDocumentsMetadata namespaceIds. */ + public namespaceIds: string[]; + + /** + * Creates an ImportDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ImportDocumentsMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ImportDocumentsMetadata; + + /** + * Creates a plain object from an ImportDocumentsMetadata message. Also converts values to other types if specified. + * @param message ImportDocumentsMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ImportDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ImportDocumentsMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ImportDocumentsMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BulkDeleteDocumentsMetadata. */ + interface IBulkDeleteDocumentsMetadata { + + /** BulkDeleteDocumentsMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** BulkDeleteDocumentsMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata collectionIds */ + collectionIds?: (string[]|null); + + /** BulkDeleteDocumentsMetadata namespaceIds */ + namespaceIds?: (string[]|null); + + /** BulkDeleteDocumentsMetadata snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BulkDeleteDocumentsMetadata. */ + class BulkDeleteDocumentsMetadata implements IBulkDeleteDocumentsMetadata { + + /** + * Constructs a new BulkDeleteDocumentsMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsMetadata); + + /** BulkDeleteDocumentsMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** BulkDeleteDocumentsMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata collectionIds. */ + public collectionIds: string[]; + + /** BulkDeleteDocumentsMetadata namespaceIds. */ + public namespaceIds: string[]; + + /** BulkDeleteDocumentsMetadata snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a BulkDeleteDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsMetadata; + + /** + * Creates a plain object from a BulkDeleteDocumentsMetadata message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BulkDeleteDocumentsMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BulkDeleteDocumentsMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExportDocumentsResponse. */ + interface IExportDocumentsResponse { + + /** ExportDocumentsResponse outputUriPrefix */ + outputUriPrefix?: (string|null); + } + + /** Represents an ExportDocumentsResponse. */ + class ExportDocumentsResponse implements IExportDocumentsResponse { + + /** + * Constructs a new ExportDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IExportDocumentsResponse); + + /** ExportDocumentsResponse outputUriPrefix. */ + public outputUriPrefix: string; + + /** + * Creates an ExportDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExportDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsResponse; + + /** + * Creates a plain object from an ExportDocumentsResponse message. Also converts values to other types if specified. + * @param message ExportDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ExportDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExportDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExportDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RestoreDatabaseMetadata. */ + interface IRestoreDatabaseMetadata { + + /** RestoreDatabaseMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** RestoreDatabaseMetadata database */ + database?: (string|null); + + /** RestoreDatabaseMetadata backup */ + backup?: (string|null); + + /** RestoreDatabaseMetadata progressPercentage */ + progressPercentage?: (google.firestore.admin.v1.IProgress|null); + } + + /** Represents a RestoreDatabaseMetadata. */ + class RestoreDatabaseMetadata implements IRestoreDatabaseMetadata { + + /** + * Constructs a new RestoreDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IRestoreDatabaseMetadata); + + /** RestoreDatabaseMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** RestoreDatabaseMetadata database. */ + public database: string; + + /** RestoreDatabaseMetadata backup. */ + public backup: string; + + /** RestoreDatabaseMetadata progressPercentage. */ + public progressPercentage?: (google.firestore.admin.v1.IProgress|null); + + /** + * Creates a RestoreDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RestoreDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.RestoreDatabaseMetadata; + + /** + * Creates a plain object from a RestoreDatabaseMetadata message. Also converts values to other types if specified. + * @param message RestoreDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.RestoreDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RestoreDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RestoreDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CloneDatabaseMetadata. */ + interface ICloneDatabaseMetadata { + + /** CloneDatabaseMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** CloneDatabaseMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** CloneDatabaseMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** CloneDatabaseMetadata database */ + database?: (string|null); + + /** CloneDatabaseMetadata pitrSnapshot */ + pitrSnapshot?: (google.firestore.admin.v1.IPitrSnapshot|null); + + /** CloneDatabaseMetadata progressPercentage */ + progressPercentage?: (google.firestore.admin.v1.IProgress|null); + } + + /** Represents a CloneDatabaseMetadata. */ + class CloneDatabaseMetadata implements ICloneDatabaseMetadata { + + /** + * Constructs a new CloneDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICloneDatabaseMetadata); + + /** CloneDatabaseMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** CloneDatabaseMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** CloneDatabaseMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** CloneDatabaseMetadata database. */ + public database: string; + + /** CloneDatabaseMetadata pitrSnapshot. */ + public pitrSnapshot?: (google.firestore.admin.v1.IPitrSnapshot|null); + + /** CloneDatabaseMetadata progressPercentage. */ + public progressPercentage?: (google.firestore.admin.v1.IProgress|null); + + /** + * Creates a CloneDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CloneDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CloneDatabaseMetadata; + + /** + * Creates a plain object from a CloneDatabaseMetadata message. Also converts values to other types if specified. + * @param message CloneDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CloneDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CloneDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CloneDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Progress. */ + interface IProgress { + + /** Progress estimatedWork */ + estimatedWork?: (number|string|null); + + /** Progress completedWork */ + completedWork?: (number|string|null); + } + + /** Represents a Progress. */ + class Progress implements IProgress { + + /** + * Constructs a new Progress. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IProgress); + + /** Progress estimatedWork. */ + public estimatedWork: (number|string); + + /** Progress completedWork. */ + public completedWork: (number|string); + + /** + * Creates a Progress message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Progress + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Progress; + + /** + * Creates a plain object from a Progress message. Also converts values to other types if specified. + * @param message Progress + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Progress, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Progress to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Progress + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** OperationState enum. */ + type OperationState = + "OPERATION_STATE_UNSPECIFIED"| "INITIALIZING"| "PROCESSING"| "CANCELLING"| "FINALIZING"| "SUCCESSFUL"| "FAILED"| "CANCELLED"; + + /** Properties of a PitrSnapshot. */ + interface IPitrSnapshot { + + /** PitrSnapshot database */ + database?: (string|null); + + /** PitrSnapshot databaseUid */ + databaseUid?: (Uint8Array|null); + + /** PitrSnapshot snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a PitrSnapshot. */ + class PitrSnapshot implements IPitrSnapshot { + + /** + * Constructs a new PitrSnapshot. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IPitrSnapshot); + + /** PitrSnapshot database. */ + public database: string; + + /** PitrSnapshot databaseUid. */ + public databaseUid: Uint8Array; + + /** PitrSnapshot snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a PitrSnapshot message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PitrSnapshot + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.PitrSnapshot; + + /** + * Creates a plain object from a PitrSnapshot message. Also converts values to other types if specified. + * @param message PitrSnapshot + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.PitrSnapshot, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PitrSnapshot to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PitrSnapshot + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BackupSchedule. */ + interface IBackupSchedule { + + /** BackupSchedule name */ + name?: (string|null); + + /** BackupSchedule createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule retention */ + retention?: (google.protobuf.IDuration|null); + + /** BackupSchedule dailyRecurrence */ + dailyRecurrence?: (google.firestore.admin.v1.IDailyRecurrence|null); + + /** BackupSchedule weeklyRecurrence */ + weeklyRecurrence?: (google.firestore.admin.v1.IWeeklyRecurrence|null); + } + + /** Represents a BackupSchedule. */ + class BackupSchedule implements IBackupSchedule { + + /** + * Constructs a new BackupSchedule. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBackupSchedule); + + /** BackupSchedule name. */ + public name: string; + + /** BackupSchedule createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule retention. */ + public retention?: (google.protobuf.IDuration|null); + + /** BackupSchedule dailyRecurrence. */ + public dailyRecurrence?: (google.firestore.admin.v1.IDailyRecurrence|null); + + /** BackupSchedule weeklyRecurrence. */ + public weeklyRecurrence?: (google.firestore.admin.v1.IWeeklyRecurrence|null); + + /** BackupSchedule recurrence. */ + public recurrence?: ("dailyRecurrence"|"weeklyRecurrence"); + + /** + * Creates a BackupSchedule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BackupSchedule + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BackupSchedule; + + /** + * Creates a plain object from a BackupSchedule message. Also converts values to other types if specified. + * @param message BackupSchedule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BackupSchedule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BackupSchedule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BackupSchedule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DailyRecurrence. */ + interface IDailyRecurrence { + } + + /** Represents a DailyRecurrence. */ + class DailyRecurrence implements IDailyRecurrence { + + /** + * Constructs a new DailyRecurrence. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDailyRecurrence); + + /** + * Creates a DailyRecurrence message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DailyRecurrence + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DailyRecurrence; + + /** + * Creates a plain object from a DailyRecurrence message. Also converts values to other types if specified. + * @param message DailyRecurrence + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DailyRecurrence, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DailyRecurrence to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DailyRecurrence + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WeeklyRecurrence. */ + interface IWeeklyRecurrence { + + /** WeeklyRecurrence day */ + day?: (google.type.DayOfWeek|null); + } + + /** Represents a WeeklyRecurrence. */ + class WeeklyRecurrence implements IWeeklyRecurrence { + + /** + * Constructs a new WeeklyRecurrence. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IWeeklyRecurrence); + + /** WeeklyRecurrence day. */ + public day: google.type.DayOfWeek; + + /** + * Creates a WeeklyRecurrence message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WeeklyRecurrence + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.WeeklyRecurrence; + + /** + * Creates a plain object from a WeeklyRecurrence message. Also converts values to other types if specified. + * @param message WeeklyRecurrence + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.WeeklyRecurrence, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WeeklyRecurrence to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WeeklyRecurrence + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UserCreds. */ + interface IUserCreds { + + /** UserCreds name */ + name?: (string|null); + + /** UserCreds createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** UserCreds updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** UserCreds state */ + state?: (google.firestore.admin.v1.UserCreds.State|null); + + /** UserCreds securePassword */ + securePassword?: (string|null); + + /** UserCreds resourceIdentity */ + resourceIdentity?: (google.firestore.admin.v1.UserCreds.IResourceIdentity|null); + } + + /** Represents a UserCreds. */ + class UserCreds implements IUserCreds { + + /** + * Constructs a new UserCreds. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUserCreds); + + /** UserCreds name. */ + public name: string; + + /** UserCreds createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** UserCreds updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** UserCreds state. */ + public state: google.firestore.admin.v1.UserCreds.State; + + /** UserCreds securePassword. */ + public securePassword: string; + + /** UserCreds resourceIdentity. */ + public resourceIdentity?: (google.firestore.admin.v1.UserCreds.IResourceIdentity|null); + + /** UserCreds UserCredsIdentity. */ + public UserCredsIdentity?: "resourceIdentity"; + + /** + * Creates a UserCreds message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UserCreds + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UserCreds; + + /** + * Creates a plain object from a UserCreds message. Also converts values to other types if specified. + * @param message UserCreds + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UserCreds, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UserCreds to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UserCreds + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UserCreds { + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "ENABLED"| "DISABLED"; + + /** Properties of a ResourceIdentity. */ + interface IResourceIdentity { + + /** ResourceIdentity principal */ + principal?: (string|null); + } + + /** Represents a ResourceIdentity. */ + class ResourceIdentity implements IResourceIdentity { + + /** + * Constructs a new ResourceIdentity. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.UserCreds.IResourceIdentity); + + /** ResourceIdentity principal. */ + public principal: string; + + /** + * Creates a ResourceIdentity message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceIdentity + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UserCreds.ResourceIdentity; + + /** + * Creates a plain object from a ResourceIdentity message. Also converts values to other types if specified. + * @param message ResourceIdentity + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UserCreds.ResourceIdentity, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceIdentity to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceIdentity + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a LocationMetadata. */ + interface ILocationMetadata { + } + + /** Represents a LocationMetadata. */ + class LocationMetadata implements ILocationMetadata { + + /** + * Constructs a new LocationMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ILocationMetadata); + + /** + * Creates a LocationMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LocationMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.LocationMetadata; + + /** + * Creates a plain object from a LocationMetadata message. Also converts values to other types if specified. + * @param message LocationMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.LocationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LocationMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LocationMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + } + + /** Namespace api. */ + namespace api { + + /** FieldBehavior enum. */ + type FieldBehavior = + "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; + + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { + + /** ResourceDescriptor type */ + type?: (string|null); + + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); + + /** ResourceDescriptor nameField */ + nameField?: (string|null); + + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|null); + + /** ResourceDescriptor plural */ + plural?: (string|null); + + /** ResourceDescriptor singular */ + singular?: (string|null); + + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } + + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { + + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); + + /** ResourceDescriptor type. */ + public type: string; + + /** ResourceDescriptor pattern. */ + public pattern: string[]; + + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: google.api.ResourceDescriptor.History; + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ResourceDescriptor { + + /** History enum. */ + type History = + "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; + + /** Style enum. */ + type Style = + "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + } + + /** Properties of a ResourceReference. */ + interface IResourceReference { + + /** ResourceReference type */ + type?: (string|null); + + /** ResourceReference childType */ + childType?: (string|null); + } + + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { + + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); + + /** ResourceReference type. */ + public type: string; + + /** ResourceReference childType. */ + public childType: string; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { + + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); + + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + } + + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { + + /** + * Constructs a new CommonLanguageSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICommonLanguageSettings); + + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; + + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; + + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommonLanguageSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { + + /** ClientLibrarySettings version */ + version?: (string|null); + + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|null); + + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); + + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } + + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { + + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); + + /** ClientLibrarySettings version. */ + public version: string; + + /** ClientLibrarySettings launchStage. */ + public launchStage: google.api.LaunchStage; + + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; + + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Publishing. */ + interface IPublishing { + + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); + + /** Publishing newIssueUri */ + newIssueUri?: (string|null); + + /** Publishing documentationUri */ + documentationUri?: (string|null); + + /** Publishing apiShortName */ + apiShortName?: (string|null); + + /** Publishing githubLabel */ + githubLabel?: (string|null); + + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); + + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); + + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|null); + + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); + + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); + + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } + + /** Represents a Publishing. */ + class Publishing implements IPublishing { + + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); + + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; + + /** Publishing newIssueUri. */ + public newIssueUri: string; + + /** Publishing documentationUri. */ + public documentationUri: string; + + /** Publishing apiShortName. */ + public apiShortName: string; + + /** Publishing githubLabel. */ + public githubLabel: string; + + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; + + /** Publishing docTagPrefix. */ + public docTagPrefix: string; + + /** Publishing organization. */ + public organization: google.api.ClientLibraryOrganization; + + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; + + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; + + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a JavaSettings. */ + interface IJavaSettings { + + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); + + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); + + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { + + /** + * Constructs a new JavaSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IJavaSettings); + + /** JavaSettings libraryPackage. */ + public libraryPackage: string; + + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; + + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns JavaSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this JavaSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CppSettings. */ + interface ICppSettings { + + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { + + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); + + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PhpSettings. */ + interface IPhpSettings { + + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { + + /** + * Constructs a new PhpSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPhpSettings); + + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PythonSettings. */ + interface IPythonSettings { + + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + } + + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { + + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); + + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PythonSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PythonSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PythonSettings { + + /** Properties of an ExperimentalFeatures. */ + interface IExperimentalFeatures { + + /** ExperimentalFeatures restAsyncIoEnabled */ + restAsyncIoEnabled?: (boolean|null); + + /** ExperimentalFeatures protobufPythonicTypesEnabled */ + protobufPythonicTypesEnabled?: (boolean|null); + + /** ExperimentalFeatures unversionedPackageDisabled */ + unversionedPackageDisabled?: (boolean|null); + } + + /** Represents an ExperimentalFeatures. */ + class ExperimentalFeatures implements IExperimentalFeatures { + + /** + * Constructs a new ExperimentalFeatures. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.PythonSettings.IExperimentalFeatures); + + /** ExperimentalFeatures restAsyncIoEnabled. */ + public restAsyncIoEnabled: boolean; + + /** ExperimentalFeatures protobufPythonicTypesEnabled. */ + public protobufPythonicTypesEnabled: boolean; + + /** ExperimentalFeatures unversionedPackageDisabled. */ + public unversionedPackageDisabled: boolean; + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExperimentalFeatures + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @param message ExperimentalFeatures + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings.ExperimentalFeatures, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExperimentalFeatures + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a NodeSettings. */ + interface INodeSettings { + + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { + + /** + * Constructs a new NodeSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.INodeSettings); + + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NodeSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NodeSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { + + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); + + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); + + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); + + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); + } + + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { + + /** + * Constructs a new DotnetSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IDotnetSettings); + + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; + + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; + + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; + + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DotnetSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DotnetSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RubySettings. */ + interface IRubySettings { + + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { + + /** + * Constructs a new RubySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRubySettings); + + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GoSettings. */ + interface IGoSettings { + + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + } + + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { + + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); + + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodSettings. */ + interface IMethodSettings { + + /** MethodSettings selector */ + selector?: (string|null); + + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); + } + + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { + + /** + * Constructs a new MethodSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IMethodSettings); + + /** MethodSettings selector. */ + public selector: string; + + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodSettings { + + /** Properties of a LongRunning. */ + interface ILongRunning { + + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); + + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); + } + + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { + + /** + * Constructs a new LongRunning. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.MethodSettings.ILongRunning); + + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; + + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LongRunning + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LongRunning to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LongRunning + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** ClientLibraryOrganization enum. */ + type ClientLibraryOrganization = + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; + + /** ClientLibraryDestination enum. */ + type ClientLibraryDestination = + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; + + /** Properties of a SelectiveGapicGeneration. */ + interface ISelectiveGapicGeneration { + + /** SelectiveGapicGeneration methods */ + methods?: (string[]|null); + + /** SelectiveGapicGeneration generateOmittedAsInternal */ + generateOmittedAsInternal?: (boolean|null); + } + + /** Represents a SelectiveGapicGeneration. */ + class SelectiveGapicGeneration implements ISelectiveGapicGeneration { + + /** + * Constructs a new SelectiveGapicGeneration. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ISelectiveGapicGeneration); + + /** SelectiveGapicGeneration methods. */ + public methods: string[]; + + /** SelectiveGapicGeneration generateOmittedAsInternal. */ + public generateOmittedAsInternal: boolean; + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SelectiveGapicGeneration + */ + public static fromObject(object: { [k: string]: any }): google.api.SelectiveGapicGeneration; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @param message SelectiveGapicGeneration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.SelectiveGapicGeneration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; + + /** Properties of a RoutingRule. */ + interface IRoutingRule { + + /** RoutingRule routingParameters */ + routingParameters?: (google.api.IRoutingParameter[]|null); + } + + /** Represents a RoutingRule. */ + class RoutingRule implements IRoutingRule { + + /** + * Constructs a new RoutingRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRoutingRule); + + /** RoutingRule routingParameters. */ + public routingParameters: google.api.IRoutingParameter[]; + + /** + * Creates a RoutingRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingRule + */ + public static fromObject(object: { [k: string]: any }): google.api.RoutingRule; + + /** + * Creates a plain object from a RoutingRule message. Also converts values to other types if specified. + * @param message RoutingRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RoutingRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RoutingParameter. */ + interface IRoutingParameter { + + /** RoutingParameter field */ + field?: (string|null); + + /** RoutingParameter pathTemplate */ + pathTemplate?: (string|null); + } + + /** Represents a RoutingParameter. */ + class RoutingParameter implements IRoutingParameter { + + /** + * Constructs a new RoutingParameter. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRoutingParameter); + + /** RoutingParameter field. */ + public field: string; + + /** RoutingParameter pathTemplate. */ + public pathTemplate: string; + + /** + * Creates a RoutingParameter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingParameter + */ + public static fromObject(object: { [k: string]: any }): google.api.RoutingParameter; + + /** + * Creates a plain object from a RoutingParameter message. Also converts values to other types if specified. + * @param message RoutingParameter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RoutingParameter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingParameter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingParameter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); + + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Edition enum. */ + type Edition = + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; + + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { + + /** FileDescriptorProto name */ + name?: (string|null); + + /** FileDescriptorProto package */ + "package"?: (string|null); + + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); + + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); + + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); + + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); + + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); + + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax */ + syntax?: (string|null); + + /** FileDescriptorProto edition */ + edition?: (google.protobuf.Edition|null); + } + + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { + + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); + + /** FileDescriptorProto name. */ + public name: string; + + /** FileDescriptorProto package. */ + public package: string; + + /** FileDescriptorProto dependency. */ + public dependency: string[]; + + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; + + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; + + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; + + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; + + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax. */ + public syntax: string; + + /** FileDescriptorProto edition. */ + public edition: google.protobuf.Edition; + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { + + /** DescriptorProto name */ + name?: (string|null); + + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { + + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); + + /** DescriptorProto name. */ + public name: string; + + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; + + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + + /** DescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DescriptorProto { + + /** Properties of an ExtensionRange. */ + interface IExtensionRange { + + /** ExtensionRange start */ + start?: (number|null); + + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); + } + + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { + + /** + * Constructs a new ExtensionRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + + /** ExtensionRange start. */ + public start: number; + + /** ExtensionRange end. */ + public end: number; + + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReservedRange. */ + interface IReservedRange { + + /** ReservedRange start */ + start?: (number|null); + + /** ReservedRange end */ + end?: (number|null); + } + + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { + + /** + * Constructs a new ReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + + /** ReservedRange start. */ + public start: number; + + /** ReservedRange end. */ + public end: number; + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ExtensionRangeOptions declaration */ + declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); + + /** ExtensionRangeOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification */ + verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** ExtensionRangeOptions declaration. */ + public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; + + /** ExtensionRangeOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification. */ + public verification: google.protobuf.ExtensionRangeOptions.VerificationState; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExtensionRangeOptions { + + /** Properties of a Declaration. */ + interface IDeclaration { + + /** Declaration number */ + number?: (number|null); + + /** Declaration fullName */ + fullName?: (string|null); + + /** Declaration type */ + type?: (string|null); + + /** Declaration reserved */ + reserved?: (boolean|null); + + /** Declaration repeated */ + repeated?: (boolean|null); + } + + /** Represents a Declaration. */ + class Declaration implements IDeclaration { + + /** + * Constructs a new Declaration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); + + /** Declaration number. */ + public number: number; + + /** Declaration fullName. */ + public fullName: string; + + /** Declaration type. */ + public type: string; + + /** Declaration reserved. */ + public reserved: boolean; + + /** Declaration repeated. */ + public repeated: boolean; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Declaration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @param message Declaration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Declaration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Declaration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** VerificationState enum. */ + type VerificationState = + "DECLARATION"| "UNVERIFIED"; + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; + + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldDescriptorProto { + + /** Type enum. */ + type Type = + "TYPE_DOUBLE"| "TYPE_FLOAT"| "TYPE_INT64"| "TYPE_UINT64"| "TYPE_INT32"| "TYPE_FIXED64"| "TYPE_FIXED32"| "TYPE_BOOL"| "TYPE_STRING"| "TYPE_GROUP"| "TYPE_MESSAGE"| "TYPE_BYTES"| "TYPE_UINT32"| "TYPE_ENUM"| "TYPE_SFIXED32"| "TYPE_SFIXED64"| "TYPE_SINT32"| "TYPE_SINT64"; + + /** Label enum. */ + type Label = + "LABEL_OPTIONAL"| "LABEL_REPEATED"| "LABEL_REQUIRED"; + } + + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { + + /** OneofDescriptorProto name */ + name?: (string|null); + + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } + + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { + + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); + + /** OneofDescriptorProto name. */ + public name: string; + + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { + + /** EnumDescriptorProto name */ + name?: (string|null); + + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { + + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); + + /** EnumDescriptorProto name. */ + public name: string; + + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; + + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { + + /** EnumValueDescriptorProto name */ + name?: (string|null); + + /** EnumValueDescriptorProto number */ + number?: (number|null); + + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } + + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + + /** EnumValueDescriptorProto name. */ + public name: string; + + /** EnumValueDescriptorProto number. */ + public number: number; + + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { + + /** ServiceDescriptorProto name */ + name?: (string|null); + + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); + + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } + + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { + + /** FileOptions javaPackage */ + javaPackage?: (string|null); + + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); + + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); + + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); + + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); + + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + + /** FileOptions goPackage */ + goPackage?: (string|null); + + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); + + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); + + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); + + /** FileOptions deprecated */ + deprecated?: (boolean|null); + + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); + + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); + + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); + + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); + } + + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { + + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); + + /** FileOptions javaPackage. */ + public javaPackage: string; + + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; + + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; + + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; + + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; + + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + + /** FileOptions goPackage. */ + public goPackage: string; + + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; + + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; + + /** FileOptions deprecated. */ + public deprecated: boolean; + + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; + + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; + + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + type OptimizeMode = + "SPEED"| "CODE_SIZE"| "LITE_RUNTIME"; + } + + /** Properties of a MessageOptions. */ + interface IMessageOptions { + + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); + + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); + + /** MessageOptions deprecated */ + deprecated?: (boolean|null); + + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); + + /** MessageOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** MessageOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MessageOptions .google.api.resource */ + ".google.api.resource"?: (google.api.IResourceDescriptor|null); + } + + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { + + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); + + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; + + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; + + /** MessageOptions deprecated. */ + public deprecated: boolean; + + /** MessageOptions mapEntry. */ + public mapEntry: boolean; + + /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** MessageOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MessageOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldOptions. */ + interface IFieldOptions { + + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); + + /** FieldOptions packed */ + packed?: (boolean|null); + + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); + + /** FieldOptions lazy */ + lazy?: (boolean|null); + + /** FieldOptions unverifiedLazy */ + unverifiedLazy?: (boolean|null); + + /** FieldOptions deprecated */ + deprecated?: (boolean|null); + + /** FieldOptions weak */ + weak?: (boolean|null); + + /** FieldOptions debugRedact */ + debugRedact?: (boolean|null); + + /** FieldOptions retention */ + retention?: (google.protobuf.FieldOptions.OptionRetention|null); + + /** FieldOptions targets */ + targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); + + /** FieldOptions editionDefaults */ + editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); + + /** FieldOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FieldOptions .google.api.fieldBehavior */ + ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); + + /** FieldOptions .google.api.resourceReference */ + ".google.api.resourceReference"?: (google.api.IResourceReference|null); + } + + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { + + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); + + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; + + /** FieldOptions packed. */ + public packed: boolean; + + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; + + /** FieldOptions lazy. */ + public lazy: boolean; + + /** FieldOptions unverifiedLazy. */ + public unverifiedLazy: boolean; + + /** FieldOptions deprecated. */ + public deprecated: boolean; + + /** FieldOptions weak. */ + public weak: boolean; + + /** FieldOptions debugRedact. */ + public debugRedact: boolean; + + /** FieldOptions retention. */ + public retention: google.protobuf.FieldOptions.OptionRetention; + + /** FieldOptions targets. */ + public targets: google.protobuf.FieldOptions.OptionTargetType[]; + + /** FieldOptions editionDefaults. */ + public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; + + /** FieldOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldOptions { + + /** CType enum. */ + type CType = + "STRING"| "CORD"| "STRING_PIECE"; + + /** JSType enum. */ + type JSType = + "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; + + /** OptionRetention enum. */ + type OptionRetention = + "RETENTION_UNKNOWN"| "RETENTION_RUNTIME"| "RETENTION_SOURCE"; + + /** OptionTargetType enum. */ + type OptionTargetType = + "TARGET_TYPE_UNKNOWN"| "TARGET_TYPE_FILE"| "TARGET_TYPE_EXTENSION_RANGE"| "TARGET_TYPE_MESSAGE"| "TARGET_TYPE_FIELD"| "TARGET_TYPE_ONEOF"| "TARGET_TYPE_ENUM"| "TARGET_TYPE_ENUM_ENTRY"| "TARGET_TYPE_SERVICE"| "TARGET_TYPE_METHOD"; + + /** Properties of an EditionDefault. */ + interface IEditionDefault { + + /** EditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** EditionDefault value */ + value?: (string|null); + } + + /** Represents an EditionDefault. */ + class EditionDefault implements IEditionDefault { + + /** + * Constructs a new EditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); + + /** EditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** EditionDefault value. */ + public value: string; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @param message EditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an OneofOptions. */ + interface IOneofOptions { + + /** OneofOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { + + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); + + /** OneofOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumOptions. */ + interface IEnumOptions { + + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); + + /** EnumOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** EnumOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { + + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** EnumOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact */ + debugRedact?: (boolean|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { + + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); + + /** EnumValueOptions deprecated. */ + public deprecated: boolean; + + /** EnumValueOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact. */ + public debugRedact: boolean; + + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceOptions. */ + interface IServiceOptions { + + /** ServiceOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); + + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); + + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); + + /** ServiceOptions .google.api.apiVersion */ + ".google.api.apiVersion"?: (string|null); + } + + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { + + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); + + /** ServiceOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated. */ + public deprecated: boolean; + + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodOptions. */ + interface IMethodOptions { + + /** MethodOptions deprecated */ + deprecated?: (boolean|null); + + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); + + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); + + /** MethodOptions .google.api.routing */ + ".google.api.routing"?: (google.api.IRoutingRule|null); + + /** MethodOptions .google.longrunning.operationInfo */ + ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); + } + + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { + + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); + + /** MethodOptions deprecated. */ + public deprecated: boolean; + + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + type IdempotencyLevel = + "IDEMPOTENCY_UNKNOWN"| "NO_SIDE_EFFECTS"| "IDEMPOTENT"; + } + + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { + + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); + + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|string|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|string|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|string); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|string); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UninterpretedOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamePart + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a FeatureSet. */ + interface IFeatureSet { + + /** FeatureSet fieldPresence */ + fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|null); + + /** FeatureSet enumType */ + enumType?: (google.protobuf.FeatureSet.EnumType|null); + + /** FeatureSet repeatedFieldEncoding */ + repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|null); + + /** FeatureSet utf8Validation */ + utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|null); + + /** FeatureSet messageEncoding */ + messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|null); + + /** FeatureSet jsonFormat */ + jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|null); + } + + /** Represents a FeatureSet. */ + class FeatureSet implements IFeatureSet { + + /** + * Constructs a new FeatureSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSet); + + /** FeatureSet fieldPresence. */ + public fieldPresence: google.protobuf.FeatureSet.FieldPresence; + + /** FeatureSet enumType. */ + public enumType: google.protobuf.FeatureSet.EnumType; + + /** FeatureSet repeatedFieldEncoding. */ + public repeatedFieldEncoding: google.protobuf.FeatureSet.RepeatedFieldEncoding; + + /** FeatureSet utf8Validation. */ + public utf8Validation: google.protobuf.FeatureSet.Utf8Validation; + + /** FeatureSet messageEncoding. */ + public messageEncoding: google.protobuf.FeatureSet.MessageEncoding; + + /** FeatureSet jsonFormat. */ + public jsonFormat: google.protobuf.FeatureSet.JsonFormat; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @param message FeatureSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSet { + + /** FieldPresence enum. */ + type FieldPresence = + "FIELD_PRESENCE_UNKNOWN"| "EXPLICIT"| "IMPLICIT"| "LEGACY_REQUIRED"; + + /** EnumType enum. */ + type EnumType = + "ENUM_TYPE_UNKNOWN"| "OPEN"| "CLOSED"; + + /** RepeatedFieldEncoding enum. */ + type RepeatedFieldEncoding = + "REPEATED_FIELD_ENCODING_UNKNOWN"| "PACKED"| "EXPANDED"; + + /** Utf8Validation enum. */ + type Utf8Validation = + "UTF8_VALIDATION_UNKNOWN"| "VERIFY"| "NONE"; + + /** MessageEncoding enum. */ + type MessageEncoding = + "MESSAGE_ENCODING_UNKNOWN"| "LENGTH_PREFIXED"| "DELIMITED"; + + /** JsonFormat enum. */ + type JsonFormat = + "JSON_FORMAT_UNKNOWN"| "ALLOW"| "LEGACY_BEST_EFFORT"; + } + + /** Properties of a FeatureSetDefaults. */ + interface IFeatureSetDefaults { + + /** FeatureSetDefaults defaults */ + defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); + + /** FeatureSetDefaults minimumEdition */ + minimumEdition?: (google.protobuf.Edition|null); + + /** FeatureSetDefaults maximumEdition */ + maximumEdition?: (google.protobuf.Edition|null); + } + + /** Represents a FeatureSetDefaults. */ + class FeatureSetDefaults implements IFeatureSetDefaults { + + /** + * Constructs a new FeatureSetDefaults. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSetDefaults); + + /** FeatureSetDefaults defaults. */ + public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; + + /** FeatureSetDefaults minimumEdition. */ + public minimumEdition: google.protobuf.Edition; + + /** FeatureSetDefaults maximumEdition. */ + public maximumEdition: google.protobuf.Edition; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetDefaults + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @param message FeatureSetDefaults + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetDefaults + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSetDefaults { + + /** Properties of a FeatureSetEditionDefault. */ + interface IFeatureSetEditionDefault { + + /** FeatureSetEditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); + } + + /** Represents a FeatureSetEditionDefault. */ + class FeatureSetEditionDefault implements IFeatureSetEditionDefault { + + /** + * Constructs a new FeatureSetEditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); + + /** FeatureSetEditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetEditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @param message FeatureSetEditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { + + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } + + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { + + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); + + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SourceCodeInfo { + + /** Properties of a Location. */ + interface ILocation { + + /** Location path */ + path?: (number[]|null); + + /** Location span */ + span?: (number[]|null); + + /** Location leadingComments */ + leadingComments?: (string|null); + + /** Location trailingComments */ + trailingComments?: (string|null); + + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + + /** Location path. */ + public path: number[]; + + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Location + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { + + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } + + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { + + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); + + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + + /** Annotation semantic */ + semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); + } + + /** Represents an Annotation. */ + class Annotation implements IAnnotation { + + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); + + /** Annotation path. */ + public path: number[]; + + /** Annotation sourceFile. */ + public sourceFile: string; + + /** Annotation begin. */ + public begin: number; + + /** Annotation end. */ + public end: number; + + /** Annotation semantic. */ + public semantic: google.protobuf.GeneratedCodeInfo.Annotation.Semantic; + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Annotation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Annotation { + + /** Semantic enum. */ + type Semantic = + "NONE"| "SET"| "ALIAS"; + } + } + + /** Properties of a Timestamp. */ + interface ITimestamp { + + /** Timestamp seconds */ + seconds?: (number|string|null); + + /** Timestamp nanos */ + nanos?: (number|null); + } + + /** Represents a Timestamp. */ + class Timestamp implements ITimestamp { + + /** + * Constructs a new Timestamp. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ITimestamp); + + /** Timestamp seconds. */ + public seconds: (number|string); + + /** Timestamp nanos. */ + public nanos: number; + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Timestamp + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @param message Timestamp + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Timestamp to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Timestamp + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Duration. */ + interface IDuration { + + /** Duration seconds */ + seconds?: (number|string|null); + + /** Duration nanos */ + nanos?: (number|null); + } + + /** Represents a Duration. */ + class Duration implements IDuration { + + /** + * Constructs a new Duration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDuration); + + /** Duration seconds. */ + public seconds: (number|string); + + /** Duration nanos. */ + public nanos: number; + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Duration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Duration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Duration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Any. */ + interface IAny { + + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|null); + } + + /** Represents an Any. */ + class Any implements IAny { + + /** + * Constructs a new Any. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IAny); + + /** Any type_url. */ + public type_url: string; + + /** Any value. */ + public value: Uint8Array; + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Any + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Any to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Any + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Empty. */ + interface IEmpty { + } + + /** Represents an Empty. */ + class Empty implements IEmpty { + + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Empty + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldMask. */ + interface IFieldMask { + + /** FieldMask paths */ + paths?: (string[]|null); + } + + /** Represents a FieldMask. */ + class FieldMask implements IFieldMask { + + /** + * Constructs a new FieldMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldMask); + + /** FieldMask paths. */ + public paths: string[]; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldMask + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @param message FieldMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Struct. */ + interface IStruct { + + /** Struct fields */ + fields?: ({ [k: string]: google.protobuf.IValue }|null); + } + + /** Represents a Struct. */ + class Struct implements IStruct { + + /** + * Constructs a new Struct. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStruct); + + /** Struct fields. */ + public fields: { [k: string]: google.protobuf.IValue }; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Struct + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @param message Struct + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Struct to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Struct + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue */ + numberValue?: (number|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value boolValue */ + boolValue?: (boolean|null); + + /** Value structValue */ + structValue?: (google.protobuf.IStruct|null); + + /** Value listValue */ + listValue?: (google.protobuf.IListValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue. */ + public numberValue?: (number|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value boolValue. */ + public boolValue?: (boolean|null); + + /** Value structValue. */ + public structValue?: (google.protobuf.IStruct|null); + + /** Value listValue. */ + public listValue?: (google.protobuf.IListValue|null); + + /** Value kind. */ + public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** NullValue enum. */ + type NullValue = + "NULL_VALUE"; + + /** Properties of a ListValue. */ + interface IListValue { + + /** ListValue values */ + values?: (google.protobuf.IValue[]|null); + } + + /** Represents a ListValue. */ + class ListValue implements IListValue { + + /** + * Constructs a new ListValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IListValue); + + /** ListValue values. */ + public values: google.protobuf.IValue[]; + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @param message ListValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DoubleValue. */ + interface IDoubleValue { + + /** DoubleValue value */ + value?: (number|null); + } + + /** Represents a DoubleValue. */ + class DoubleValue implements IDoubleValue { + + /** + * Constructs a new DoubleValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDoubleValue); + + /** DoubleValue value. */ + public value: number; + + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DoubleValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; + + /** + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @param message DoubleValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DoubleValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DoubleValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FloatValue. */ + interface IFloatValue { + + /** FloatValue value */ + value?: (number|null); + } + + /** Represents a FloatValue. */ + class FloatValue implements IFloatValue { + + /** + * Constructs a new FloatValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFloatValue); + + /** FloatValue value. */ + public value: number; + + /** + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FloatValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; + + /** + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. + * @param message FloatValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FloatValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FloatValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int64Value. */ + interface IInt64Value { + + /** Int64Value value */ + value?: (number|string|null); + } + + /** Represents an Int64Value. */ + class Int64Value implements IInt64Value { + + /** + * Constructs a new Int64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt64Value); + + /** Int64Value value. */ + public value: (number|string); + + /** + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; + + /** + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. + * @param message Int64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt64Value. */ + interface IUInt64Value { + + /** UInt64Value value */ + value?: (number|string|null); + } + + /** Represents a UInt64Value. */ + class UInt64Value implements IUInt64Value { + + /** + * Constructs a new UInt64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt64Value); + + /** UInt64Value value. */ + public value: (number|string); + + /** + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; + + /** + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. + * @param message UInt64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int32Value. */ + interface IInt32Value { + + /** Int32Value value */ + value?: (number|null); + } + + /** Represents an Int32Value. */ + class Int32Value implements IInt32Value { + + /** + * Constructs a new Int32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt32Value); + + /** Int32Value value. */ + public value: number; + + /** + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; + + /** + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. + * @param message Int32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt32Value. */ + interface IUInt32Value { + + /** UInt32Value value */ + value?: (number|null); + } + + /** Represents a UInt32Value. */ + class UInt32Value implements IUInt32Value { + + /** + * Constructs a new UInt32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt32Value); + + /** UInt32Value value. */ + public value: number; + + /** + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; + + /** + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. + * @param message UInt32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BoolValue. */ + interface IBoolValue { + + /** BoolValue value */ + value?: (boolean|null); + } + + /** Represents a BoolValue. */ + class BoolValue implements IBoolValue { + + /** + * Constructs a new BoolValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBoolValue); + + /** BoolValue value. */ + public value: boolean; + + /** + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BoolValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; + + /** + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. + * @param message BoolValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BoolValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BoolValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StringValue. */ + interface IStringValue { + + /** StringValue value */ + value?: (string|null); + } + + /** Represents a StringValue. */ + class StringValue implements IStringValue { + + /** + * Constructs a new StringValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStringValue); + + /** StringValue value. */ + public value: string; + + /** + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StringValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; + + /** + * Creates a plain object from a StringValue message. Also converts values to other types if specified. + * @param message StringValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StringValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StringValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BytesValue. */ + interface IBytesValue { + + /** BytesValue value */ + value?: (Uint8Array|null); + } + + /** Represents a BytesValue. */ + class BytesValue implements IBytesValue { + + /** + * Constructs a new BytesValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBytesValue); + + /** BytesValue value. */ + public value: Uint8Array; + + /** + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BytesValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; + + /** + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. + * @param message BytesValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BytesValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BytesValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace type. */ + namespace type { + + /** DayOfWeek enum. */ + type DayOfWeek = + "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; + + /** Properties of a LatLng. */ + interface ILatLng { + + /** LatLng latitude */ + latitude?: (number|null); + + /** LatLng longitude */ + longitude?: (number|null); + } + + /** Represents a LatLng. */ + class LatLng implements ILatLng { + + /** + * Constructs a new LatLng. + * @param [properties] Properties to set + */ + constructor(properties?: google.type.ILatLng); + + /** LatLng latitude. */ + public latitude: number; + + /** LatLng longitude. */ + public longitude: number; + + /** + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LatLng + */ + public static fromObject(object: { [k: string]: any }): google.type.LatLng; + + /** + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @param message LatLng + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LatLng to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LatLng + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace longrunning. */ + namespace longrunning { + + /** Represents an Operations */ + class Operations extends $protobuf.rpc.Service { + + /** + * Constructs a new Operations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListOperationsResponse + */ + public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void; + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @returns Promise + */ + public listOperations(request: google.longrunning.IListOperationsRequest): Promise; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @returns Promise + */ + public getOperation(request: google.longrunning.IGetOperationRequest): Promise; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @returns Promise + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @returns Promise + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @returns Promise + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise; + } + + namespace Operations { + + /** + * Callback as used by {@link google.longrunning.Operations#listOperations}. + * @param error Error, if any + * @param [response] ListOperationsResponse + */ + type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#getOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#deleteOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#cancelOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#waitOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of an Operation. */ + interface IOperation { + + /** Operation name */ + name?: (string|null); + + /** Operation metadata */ + metadata?: (google.protobuf.IAny|null); + + /** Operation done */ + done?: (boolean|null); + + /** Operation error */ + error?: (google.rpc.IStatus|null); + + /** Operation response */ + response?: (google.protobuf.IAny|null); + } + + /** Represents an Operation. */ + class Operation implements IOperation { + + /** + * Constructs a new Operation. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperation); + + /** Operation name. */ + public name: string; + + /** Operation metadata. */ + public metadata?: (google.protobuf.IAny|null); + + /** Operation done. */ + public done: boolean; + + /** Operation error. */ + public error?: (google.rpc.IStatus|null); + + /** Operation response. */ + public response?: (google.protobuf.IAny|null); + + /** Operation result. */ + public result?: ("error"|"response"); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Operation + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.Operation; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @param message Operation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Operation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Operation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetOperationRequest. */ + interface IGetOperationRequest { + + /** GetOperationRequest name */ + name?: (string|null); + } + + /** Represents a GetOperationRequest. */ + class GetOperationRequest implements IGetOperationRequest { + + /** + * Constructs a new GetOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IGetOperationRequest); + + /** GetOperationRequest name. */ + public name: string; + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @param message GetOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsRequest. */ + interface IListOperationsRequest { + + /** ListOperationsRequest name */ + name?: (string|null); + + /** ListOperationsRequest filter */ + filter?: (string|null); + + /** ListOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListOperationsRequest pageToken */ + pageToken?: (string|null); + + /** ListOperationsRequest returnPartialSuccess */ + returnPartialSuccess?: (boolean|null); + } + + /** Represents a ListOperationsRequest. */ + class ListOperationsRequest implements IListOperationsRequest { + + /** + * Constructs a new ListOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsRequest); + + /** ListOperationsRequest name. */ + public name: string; + + /** ListOperationsRequest filter. */ + public filter: string; + + /** ListOperationsRequest pageSize. */ + public pageSize: number; + + /** ListOperationsRequest pageToken. */ + public pageToken: string; + + /** ListOperationsRequest returnPartialSuccess. */ + public returnPartialSuccess: boolean; + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @param message ListOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsResponse. */ + interface IListOperationsResponse { + + /** ListOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + + /** ListOperationsResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListOperationsResponse. */ + class ListOperationsResponse implements IListOperationsResponse { + + /** + * Constructs a new ListOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsResponse); + + /** ListOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** ListOperationsResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @param message ListOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CancelOperationRequest. */ + interface ICancelOperationRequest { + + /** CancelOperationRequest name */ + name?: (string|null); + } + + /** Represents a CancelOperationRequest. */ + class CancelOperationRequest implements ICancelOperationRequest { + + /** + * Constructs a new CancelOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.ICancelOperationRequest); + + /** CancelOperationRequest name. */ + public name: string; + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CancelOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @param message CancelOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CancelOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteOperationRequest. */ + interface IDeleteOperationRequest { + + /** DeleteOperationRequest name */ + name?: (string|null); + } + + /** Represents a DeleteOperationRequest. */ + class DeleteOperationRequest implements IDeleteOperationRequest { + + /** + * Constructs a new DeleteOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IDeleteOperationRequest); + + /** DeleteOperationRequest name. */ + public name: string; + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @param message DeleteOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WaitOperationRequest. */ + interface IWaitOperationRequest { + + /** WaitOperationRequest name */ + name?: (string|null); + + /** WaitOperationRequest timeout */ + timeout?: (google.protobuf.IDuration|null); + } + + /** Represents a WaitOperationRequest. */ + class WaitOperationRequest implements IWaitOperationRequest { + + /** + * Constructs a new WaitOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IWaitOperationRequest); + + /** WaitOperationRequest name. */ + public name: string; + + /** WaitOperationRequest timeout. */ + public timeout?: (google.protobuf.IDuration|null); + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @param message WaitOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WaitOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an OperationInfo. */ + interface IOperationInfo { + + /** OperationInfo responseType */ + responseType?: (string|null); + + /** OperationInfo metadataType */ + metadataType?: (string|null); + } + + /** Represents an OperationInfo. */ + class OperationInfo implements IOperationInfo { + + /** + * Constructs a new OperationInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperationInfo); + + /** OperationInfo responseType. */ + public responseType: string; + + /** OperationInfo metadataType. */ + public metadataType: string; + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationInfo + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @param message OperationInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace rpc. */ + namespace rpc { + + /** Properties of a Status. */ + interface IStatus { + + /** Status code */ + code?: (number|null); + + /** Status message */ + message?: (string|null); + + /** Status details */ + details?: (google.protobuf.IAny[]|null); + } + + /** Represents a Status. */ + class Status implements IStatus { + + /** + * Constructs a new Status. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IStatus); + + /** Status code. */ + public code: number; + + /** Status message. */ + public message: string; + + /** Status details. */ + public details: google.protobuf.IAny[]; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Status + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Status; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @param message Status + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Status to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Status + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } +} diff --git a/handwritten/firestore/types/protos/firestore_v1_proto_api.d.ts b/handwritten/firestore/types/protos/firestore_v1_proto_api.d.ts new file mode 100644 index 00000000000..e7ede770764 --- /dev/null +++ b/handwritten/firestore/types/protos/firestore_v1_proto_api.d.ts @@ -0,0 +1,11156 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as $protobuf from "protobufjs"; + +/** Namespace firestore. */ +export namespace firestore { + + /** Properties of a BundledQuery. */ + interface IBundledQuery { + + /** BundledQuery parent */ + parent?: (string|null); + + /** BundledQuery structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** BundledQuery limitType */ + limitType?: (firestore.BundledQuery.LimitType|null); + } + + /** Represents a BundledQuery. */ + class BundledQuery implements IBundledQuery { + + /** + * Constructs a new BundledQuery. + * @param [properties] Properties to set + */ + constructor(properties?: firestore.IBundledQuery); + + /** BundledQuery parent. */ + public parent: string; + + /** BundledQuery structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** BundledQuery limitType. */ + public limitType: firestore.BundledQuery.LimitType; + + /** BundledQuery queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a BundledQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BundledQuery + */ + public static fromObject(object: { [k: string]: any }): firestore.BundledQuery; + + /** + * Creates a plain object from a BundledQuery message. Also converts values to other types if specified. + * @param message BundledQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: firestore.BundledQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BundledQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BundledQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace BundledQuery { + + /** LimitType enum. */ + type LimitType = + "FIRST"| "LAST"; + } + + /** Properties of a NamedQuery. */ + interface INamedQuery { + + /** NamedQuery name */ + name?: (string|null); + + /** NamedQuery bundledQuery */ + bundledQuery?: (firestore.IBundledQuery|null); + + /** NamedQuery readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a NamedQuery. */ + class NamedQuery implements INamedQuery { + + /** + * Constructs a new NamedQuery. + * @param [properties] Properties to set + */ + constructor(properties?: firestore.INamedQuery); + + /** NamedQuery name. */ + public name: string; + + /** NamedQuery bundledQuery. */ + public bundledQuery?: (firestore.IBundledQuery|null); + + /** NamedQuery readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a NamedQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamedQuery + */ + public static fromObject(object: { [k: string]: any }): firestore.NamedQuery; + + /** + * Creates a plain object from a NamedQuery message. Also converts values to other types if specified. + * @param message NamedQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: firestore.NamedQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamedQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamedQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BundledDocumentMetadata. */ + interface IBundledDocumentMetadata { + + /** BundledDocumentMetadata name */ + name?: (string|null); + + /** BundledDocumentMetadata readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** BundledDocumentMetadata exists */ + exists?: (boolean|null); + + /** BundledDocumentMetadata queries */ + queries?: (string[]|null); + } + + /** Represents a BundledDocumentMetadata. */ + class BundledDocumentMetadata implements IBundledDocumentMetadata { + + /** + * Constructs a new BundledDocumentMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: firestore.IBundledDocumentMetadata); + + /** BundledDocumentMetadata name. */ + public name: string; + + /** BundledDocumentMetadata readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BundledDocumentMetadata exists. */ + public exists: boolean; + + /** BundledDocumentMetadata queries. */ + public queries: string[]; + + /** + * Creates a BundledDocumentMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BundledDocumentMetadata + */ + public static fromObject(object: { [k: string]: any }): firestore.BundledDocumentMetadata; + + /** + * Creates a plain object from a BundledDocumentMetadata message. Also converts values to other types if specified. + * @param message BundledDocumentMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: firestore.BundledDocumentMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BundledDocumentMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BundledDocumentMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BundleMetadata. */ + interface IBundleMetadata { + + /** BundleMetadata id */ + id?: (string|null); + + /** BundleMetadata createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** BundleMetadata version */ + version?: (number|null); + + /** BundleMetadata totalDocuments */ + totalDocuments?: (number|null); + + /** BundleMetadata totalBytes */ + totalBytes?: (number|string|null); + } + + /** Represents a BundleMetadata. */ + class BundleMetadata implements IBundleMetadata { + + /** + * Constructs a new BundleMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: firestore.IBundleMetadata); + + /** BundleMetadata id. */ + public id: string; + + /** BundleMetadata createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** BundleMetadata version. */ + public version: number; + + /** BundleMetadata totalDocuments. */ + public totalDocuments: number; + + /** BundleMetadata totalBytes. */ + public totalBytes: (number|string); + + /** + * Creates a BundleMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BundleMetadata + */ + public static fromObject(object: { [k: string]: any }): firestore.BundleMetadata; + + /** + * Creates a plain object from a BundleMetadata message. Also converts values to other types if specified. + * @param message BundleMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: firestore.BundleMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BundleMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BundleMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BundleElement. */ + interface IBundleElement { + + /** BundleElement metadata */ + metadata?: (firestore.IBundleMetadata|null); + + /** BundleElement namedQuery */ + namedQuery?: (firestore.INamedQuery|null); + + /** BundleElement documentMetadata */ + documentMetadata?: (firestore.IBundledDocumentMetadata|null); + + /** BundleElement document */ + document?: (google.firestore.v1.IDocument|null); + } + + /** Represents a BundleElement. */ + class BundleElement implements IBundleElement { + + /** + * Constructs a new BundleElement. + * @param [properties] Properties to set + */ + constructor(properties?: firestore.IBundleElement); + + /** BundleElement metadata. */ + public metadata?: (firestore.IBundleMetadata|null); + + /** BundleElement namedQuery. */ + public namedQuery?: (firestore.INamedQuery|null); + + /** BundleElement documentMetadata. */ + public documentMetadata?: (firestore.IBundledDocumentMetadata|null); + + /** BundleElement document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** BundleElement elementType. */ + public elementType?: ("metadata"|"namedQuery"|"documentMetadata"|"document"); + + /** + * Creates a BundleElement message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BundleElement + */ + public static fromObject(object: { [k: string]: any }): firestore.BundleElement; + + /** + * Creates a plain object from a BundleElement message. Also converts values to other types if specified. + * @param message BundleElement + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: firestore.BundleElement, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BundleElement to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BundleElement + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } +} + +/** Namespace google. */ +export namespace google { + + /** Namespace firestore. */ + namespace firestore { + + /** Namespace v1. */ + namespace v1 { + + /** Properties of an AggregationResult. */ + interface IAggregationResult { + + /** AggregationResult aggregateFields */ + aggregateFields?: ({ [k: string]: google.firestore.v1.IValue }|null); + } + + /** Represents an AggregationResult. */ + class AggregationResult implements IAggregationResult { + + /** + * Constructs a new AggregationResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IAggregationResult); + + /** AggregationResult aggregateFields. */ + public aggregateFields: { [k: string]: google.firestore.v1.IValue }; + + /** + * Creates an AggregationResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AggregationResult + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.AggregationResult; + + /** + * Creates a plain object from an AggregationResult message. Also converts values to other types if specified. + * @param message AggregationResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.AggregationResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AggregationResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AggregationResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Document. */ + interface IDocument { + + /** Document name */ + name?: (string|null); + + /** Document fields */ + fields?: ({ [k: string]: google.firestore.v1.IValue }|null); + + /** Document createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** Document updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a Document. */ + class Document implements IDocument { + + /** + * Constructs a new Document. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocument); + + /** Document name. */ + public name: string; + + /** Document fields. */ + public fields: { [k: string]: google.firestore.v1.IValue }; + + /** Document createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** Document updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a Document message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Document + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Document; + + /** + * Creates a plain object from a Document message. Also converts values to other types if specified. + * @param message Document + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Document, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Document to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Document + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value booleanValue */ + booleanValue?: (boolean|null); + + /** Value integerValue */ + integerValue?: (number|string|null); + + /** Value doubleValue */ + doubleValue?: (number|null); + + /** Value timestampValue */ + timestampValue?: (google.protobuf.ITimestamp|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value bytesValue */ + bytesValue?: (Uint8Array|null); + + /** Value referenceValue */ + referenceValue?: (string|null); + + /** Value geoPointValue */ + geoPointValue?: (google.type.ILatLng|null); + + /** Value arrayValue */ + arrayValue?: (google.firestore.v1.IArrayValue|null); + + /** Value mapValue */ + mapValue?: (google.firestore.v1.IMapValue|null); + + /** Value fieldReferenceValue */ + fieldReferenceValue?: (string|null); + + /** Value functionValue */ + functionValue?: (google.firestore.v1.IFunction|null); + + /** Value pipelineValue */ + pipelineValue?: (google.firestore.v1.IPipeline|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value booleanValue. */ + public booleanValue?: (boolean|null); + + /** Value integerValue. */ + public integerValue?: (number|string|null); + + /** Value doubleValue. */ + public doubleValue?: (number|null); + + /** Value timestampValue. */ + public timestampValue?: (google.protobuf.ITimestamp|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value bytesValue. */ + public bytesValue?: (Uint8Array|null); + + /** Value referenceValue. */ + public referenceValue?: (string|null); + + /** Value geoPointValue. */ + public geoPointValue?: (google.type.ILatLng|null); + + /** Value arrayValue. */ + public arrayValue?: (google.firestore.v1.IArrayValue|null); + + /** Value mapValue. */ + public mapValue?: (google.firestore.v1.IMapValue|null); + + /** Value fieldReferenceValue. */ + public fieldReferenceValue?: (string|null); + + /** Value functionValue. */ + public functionValue?: (google.firestore.v1.IFunction|null); + + /** Value pipelineValue. */ + public pipelineValue?: (google.firestore.v1.IPipeline|null); + + /** Value valueType. */ + public valueType?: ("nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"|"fieldReferenceValue"|"functionValue"|"pipelineValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ArrayValue. */ + interface IArrayValue { + + /** ArrayValue values */ + values?: (google.firestore.v1.IValue[]|null); + } + + /** Represents an ArrayValue. */ + class ArrayValue implements IArrayValue { + + /** + * Constructs a new ArrayValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IArrayValue); + + /** ArrayValue values. */ + public values: google.firestore.v1.IValue[]; + + /** + * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ArrayValue + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ArrayValue; + + /** + * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. + * @param message ArrayValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ArrayValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ArrayValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ArrayValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MapValue. */ + interface IMapValue { + + /** MapValue fields */ + fields?: ({ [k: string]: google.firestore.v1.IValue }|null); + } + + /** Represents a MapValue. */ + class MapValue implements IMapValue { + + /** + * Constructs a new MapValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IMapValue); + + /** MapValue fields. */ + public fields: { [k: string]: google.firestore.v1.IValue }; + + /** + * Creates a MapValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MapValue + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.MapValue; + + /** + * Creates a plain object from a MapValue message. Also converts values to other types if specified. + * @param message MapValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.MapValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MapValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MapValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Function. */ + interface IFunction { + + /** Function name */ + name?: (string|null); + + /** Function args */ + args?: (google.firestore.v1.IValue[]|null); + + /** Function options */ + options?: ({ [k: string]: google.firestore.v1.IValue }|null); + } + + /** Represents a Function. */ + class Function implements IFunction { + + /** + * Constructs a new Function. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IFunction); + + /** Function name. */ + public name: string; + + /** Function args. */ + public args: google.firestore.v1.IValue[]; + + /** Function options. */ + public options: { [k: string]: google.firestore.v1.IValue }; + + /** + * Creates a Function message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Function + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Function; + + /** + * Creates a plain object from a Function message. Also converts values to other types if specified. + * @param message Function + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Function, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Function to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Function + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Pipeline. */ + interface IPipeline { + + /** Pipeline stages */ + stages?: (google.firestore.v1.Pipeline.IStage[]|null); + } + + /** Represents a Pipeline. */ + class Pipeline implements IPipeline { + + /** + * Constructs a new Pipeline. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPipeline); + + /** Pipeline stages. */ + public stages: google.firestore.v1.Pipeline.IStage[]; + + /** + * Creates a Pipeline message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Pipeline + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Pipeline; + + /** + * Creates a plain object from a Pipeline message. Also converts values to other types if specified. + * @param message Pipeline + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Pipeline, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Pipeline to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Pipeline + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Pipeline { + + /** Properties of a Stage. */ + interface IStage { + + /** Stage name */ + name?: (string|null); + + /** Stage args */ + args?: (google.firestore.v1.IValue[]|null); + + /** Stage options */ + options?: ({ [k: string]: google.firestore.v1.IValue }|null); + } + + /** Represents a Stage. */ + class Stage implements IStage { + + /** + * Constructs a new Stage. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.Pipeline.IStage); + + /** Stage name. */ + public name: string; + + /** Stage args. */ + public args: google.firestore.v1.IValue[]; + + /** Stage options. */ + public options: { [k: string]: google.firestore.v1.IValue }; + + /** + * Creates a Stage message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Stage + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Pipeline.Stage; + + /** + * Creates a plain object from a Stage message. Also converts values to other types if specified. + * @param message Stage + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Pipeline.Stage, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Stage to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Stage + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a BitSequence. */ + interface IBitSequence { + + /** BitSequence bitmap */ + bitmap?: (Uint8Array|null); + + /** BitSequence padding */ + padding?: (number|null); + } + + /** Represents a BitSequence. */ + class BitSequence implements IBitSequence { + + /** + * Constructs a new BitSequence. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBitSequence); + + /** BitSequence bitmap. */ + public bitmap: Uint8Array; + + /** BitSequence padding. */ + public padding: number; + + /** + * Creates a BitSequence message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BitSequence + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BitSequence; + + /** + * Creates a plain object from a BitSequence message. Also converts values to other types if specified. + * @param message BitSequence + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BitSequence, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BitSequence to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BitSequence + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BloomFilter. */ + interface IBloomFilter { + + /** BloomFilter bits */ + bits?: (google.firestore.v1.IBitSequence|null); + + /** BloomFilter hashCount */ + hashCount?: (number|null); + } + + /** Represents a BloomFilter. */ + class BloomFilter implements IBloomFilter { + + /** + * Constructs a new BloomFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBloomFilter); + + /** BloomFilter bits. */ + public bits?: (google.firestore.v1.IBitSequence|null); + + /** BloomFilter hashCount. */ + public hashCount: number; + + /** + * Creates a BloomFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BloomFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BloomFilter; + + /** + * Creates a plain object from a BloomFilter message. Also converts values to other types if specified. + * @param message BloomFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BloomFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BloomFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BloomFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentMask. */ + interface IDocumentMask { + + /** DocumentMask fieldPaths */ + fieldPaths?: (string[]|null); + } + + /** Represents a DocumentMask. */ + class DocumentMask implements IDocumentMask { + + /** + * Constructs a new DocumentMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentMask); + + /** DocumentMask fieldPaths. */ + public fieldPaths: string[]; + + /** + * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentMask + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentMask; + + /** + * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. + * @param message DocumentMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Precondition. */ + interface IPrecondition { + + /** Precondition exists */ + exists?: (boolean|null); + + /** Precondition updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a Precondition. */ + class Precondition implements IPrecondition { + + /** + * Constructs a new Precondition. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPrecondition); + + /** Precondition exists. */ + public exists?: (boolean|null); + + /** Precondition updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** Precondition conditionType. */ + public conditionType?: ("exists"|"updateTime"); + + /** + * Creates a Precondition message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Precondition + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Precondition; + + /** + * Creates a plain object from a Precondition message. Also converts values to other types if specified. + * @param message Precondition + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Precondition, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Precondition to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Precondition + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TransactionOptions. */ + interface ITransactionOptions { + + /** TransactionOptions readOnly */ + readOnly?: (google.firestore.v1.TransactionOptions.IReadOnly|null); + + /** TransactionOptions readWrite */ + readWrite?: (google.firestore.v1.TransactionOptions.IReadWrite|null); + } + + /** Represents a TransactionOptions. */ + class TransactionOptions implements ITransactionOptions { + + /** + * Constructs a new TransactionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ITransactionOptions); + + /** TransactionOptions readOnly. */ + public readOnly?: (google.firestore.v1.TransactionOptions.IReadOnly|null); + + /** TransactionOptions readWrite. */ + public readWrite?: (google.firestore.v1.TransactionOptions.IReadWrite|null); + + /** TransactionOptions mode. */ + public mode?: ("readOnly"|"readWrite"); + + /** + * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TransactionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions; + + /** + * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. + * @param message TransactionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TransactionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TransactionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TransactionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TransactionOptions { + + /** Properties of a ReadWrite. */ + interface IReadWrite { + + /** ReadWrite retryTransaction */ + retryTransaction?: (Uint8Array|null); + } + + /** Represents a ReadWrite. */ + class ReadWrite implements IReadWrite { + + /** + * Constructs a new ReadWrite. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.TransactionOptions.IReadWrite); + + /** ReadWrite retryTransaction. */ + public retryTransaction: Uint8Array; + + /** + * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadWrite + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions.ReadWrite; + + /** + * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. + * @param message ReadWrite + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TransactionOptions.ReadWrite, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadWrite to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadWrite + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReadOnly. */ + interface IReadOnly { + + /** ReadOnly readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a ReadOnly. */ + class ReadOnly implements IReadOnly { + + /** + * Constructs a new ReadOnly. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.TransactionOptions.IReadOnly); + + /** ReadOnly readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ReadOnly consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadOnly + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions.ReadOnly; + + /** + * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. + * @param message ReadOnly + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TransactionOptions.ReadOnly, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadOnly to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadOnly + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExplainStats. */ + interface IExplainStats { + + /** ExplainStats data */ + data?: (google.protobuf.IAny|null); + } + + /** Represents an ExplainStats. */ + class ExplainStats implements IExplainStats { + + /** + * Constructs a new ExplainStats. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExplainStats); + + /** ExplainStats data. */ + public data?: (google.protobuf.IAny|null); + + /** + * Creates an ExplainStats message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExplainStats + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainStats; + + /** + * Creates a plain object from an ExplainStats message. Also converts values to other types if specified. + * @param message ExplainStats + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExplainStats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExplainStats to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExplainStats + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Represents a Firestore */ + class Firestore extends $protobuf.rpc.Service { + + /** + * Constructs a new Firestore service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls GetDocument. + * @param request GetDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public getDocument(request: google.firestore.v1.IGetDocumentRequest, callback: google.firestore.v1.Firestore.GetDocumentCallback): void; + + /** + * Calls GetDocument. + * @param request GetDocumentRequest message or plain object + * @returns Promise + */ + public getDocument(request: google.firestore.v1.IGetDocumentRequest): Promise; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDocumentsResponse + */ + public listDocuments(request: google.firestore.v1.IListDocumentsRequest, callback: google.firestore.v1.Firestore.ListDocumentsCallback): void; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @returns Promise + */ + public listDocuments(request: google.firestore.v1.IListDocumentsRequest): Promise; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public updateDocument(request: google.firestore.v1.IUpdateDocumentRequest, callback: google.firestore.v1.Firestore.UpdateDocumentCallback): void; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @returns Promise + */ + public updateDocument(request: google.firestore.v1.IUpdateDocumentRequest): Promise; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteDocument(request: google.firestore.v1.IDeleteDocumentRequest, callback: google.firestore.v1.Firestore.DeleteDocumentCallback): void; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @returns Promise + */ + public deleteDocument(request: google.firestore.v1.IDeleteDocumentRequest): Promise; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse + */ + public batchGetDocuments(request: google.firestore.v1.IBatchGetDocumentsRequest, callback: google.firestore.v1.Firestore.BatchGetDocumentsCallback): void; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @returns Promise + */ + public batchGetDocuments(request: google.firestore.v1.IBatchGetDocumentsRequest): Promise; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BeginTransactionResponse + */ + public beginTransaction(request: google.firestore.v1.IBeginTransactionRequest, callback: google.firestore.v1.Firestore.BeginTransactionCallback): void; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @returns Promise + */ + public beginTransaction(request: google.firestore.v1.IBeginTransactionRequest): Promise; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @param callback Node-style callback called with the error, if any, and CommitResponse + */ + public commit(request: google.firestore.v1.ICommitRequest, callback: google.firestore.v1.Firestore.CommitCallback): void; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @returns Promise + */ + public commit(request: google.firestore.v1.ICommitRequest): Promise; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public rollback(request: google.firestore.v1.IRollbackRequest, callback: google.firestore.v1.Firestore.RollbackCallback): void; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @returns Promise + */ + public rollback(request: google.firestore.v1.IRollbackRequest): Promise; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RunQueryResponse + */ + public runQuery(request: google.firestore.v1.IRunQueryRequest, callback: google.firestore.v1.Firestore.RunQueryCallback): void; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @returns Promise + */ + public runQuery(request: google.firestore.v1.IRunQueryRequest): Promise; + + /** + * Calls ExecutePipeline. + * @param request ExecutePipelineRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ExecutePipelineResponse + */ + public executePipeline(request: google.firestore.v1.IExecutePipelineRequest, callback: google.firestore.v1.Firestore.ExecutePipelineCallback): void; + + /** + * Calls ExecutePipeline. + * @param request ExecutePipelineRequest message or plain object + * @returns Promise + */ + public executePipeline(request: google.firestore.v1.IExecutePipelineRequest): Promise; + + /** + * Calls RunAggregationQuery. + * @param request RunAggregationQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RunAggregationQueryResponse + */ + public runAggregationQuery(request: google.firestore.v1.IRunAggregationQueryRequest, callback: google.firestore.v1.Firestore.RunAggregationQueryCallback): void; + + /** + * Calls RunAggregationQuery. + * @param request RunAggregationQueryRequest message or plain object + * @returns Promise + */ + public runAggregationQuery(request: google.firestore.v1.IRunAggregationQueryRequest): Promise; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and PartitionQueryResponse + */ + public partitionQuery(request: google.firestore.v1.IPartitionQueryRequest, callback: google.firestore.v1.Firestore.PartitionQueryCallback): void; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @returns Promise + */ + public partitionQuery(request: google.firestore.v1.IPartitionQueryRequest): Promise; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and WriteResponse + */ + public write(request: google.firestore.v1.IWriteRequest, callback: google.firestore.v1.Firestore.WriteCallback): void; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @returns Promise + */ + public write(request: google.firestore.v1.IWriteRequest): Promise; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListenResponse + */ + public listen(request: google.firestore.v1.IListenRequest, callback: google.firestore.v1.Firestore.ListenCallback): void; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @returns Promise + */ + public listen(request: google.firestore.v1.IListenRequest): Promise; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListCollectionIdsResponse + */ + public listCollectionIds(request: google.firestore.v1.IListCollectionIdsRequest, callback: google.firestore.v1.Firestore.ListCollectionIdsCallback): void; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @returns Promise + */ + public listCollectionIds(request: google.firestore.v1.IListCollectionIdsRequest): Promise; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchWriteResponse + */ + public batchWrite(request: google.firestore.v1.IBatchWriteRequest, callback: google.firestore.v1.Firestore.BatchWriteCallback): void; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @returns Promise + */ + public batchWrite(request: google.firestore.v1.IBatchWriteRequest): Promise; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public createDocument(request: google.firestore.v1.ICreateDocumentRequest, callback: google.firestore.v1.Firestore.CreateDocumentCallback): void; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @returns Promise + */ + public createDocument(request: google.firestore.v1.ICreateDocumentRequest): Promise; + } + + namespace Firestore { + + /** + * Callback as used by {@link google.firestore.v1.Firestore#getDocument}. + * @param error Error, if any + * @param [response] Document + */ + type GetDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listDocuments}. + * @param error Error, if any + * @param [response] ListDocumentsResponse + */ + type ListDocumentsCallback = (error: (Error|null), response?: google.firestore.v1.ListDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#updateDocument}. + * @param error Error, if any + * @param [response] Document + */ + type UpdateDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#deleteDocument}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteDocumentCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#batchGetDocuments}. + * @param error Error, if any + * @param [response] BatchGetDocumentsResponse + */ + type BatchGetDocumentsCallback = (error: (Error|null), response?: google.firestore.v1.BatchGetDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#beginTransaction}. + * @param error Error, if any + * @param [response] BeginTransactionResponse + */ + type BeginTransactionCallback = (error: (Error|null), response?: google.firestore.v1.BeginTransactionResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#commit}. + * @param error Error, if any + * @param [response] CommitResponse + */ + type CommitCallback = (error: (Error|null), response?: google.firestore.v1.CommitResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#rollback}. + * @param error Error, if any + * @param [response] Empty + */ + type RollbackCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#runQuery}. + * @param error Error, if any + * @param [response] RunQueryResponse + */ + type RunQueryCallback = (error: (Error|null), response?: google.firestore.v1.RunQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#executePipeline}. + * @param error Error, if any + * @param [response] ExecutePipelineResponse + */ + type ExecutePipelineCallback = (error: (Error|null), response?: google.firestore.v1.ExecutePipelineResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#runAggregationQuery}. + * @param error Error, if any + * @param [response] RunAggregationQueryResponse + */ + type RunAggregationQueryCallback = (error: (Error|null), response?: google.firestore.v1.RunAggregationQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#partitionQuery}. + * @param error Error, if any + * @param [response] PartitionQueryResponse + */ + type PartitionQueryCallback = (error: (Error|null), response?: google.firestore.v1.PartitionQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#write}. + * @param error Error, if any + * @param [response] WriteResponse + */ + type WriteCallback = (error: (Error|null), response?: google.firestore.v1.WriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listen}. + * @param error Error, if any + * @param [response] ListenResponse + */ + type ListenCallback = (error: (Error|null), response?: google.firestore.v1.ListenResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listCollectionIds}. + * @param error Error, if any + * @param [response] ListCollectionIdsResponse + */ + type ListCollectionIdsCallback = (error: (Error|null), response?: google.firestore.v1.ListCollectionIdsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#batchWrite}. + * @param error Error, if any + * @param [response] BatchWriteResponse + */ + type BatchWriteCallback = (error: (Error|null), response?: google.firestore.v1.BatchWriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#createDocument}. + * @param error Error, if any + * @param [response] Document + */ + type CreateDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + } + + /** Properties of a GetDocumentRequest. */ + interface IGetDocumentRequest { + + /** GetDocumentRequest name */ + name?: (string|null); + + /** GetDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** GetDocumentRequest transaction */ + transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a GetDocumentRequest. */ + class GetDocumentRequest implements IGetDocumentRequest { + + /** + * Constructs a new GetDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IGetDocumentRequest); + + /** GetDocumentRequest name. */ + public name: string; + + /** GetDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** GetDocumentRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** GetDocumentRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.GetDocumentRequest; + + /** + * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. + * @param message GetDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.GetDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsRequest. */ + interface IListDocumentsRequest { + + /** ListDocumentsRequest parent */ + parent?: (string|null); + + /** ListDocumentsRequest collectionId */ + collectionId?: (string|null); + + /** ListDocumentsRequest pageSize */ + pageSize?: (number|null); + + /** ListDocumentsRequest pageToken */ + pageToken?: (string|null); + + /** ListDocumentsRequest orderBy */ + orderBy?: (string|null); + + /** ListDocumentsRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** ListDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing */ + showMissing?: (boolean|null); + } + + /** Represents a ListDocumentsRequest. */ + class ListDocumentsRequest implements IListDocumentsRequest { + + /** + * Constructs a new ListDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListDocumentsRequest); + + /** ListDocumentsRequest parent. */ + public parent: string; + + /** ListDocumentsRequest collectionId. */ + public collectionId: string; + + /** ListDocumentsRequest pageSize. */ + public pageSize: number; + + /** ListDocumentsRequest pageToken. */ + public pageToken: string; + + /** ListDocumentsRequest orderBy. */ + public orderBy: string; + + /** ListDocumentsRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** ListDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing. */ + public showMissing: boolean; + + /** ListDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListDocumentsRequest; + + /** + * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. + * @param message ListDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsResponse. */ + interface IListDocumentsResponse { + + /** ListDocumentsResponse documents */ + documents?: (google.firestore.v1.IDocument[]|null); + + /** ListDocumentsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListDocumentsResponse. */ + class ListDocumentsResponse implements IListDocumentsResponse { + + /** + * Constructs a new ListDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListDocumentsResponse); + + /** ListDocumentsResponse documents. */ + public documents: google.firestore.v1.IDocument[]; + + /** ListDocumentsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListDocumentsResponse; + + /** + * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. + * @param message ListDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDocumentRequest. */ + interface ICreateDocumentRequest { + + /** CreateDocumentRequest parent */ + parent?: (string|null); + + /** CreateDocumentRequest collectionId */ + collectionId?: (string|null); + + /** CreateDocumentRequest documentId */ + documentId?: (string|null); + + /** CreateDocumentRequest document */ + document?: (google.firestore.v1.IDocument|null); + + /** CreateDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + } + + /** Represents a CreateDocumentRequest. */ + class CreateDocumentRequest implements ICreateDocumentRequest { + + /** + * Constructs a new CreateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICreateDocumentRequest); + + /** CreateDocumentRequest parent. */ + public parent: string; + + /** CreateDocumentRequest collectionId. */ + public collectionId: string; + + /** CreateDocumentRequest documentId. */ + public documentId: string; + + /** CreateDocumentRequest document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** CreateDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** + * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CreateDocumentRequest; + + /** + * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. + * @param message CreateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CreateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDocumentRequest. */ + interface IUpdateDocumentRequest { + + /** UpdateDocumentRequest document */ + document?: (google.firestore.v1.IDocument|null); + + /** UpdateDocumentRequest updateMask */ + updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); + } + + /** Represents an UpdateDocumentRequest. */ + class UpdateDocumentRequest implements IUpdateDocumentRequest { + + /** + * Constructs a new UpdateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IUpdateDocumentRequest); + + /** UpdateDocumentRequest document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** UpdateDocumentRequest updateMask. */ + public updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); + + /** + * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.UpdateDocumentRequest; + + /** + * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. + * @param message UpdateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.UpdateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDocumentRequest. */ + interface IDeleteDocumentRequest { + + /** DeleteDocumentRequest name */ + name?: (string|null); + + /** DeleteDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); + } + + /** Represents a DeleteDocumentRequest. */ + class DeleteDocumentRequest implements IDeleteDocumentRequest { + + /** + * Constructs a new DeleteDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDeleteDocumentRequest); + + /** DeleteDocumentRequest name. */ + public name: string; + + /** DeleteDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); + + /** + * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DeleteDocumentRequest; + + /** + * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. + * @param message DeleteDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DeleteDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsRequest. */ + interface IBatchGetDocumentsRequest { + + /** BatchGetDocumentsRequest database */ + database?: (string|null); + + /** BatchGetDocumentsRequest documents */ + documents?: (string[]|null); + + /** BatchGetDocumentsRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsRequest. */ + class BatchGetDocumentsRequest implements IBatchGetDocumentsRequest { + + /** + * Constructs a new BatchGetDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchGetDocumentsRequest); + + /** BatchGetDocumentsRequest database. */ + public database: string; + + /** BatchGetDocumentsRequest documents. */ + public documents: string[]; + + /** BatchGetDocumentsRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchGetDocumentsRequest; + + /** + * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. + * @param message BatchGetDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchGetDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsResponse. */ + interface IBatchGetDocumentsResponse { + + /** BatchGetDocumentsResponse found */ + found?: (google.firestore.v1.IDocument|null); + + /** BatchGetDocumentsResponse missing */ + missing?: (string|null); + + /** BatchGetDocumentsResponse transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsResponse. */ + class BatchGetDocumentsResponse implements IBatchGetDocumentsResponse { + + /** + * Constructs a new BatchGetDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchGetDocumentsResponse); + + /** BatchGetDocumentsResponse found. */ + public found?: (google.firestore.v1.IDocument|null); + + /** BatchGetDocumentsResponse missing. */ + public missing?: (string|null); + + /** BatchGetDocumentsResponse transaction. */ + public transaction: Uint8Array; + + /** BatchGetDocumentsResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsResponse result. */ + public result?: ("found"|"missing"); + + /** + * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchGetDocumentsResponse; + + /** + * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. + * @param message BatchGetDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchGetDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionRequest. */ + interface IBeginTransactionRequest { + + /** BeginTransactionRequest database */ + database?: (string|null); + + /** BeginTransactionRequest options */ + options?: (google.firestore.v1.ITransactionOptions|null); + } + + /** Represents a BeginTransactionRequest. */ + class BeginTransactionRequest implements IBeginTransactionRequest { + + /** + * Constructs a new BeginTransactionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBeginTransactionRequest); + + /** BeginTransactionRequest database. */ + public database: string; + + /** BeginTransactionRequest options. */ + public options?: (google.firestore.v1.ITransactionOptions|null); + + /** + * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BeginTransactionRequest; + + /** + * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. + * @param message BeginTransactionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BeginTransactionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionResponse. */ + interface IBeginTransactionResponse { + + /** BeginTransactionResponse transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a BeginTransactionResponse. */ + class BeginTransactionResponse implements IBeginTransactionResponse { + + /** + * Constructs a new BeginTransactionResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBeginTransactionResponse); + + /** BeginTransactionResponse transaction. */ + public transaction: Uint8Array; + + /** + * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BeginTransactionResponse; + + /** + * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. + * @param message BeginTransactionResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BeginTransactionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitRequest. */ + interface ICommitRequest { + + /** CommitRequest database */ + database?: (string|null); + + /** CommitRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); + + /** CommitRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a CommitRequest. */ + class CommitRequest implements ICommitRequest { + + /** + * Constructs a new CommitRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICommitRequest); + + /** CommitRequest database. */ + public database: string; + + /** CommitRequest writes. */ + public writes: google.firestore.v1.IWrite[]; + + /** CommitRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CommitRequest; + + /** + * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. + * @param message CommitRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CommitRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitResponse. */ + interface ICommitResponse { + + /** CommitResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); + + /** CommitResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a CommitResponse. */ + class CommitResponse implements ICommitResponse { + + /** + * Constructs a new CommitResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICommitResponse); + + /** CommitResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; + + /** CommitResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CommitResponse; + + /** + * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. + * @param message CommitResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CommitResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RollbackRequest. */ + interface IRollbackRequest { + + /** RollbackRequest database */ + database?: (string|null); + + /** RollbackRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a RollbackRequest. */ + class RollbackRequest implements IRollbackRequest { + + /** + * Constructs a new RollbackRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRollbackRequest); + + /** RollbackRequest database. */ + public database: string; + + /** RollbackRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RollbackRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RollbackRequest; + + /** + * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. + * @param message RollbackRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RollbackRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RollbackRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RollbackRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryRequest. */ + interface IRunQueryRequest { + + /** RunQueryRequest parent */ + parent?: (string|null); + + /** RunQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** RunQueryRequest transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryRequest explainOptions */ + explainOptions?: (google.firestore.v1.IExplainOptions|null); + } + + /** Represents a RunQueryRequest. */ + class RunQueryRequest implements IRunQueryRequest { + + /** + * Constructs a new RunQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunQueryRequest); + + /** RunQueryRequest parent. */ + public parent: string; + + /** RunQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** RunQueryRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryRequest explainOptions. */ + public explainOptions?: (google.firestore.v1.IExplainOptions|null); + + /** RunQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** RunQueryRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunQueryRequest; + + /** + * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. + * @param message RunQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryResponse. */ + interface IRunQueryResponse { + + /** RunQueryResponse transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryResponse document */ + document?: (google.firestore.v1.IDocument|null); + + /** RunQueryResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults */ + skippedResults?: (number|null); + + /** RunQueryResponse done */ + done?: (boolean|null); + + /** RunQueryResponse explainMetrics */ + explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + } + + /** Represents a RunQueryResponse. */ + class RunQueryResponse implements IRunQueryResponse { + + /** + * Constructs a new RunQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunQueryResponse); + + /** RunQueryResponse transaction. */ + public transaction: Uint8Array; + + /** RunQueryResponse document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** RunQueryResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults. */ + public skippedResults: number; + + /** RunQueryResponse done. */ + public done?: (boolean|null); + + /** RunQueryResponse explainMetrics. */ + public explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + + /** RunQueryResponse continuationSelector. */ + public continuationSelector?: "done"; + + /** + * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunQueryResponse; + + /** + * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. + * @param message RunQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExecutePipelineRequest. */ + interface IExecutePipelineRequest { + + /** ExecutePipelineRequest database */ + database?: (string|null); + + /** ExecutePipelineRequest structuredPipeline */ + structuredPipeline?: (google.firestore.v1.IStructuredPipeline|null); + + /** ExecutePipelineRequest transaction */ + transaction?: (Uint8Array|null); + + /** ExecutePipelineRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** ExecutePipelineRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an ExecutePipelineRequest. */ + class ExecutePipelineRequest implements IExecutePipelineRequest { + + /** + * Constructs a new ExecutePipelineRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExecutePipelineRequest); + + /** ExecutePipelineRequest database. */ + public database: string; + + /** ExecutePipelineRequest structuredPipeline. */ + public structuredPipeline?: (google.firestore.v1.IStructuredPipeline|null); + + /** ExecutePipelineRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** ExecutePipelineRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** ExecutePipelineRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ExecutePipelineRequest pipelineType. */ + public pipelineType?: "structuredPipeline"; + + /** ExecutePipelineRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates an ExecutePipelineRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecutePipelineRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutePipelineRequest; + + /** + * Creates a plain object from an ExecutePipelineRequest message. Also converts values to other types if specified. + * @param message ExecutePipelineRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExecutePipelineRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecutePipelineRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecutePipelineRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExecutePipelineResponse. */ + interface IExecutePipelineResponse { + + /** ExecutePipelineResponse transaction */ + transaction?: (Uint8Array|null); + + /** ExecutePipelineResponse results */ + results?: (google.firestore.v1.IDocument[]|null); + + /** ExecutePipelineResponse executionTime */ + executionTime?: (google.protobuf.ITimestamp|null); + + /** ExecutePipelineResponse explainStats */ + explainStats?: (google.firestore.v1.IExplainStats|null); + } + + /** Represents an ExecutePipelineResponse. */ + class ExecutePipelineResponse implements IExecutePipelineResponse { + + /** + * Constructs a new ExecutePipelineResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExecutePipelineResponse); + + /** ExecutePipelineResponse transaction. */ + public transaction: Uint8Array; + + /** ExecutePipelineResponse results. */ + public results: google.firestore.v1.IDocument[]; + + /** ExecutePipelineResponse executionTime. */ + public executionTime?: (google.protobuf.ITimestamp|null); + + /** ExecutePipelineResponse explainStats. */ + public explainStats?: (google.firestore.v1.IExplainStats|null); + + /** + * Creates an ExecutePipelineResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecutePipelineResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutePipelineResponse; + + /** + * Creates a plain object from an ExecutePipelineResponse message. Also converts values to other types if specified. + * @param message ExecutePipelineResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExecutePipelineResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecutePipelineResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecutePipelineResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunAggregationQueryRequest. */ + interface IRunAggregationQueryRequest { + + /** RunAggregationQueryRequest parent */ + parent?: (string|null); + + /** RunAggregationQueryRequest structuredAggregationQuery */ + structuredAggregationQuery?: (google.firestore.v1.IStructuredAggregationQuery|null); + + /** RunAggregationQueryRequest transaction */ + transaction?: (Uint8Array|null); + + /** RunAggregationQueryRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunAggregationQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryRequest explainOptions */ + explainOptions?: (google.firestore.v1.IExplainOptions|null); + } + + /** Represents a RunAggregationQueryRequest. */ + class RunAggregationQueryRequest implements IRunAggregationQueryRequest { + + /** + * Constructs a new RunAggregationQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunAggregationQueryRequest); + + /** RunAggregationQueryRequest parent. */ + public parent: string; + + /** RunAggregationQueryRequest structuredAggregationQuery. */ + public structuredAggregationQuery?: (google.firestore.v1.IStructuredAggregationQuery|null); + + /** RunAggregationQueryRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** RunAggregationQueryRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunAggregationQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryRequest explainOptions. */ + public explainOptions?: (google.firestore.v1.IExplainOptions|null); + + /** RunAggregationQueryRequest queryType. */ + public queryType?: "structuredAggregationQuery"; + + /** RunAggregationQueryRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a RunAggregationQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunAggregationQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunAggregationQueryRequest; + + /** + * Creates a plain object from a RunAggregationQueryRequest message. Also converts values to other types if specified. + * @param message RunAggregationQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunAggregationQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunAggregationQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunAggregationQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunAggregationQueryResponse. */ + interface IRunAggregationQueryResponse { + + /** RunAggregationQueryResponse result */ + result?: (google.firestore.v1.IAggregationResult|null); + + /** RunAggregationQueryResponse transaction */ + transaction?: (Uint8Array|null); + + /** RunAggregationQueryResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryResponse explainMetrics */ + explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + } + + /** Represents a RunAggregationQueryResponse. */ + class RunAggregationQueryResponse implements IRunAggregationQueryResponse { + + /** + * Constructs a new RunAggregationQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunAggregationQueryResponse); + + /** RunAggregationQueryResponse result. */ + public result?: (google.firestore.v1.IAggregationResult|null); + + /** RunAggregationQueryResponse transaction. */ + public transaction: Uint8Array; + + /** RunAggregationQueryResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryResponse explainMetrics. */ + public explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + + /** + * Creates a RunAggregationQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunAggregationQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunAggregationQueryResponse; + + /** + * Creates a plain object from a RunAggregationQueryResponse message. Also converts values to other types if specified. + * @param message RunAggregationQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunAggregationQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunAggregationQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunAggregationQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryRequest. */ + interface IPartitionQueryRequest { + + /** PartitionQueryRequest parent */ + parent?: (string|null); + + /** PartitionQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount */ + partitionCount?: (number|string|null); + + /** PartitionQueryRequest pageToken */ + pageToken?: (string|null); + + /** PartitionQueryRequest pageSize */ + pageSize?: (number|null); + + /** PartitionQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a PartitionQueryRequest. */ + class PartitionQueryRequest implements IPartitionQueryRequest { + + /** + * Constructs a new PartitionQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPartitionQueryRequest); + + /** PartitionQueryRequest parent. */ + public parent: string; + + /** PartitionQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount. */ + public partitionCount: (number|string); + + /** PartitionQueryRequest pageToken. */ + public pageToken: string; + + /** PartitionQueryRequest pageSize. */ + public pageSize: number; + + /** PartitionQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** PartitionQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** PartitionQueryRequest consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PartitionQueryRequest; + + /** + * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. + * @param message PartitionQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.PartitionQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryResponse. */ + interface IPartitionQueryResponse { + + /** PartitionQueryResponse partitions */ + partitions?: (google.firestore.v1.ICursor[]|null); + + /** PartitionQueryResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a PartitionQueryResponse. */ + class PartitionQueryResponse implements IPartitionQueryResponse { + + /** + * Constructs a new PartitionQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPartitionQueryResponse); + + /** PartitionQueryResponse partitions. */ + public partitions: google.firestore.v1.ICursor[]; + + /** PartitionQueryResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PartitionQueryResponse; + + /** + * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. + * @param message PartitionQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.PartitionQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteRequest. */ + interface IWriteRequest { + + /** WriteRequest database */ + database?: (string|null); + + /** WriteRequest streamId */ + streamId?: (string|null); + + /** WriteRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); + + /** WriteRequest streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a WriteRequest. */ + class WriteRequest implements IWriteRequest { + + /** + * Constructs a new WriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteRequest); + + /** WriteRequest database. */ + public database: string; + + /** WriteRequest streamId. */ + public streamId: string; + + /** WriteRequest writes. */ + public writes: google.firestore.v1.IWrite[]; + + /** WriteRequest streamToken. */ + public streamToken: Uint8Array; + + /** WriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteRequest; + + /** + * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. + * @param message WriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteResponse. */ + interface IWriteResponse { + + /** WriteResponse streamId */ + streamId?: (string|null); + + /** WriteResponse streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); + + /** WriteResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a WriteResponse. */ + class WriteResponse implements IWriteResponse { + + /** + * Constructs a new WriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteResponse); + + /** WriteResponse streamId. */ + public streamId: string; + + /** WriteResponse streamToken. */ + public streamToken: Uint8Array; + + /** WriteResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; + + /** WriteResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteResponse; + + /** + * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. + * @param message WriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenRequest. */ + interface IListenRequest { + + /** ListenRequest database */ + database?: (string|null); + + /** ListenRequest addTarget */ + addTarget?: (google.firestore.v1.ITarget|null); + + /** ListenRequest removeTarget */ + removeTarget?: (number|null); + + /** ListenRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a ListenRequest. */ + class ListenRequest implements IListenRequest { + + /** + * Constructs a new ListenRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListenRequest); + + /** ListenRequest database. */ + public database: string; + + /** ListenRequest addTarget. */ + public addTarget?: (google.firestore.v1.ITarget|null); + + /** ListenRequest removeTarget. */ + public removeTarget?: (number|null); + + /** ListenRequest labels. */ + public labels: { [k: string]: string }; + + /** ListenRequest targetChange. */ + public targetChange?: ("addTarget"|"removeTarget"); + + /** + * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListenRequest; + + /** + * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. + * @param message ListenRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListenRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenResponse. */ + interface IListenResponse { + + /** ListenResponse targetChange */ + targetChange?: (google.firestore.v1.ITargetChange|null); + + /** ListenResponse documentChange */ + documentChange?: (google.firestore.v1.IDocumentChange|null); + + /** ListenResponse documentDelete */ + documentDelete?: (google.firestore.v1.IDocumentDelete|null); + + /** ListenResponse documentRemove */ + documentRemove?: (google.firestore.v1.IDocumentRemove|null); + + /** ListenResponse filter */ + filter?: (google.firestore.v1.IExistenceFilter|null); + } + + /** Represents a ListenResponse. */ + class ListenResponse implements IListenResponse { + + /** + * Constructs a new ListenResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListenResponse); + + /** ListenResponse targetChange. */ + public targetChange?: (google.firestore.v1.ITargetChange|null); + + /** ListenResponse documentChange. */ + public documentChange?: (google.firestore.v1.IDocumentChange|null); + + /** ListenResponse documentDelete. */ + public documentDelete?: (google.firestore.v1.IDocumentDelete|null); + + /** ListenResponse documentRemove. */ + public documentRemove?: (google.firestore.v1.IDocumentRemove|null); + + /** ListenResponse filter. */ + public filter?: (google.firestore.v1.IExistenceFilter|null); + + /** ListenResponse responseType. */ + public responseType?: ("targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"); + + /** + * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListenResponse; + + /** + * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. + * @param message ListenResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListenResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Target. */ + interface ITarget { + + /** Target query */ + query?: (google.firestore.v1.Target.IQueryTarget|null); + + /** Target documents */ + documents?: (google.firestore.v1.Target.IDocumentsTarget|null); + + /** Target resumeToken */ + resumeToken?: (Uint8Array|null); + + /** Target readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId */ + targetId?: (number|null); + + /** Target once */ + once?: (boolean|null); + + /** Target expectedCount */ + expectedCount?: (google.protobuf.IInt32Value|null); + } + + /** Represents a Target. */ + class Target implements ITarget { + + /** + * Constructs a new Target. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ITarget); + + /** Target query. */ + public query?: (google.firestore.v1.Target.IQueryTarget|null); + + /** Target documents. */ + public documents?: (google.firestore.v1.Target.IDocumentsTarget|null); + + /** Target resumeToken. */ + public resumeToken?: (Uint8Array|null); + + /** Target readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId. */ + public targetId: number; + + /** Target once. */ + public once: boolean; + + /** Target expectedCount. */ + public expectedCount?: (google.protobuf.IInt32Value|null); + + /** Target targetType. */ + public targetType?: ("query"|"documents"); + + /** Target resumeType. */ + public resumeType?: ("resumeToken"|"readTime"); + + /** + * Creates a Target message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Target + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target; + + /** + * Creates a plain object from a Target message. Also converts values to other types if specified. + * @param message Target + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Target to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Target + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Target { + + /** Properties of a DocumentsTarget. */ + interface IDocumentsTarget { + + /** DocumentsTarget documents */ + documents?: (string[]|null); + } + + /** Represents a DocumentsTarget. */ + class DocumentsTarget implements IDocumentsTarget { + + /** + * Constructs a new DocumentsTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.Target.IDocumentsTarget); + + /** DocumentsTarget documents. */ + public documents: string[]; + + /** + * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentsTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target.DocumentsTarget; + + /** + * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. + * @param message DocumentsTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target.DocumentsTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentsTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentsTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a QueryTarget. */ + interface IQueryTarget { + + /** QueryTarget parent */ + parent?: (string|null); + + /** QueryTarget structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + } + + /** Represents a QueryTarget. */ + class QueryTarget implements IQueryTarget { + + /** + * Constructs a new QueryTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.Target.IQueryTarget); + + /** QueryTarget parent. */ + public parent: string; + + /** QueryTarget structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** QueryTarget queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QueryTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target.QueryTarget; + + /** + * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. + * @param message QueryTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target.QueryTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this QueryTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QueryTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a TargetChange. */ + interface ITargetChange { + + /** TargetChange targetChangeType */ + targetChangeType?: (google.firestore.v1.TargetChange.TargetChangeType|null); + + /** TargetChange targetIds */ + targetIds?: (number[]|null); + + /** TargetChange cause */ + cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken */ + resumeToken?: (Uint8Array|null); + + /** TargetChange readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a TargetChange. */ + class TargetChange implements ITargetChange { + + /** + * Constructs a new TargetChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ITargetChange); + + /** TargetChange targetChangeType. */ + public targetChangeType: google.firestore.v1.TargetChange.TargetChangeType; + + /** TargetChange targetIds. */ + public targetIds: number[]; + + /** TargetChange cause. */ + public cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken. */ + public resumeToken: Uint8Array; + + /** TargetChange readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TargetChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TargetChange; + + /** + * Creates a plain object from a TargetChange message. Also converts values to other types if specified. + * @param message TargetChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TargetChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TargetChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TargetChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TargetChange { + + /** TargetChangeType enum. */ + type TargetChangeType = + "NO_CHANGE"| "ADD"| "REMOVE"| "CURRENT"| "RESET"; + } + + /** Properties of a ListCollectionIdsRequest. */ + interface IListCollectionIdsRequest { + + /** ListCollectionIdsRequest parent */ + parent?: (string|null); + + /** ListCollectionIdsRequest pageSize */ + pageSize?: (number|null); + + /** ListCollectionIdsRequest pageToken */ + pageToken?: (string|null); + + /** ListCollectionIdsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a ListCollectionIdsRequest. */ + class ListCollectionIdsRequest implements IListCollectionIdsRequest { + + /** + * Constructs a new ListCollectionIdsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListCollectionIdsRequest); + + /** ListCollectionIdsRequest parent. */ + public parent: string; + + /** ListCollectionIdsRequest pageSize. */ + public pageSize: number; + + /** ListCollectionIdsRequest pageToken. */ + public pageToken: string; + + /** ListCollectionIdsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ListCollectionIdsRequest consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListCollectionIdsRequest; + + /** + * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. + * @param message ListCollectionIdsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListCollectionIdsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListCollectionIdsResponse. */ + interface IListCollectionIdsResponse { + + /** ListCollectionIdsResponse collectionIds */ + collectionIds?: (string[]|null); + + /** ListCollectionIdsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListCollectionIdsResponse. */ + class ListCollectionIdsResponse implements IListCollectionIdsResponse { + + /** + * Constructs a new ListCollectionIdsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListCollectionIdsResponse); + + /** ListCollectionIdsResponse collectionIds. */ + public collectionIds: string[]; + + /** ListCollectionIdsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListCollectionIdsResponse; + + /** + * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. + * @param message ListCollectionIdsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListCollectionIdsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteRequest. */ + interface IBatchWriteRequest { + + /** BatchWriteRequest database */ + database?: (string|null); + + /** BatchWriteRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); + + /** BatchWriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a BatchWriteRequest. */ + class BatchWriteRequest implements IBatchWriteRequest { + + /** + * Constructs a new BatchWriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchWriteRequest); + + /** BatchWriteRequest database. */ + public database: string; + + /** BatchWriteRequest writes. */ + public writes: google.firestore.v1.IWrite[]; + + /** BatchWriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchWriteRequest; + + /** + * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. + * @param message BatchWriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchWriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteResponse. */ + interface IBatchWriteResponse { + + /** BatchWriteResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); + + /** BatchWriteResponse status */ + status?: (google.rpc.IStatus[]|null); + } + + /** Represents a BatchWriteResponse. */ + class BatchWriteResponse implements IBatchWriteResponse { + + /** + * Constructs a new BatchWriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchWriteResponse); + + /** BatchWriteResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; + + /** BatchWriteResponse status. */ + public status: google.rpc.IStatus[]; + + /** + * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchWriteResponse; + + /** + * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. + * @param message BatchWriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchWriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StructuredPipeline. */ + interface IStructuredPipeline { + + /** StructuredPipeline pipeline */ + pipeline?: (google.firestore.v1.IPipeline|null); + + /** StructuredPipeline options */ + options?: ({ [k: string]: google.firestore.v1.IValue }|null); + } + + /** Represents a StructuredPipeline. */ + class StructuredPipeline implements IStructuredPipeline { + + /** + * Constructs a new StructuredPipeline. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IStructuredPipeline); + + /** StructuredPipeline pipeline. */ + public pipeline?: (google.firestore.v1.IPipeline|null); + + /** StructuredPipeline options. */ + public options: { [k: string]: google.firestore.v1.IValue }; + + /** + * Creates a StructuredPipeline message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredPipeline + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredPipeline; + + /** + * Creates a plain object from a StructuredPipeline message. Also converts values to other types if specified. + * @param message StructuredPipeline + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredPipeline, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructuredPipeline to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredPipeline + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StructuredQuery. */ + interface IStructuredQuery { + + /** StructuredQuery select */ + select?: (google.firestore.v1.StructuredQuery.IProjection|null); + + /** StructuredQuery from */ + from?: (google.firestore.v1.StructuredQuery.ICollectionSelector[]|null); + + /** StructuredQuery where */ + where?: (google.firestore.v1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy */ + orderBy?: (google.firestore.v1.StructuredQuery.IOrder[]|null); + + /** StructuredQuery startAt */ + startAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery endAt */ + endAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery offset */ + offset?: (number|null); + + /** StructuredQuery limit */ + limit?: (google.protobuf.IInt32Value|null); + + /** StructuredQuery findNearest */ + findNearest?: (google.firestore.v1.StructuredQuery.IFindNearest|null); + } + + /** Represents a StructuredQuery. */ + class StructuredQuery implements IStructuredQuery { + + /** + * Constructs a new StructuredQuery. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IStructuredQuery); + + /** StructuredQuery select. */ + public select?: (google.firestore.v1.StructuredQuery.IProjection|null); + + /** StructuredQuery from. */ + public from: google.firestore.v1.StructuredQuery.ICollectionSelector[]; + + /** StructuredQuery where. */ + public where?: (google.firestore.v1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy. */ + public orderBy: google.firestore.v1.StructuredQuery.IOrder[]; + + /** StructuredQuery startAt. */ + public startAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery endAt. */ + public endAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery offset. */ + public offset: number; + + /** StructuredQuery limit. */ + public limit?: (google.protobuf.IInt32Value|null); + + /** StructuredQuery findNearest. */ + public findNearest?: (google.firestore.v1.StructuredQuery.IFindNearest|null); + + /** + * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredQuery + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery; + + /** + * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. + * @param message StructuredQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructuredQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace StructuredQuery { + + /** Properties of a CollectionSelector. */ + interface ICollectionSelector { + + /** CollectionSelector collectionId */ + collectionId?: (string|null); + + /** CollectionSelector allDescendants */ + allDescendants?: (boolean|null); + } + + /** Represents a CollectionSelector. */ + class CollectionSelector implements ICollectionSelector { + + /** + * Constructs a new CollectionSelector. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.ICollectionSelector); + + /** CollectionSelector collectionId. */ + public collectionId: string; + + /** CollectionSelector allDescendants. */ + public allDescendants: boolean; + + /** + * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CollectionSelector + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.CollectionSelector; + + /** + * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. + * @param message CollectionSelector + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.CollectionSelector, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CollectionSelector to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CollectionSelector + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Filter. */ + interface IFilter { + + /** Filter compositeFilter */ + compositeFilter?: (google.firestore.v1.StructuredQuery.ICompositeFilter|null); + + /** Filter fieldFilter */ + fieldFilter?: (google.firestore.v1.StructuredQuery.IFieldFilter|null); + + /** Filter unaryFilter */ + unaryFilter?: (google.firestore.v1.StructuredQuery.IUnaryFilter|null); + } + + /** Represents a Filter. */ + class Filter implements IFilter { + + /** + * Constructs a new Filter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFilter); + + /** Filter compositeFilter. */ + public compositeFilter?: (google.firestore.v1.StructuredQuery.ICompositeFilter|null); + + /** Filter fieldFilter. */ + public fieldFilter?: (google.firestore.v1.StructuredQuery.IFieldFilter|null); + + /** Filter unaryFilter. */ + public unaryFilter?: (google.firestore.v1.StructuredQuery.IUnaryFilter|null); + + /** Filter filterType. */ + public filterType?: ("compositeFilter"|"fieldFilter"|"unaryFilter"); + + /** + * Creates a Filter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Filter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Filter; + + /** + * Creates a plain object from a Filter message. Also converts values to other types if specified. + * @param message Filter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Filter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Filter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Filter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CompositeFilter. */ + interface ICompositeFilter { + + /** CompositeFilter op */ + op?: (google.firestore.v1.StructuredQuery.CompositeFilter.Operator|null); + + /** CompositeFilter filters */ + filters?: (google.firestore.v1.StructuredQuery.IFilter[]|null); + } + + /** Represents a CompositeFilter. */ + class CompositeFilter implements ICompositeFilter { + + /** + * Constructs a new CompositeFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.ICompositeFilter); + + /** CompositeFilter op. */ + public op: google.firestore.v1.StructuredQuery.CompositeFilter.Operator; + + /** CompositeFilter filters. */ + public filters: google.firestore.v1.StructuredQuery.IFilter[]; + + /** + * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CompositeFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.CompositeFilter; + + /** + * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. + * @param message CompositeFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.CompositeFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CompositeFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CompositeFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace CompositeFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "AND"| "OR"; + } + + /** Properties of a FieldFilter. */ + interface IFieldFilter { + + /** FieldFilter field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op */ + op?: (google.firestore.v1.StructuredQuery.FieldFilter.Operator|null); + + /** FieldFilter value */ + value?: (google.firestore.v1.IValue|null); + } + + /** Represents a FieldFilter. */ + class FieldFilter implements IFieldFilter { + + /** + * Constructs a new FieldFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFieldFilter); + + /** FieldFilter field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op. */ + public op: google.firestore.v1.StructuredQuery.FieldFilter.Operator; + + /** FieldFilter value. */ + public value?: (google.firestore.v1.IValue|null); + + /** + * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FieldFilter; + + /** + * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. + * @param message FieldFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FieldFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "LESS_THAN"| "LESS_THAN_OR_EQUAL"| "GREATER_THAN"| "GREATER_THAN_OR_EQUAL"| "EQUAL"| "NOT_EQUAL"| "ARRAY_CONTAINS"| "IN"| "ARRAY_CONTAINS_ANY"| "NOT_IN"; + } + + /** Properties of an UnaryFilter. */ + interface IUnaryFilter { + + /** UnaryFilter op */ + op?: (google.firestore.v1.StructuredQuery.UnaryFilter.Operator|null); + + /** UnaryFilter field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } + + /** Represents an UnaryFilter. */ + class UnaryFilter implements IUnaryFilter { + + /** + * Constructs a new UnaryFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IUnaryFilter); + + /** UnaryFilter op. */ + public op: google.firestore.v1.StructuredQuery.UnaryFilter.Operator; + + /** UnaryFilter field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** UnaryFilter operandType. */ + public operandType?: "field"; + + /** + * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UnaryFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.UnaryFilter; + + /** + * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. + * @param message UnaryFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.UnaryFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UnaryFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UnaryFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UnaryFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "IS_NAN"| "IS_NULL"| "IS_NOT_NAN"| "IS_NOT_NULL"; + } + + /** Properties of an Order. */ + interface IOrder { + + /** Order field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** Order direction */ + direction?: (google.firestore.v1.StructuredQuery.Direction|null); + } + + /** Represents an Order. */ + class Order implements IOrder { + + /** + * Constructs a new Order. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IOrder); + + /** Order field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** Order direction. */ + public direction: google.firestore.v1.StructuredQuery.Direction; + + /** + * Creates an Order message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Order + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Order; + + /** + * Creates a plain object from an Order message. Also converts values to other types if specified. + * @param message Order + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Order, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Order to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Order + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Direction enum. */ + type Direction = + "DIRECTION_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; + + /** Properties of a FieldReference. */ + interface IFieldReference { + + /** FieldReference fieldPath */ + fieldPath?: (string|null); + } + + /** Represents a FieldReference. */ + class FieldReference implements IFieldReference { + + /** + * Constructs a new FieldReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFieldReference); + + /** FieldReference fieldPath. */ + public fieldPath: string; + + /** + * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldReference + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FieldReference; + + /** + * Creates a plain object from a FieldReference message. Also converts values to other types if specified. + * @param message FieldReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FieldReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Projection. */ + interface IProjection { + + /** Projection fields */ + fields?: (google.firestore.v1.StructuredQuery.IFieldReference[]|null); + } + + /** Represents a Projection. */ + class Projection implements IProjection { + + /** + * Constructs a new Projection. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IProjection); + + /** Projection fields. */ + public fields: google.firestore.v1.StructuredQuery.IFieldReference[]; + + /** + * Creates a Projection message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Projection + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Projection; + + /** + * Creates a plain object from a Projection message. Also converts values to other types if specified. + * @param message Projection + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Projection, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Projection to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Projection + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FindNearest. */ + interface IFindNearest { + + /** FindNearest vectorField */ + vectorField?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FindNearest queryVector */ + queryVector?: (google.firestore.v1.IValue|null); + + /** FindNearest distanceMeasure */ + distanceMeasure?: (google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure|null); + + /** FindNearest limit */ + limit?: (google.protobuf.IInt32Value|null); + + /** FindNearest distanceResultField */ + distanceResultField?: (string|null); + + /** FindNearest distanceThreshold */ + distanceThreshold?: (google.protobuf.IDoubleValue|null); + } + + /** Represents a FindNearest. */ + class FindNearest implements IFindNearest { + + /** + * Constructs a new FindNearest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFindNearest); + + /** FindNearest vectorField. */ + public vectorField?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FindNearest queryVector. */ + public queryVector?: (google.firestore.v1.IValue|null); + + /** FindNearest distanceMeasure. */ + public distanceMeasure: google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure; + + /** FindNearest limit. */ + public limit?: (google.protobuf.IInt32Value|null); + + /** FindNearest distanceResultField. */ + public distanceResultField: string; + + /** FindNearest distanceThreshold. */ + public distanceThreshold?: (google.protobuf.IDoubleValue|null); + + /** + * Creates a FindNearest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FindNearest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FindNearest; + + /** + * Creates a plain object from a FindNearest message. Also converts values to other types if specified. + * @param message FindNearest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FindNearest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FindNearest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FindNearest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FindNearest { + + /** DistanceMeasure enum. */ + type DistanceMeasure = + "DISTANCE_MEASURE_UNSPECIFIED"| "EUCLIDEAN"| "COSINE"| "DOT_PRODUCT"; + } + } + + /** Properties of a StructuredAggregationQuery. */ + interface IStructuredAggregationQuery { + + /** StructuredAggregationQuery structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** StructuredAggregationQuery aggregations */ + aggregations?: (google.firestore.v1.StructuredAggregationQuery.IAggregation[]|null); + } + + /** Represents a StructuredAggregationQuery. */ + class StructuredAggregationQuery implements IStructuredAggregationQuery { + + /** + * Constructs a new StructuredAggregationQuery. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IStructuredAggregationQuery); + + /** StructuredAggregationQuery structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** StructuredAggregationQuery aggregations. */ + public aggregations: google.firestore.v1.StructuredAggregationQuery.IAggregation[]; + + /** StructuredAggregationQuery queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a StructuredAggregationQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredAggregationQuery + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery; + + /** + * Creates a plain object from a StructuredAggregationQuery message. Also converts values to other types if specified. + * @param message StructuredAggregationQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructuredAggregationQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredAggregationQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace StructuredAggregationQuery { + + /** Properties of an Aggregation. */ + interface IAggregation { + + /** Aggregation count */ + count?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null); + + /** Aggregation sum */ + sum?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null); + + /** Aggregation avg */ + avg?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null); + + /** Aggregation alias */ + alias?: (string|null); + } + + /** Represents an Aggregation. */ + class Aggregation implements IAggregation { + + /** + * Constructs a new Aggregation. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.IAggregation); + + /** Aggregation count. */ + public count?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null); + + /** Aggregation sum. */ + public sum?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null); + + /** Aggregation avg. */ + public avg?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null); + + /** Aggregation alias. */ + public alias: string; + + /** Aggregation operator. */ + public operator?: ("count"|"sum"|"avg"); + + /** + * Creates an Aggregation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Aggregation + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation; + + /** + * Creates a plain object from an Aggregation message. Also converts values to other types if specified. + * @param message Aggregation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Aggregation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Aggregation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Aggregation { + + /** Properties of a Count. */ + interface ICount { + + /** Count upTo */ + upTo?: (google.protobuf.IInt64Value|null); + } + + /** Represents a Count. */ + class Count implements ICount { + + /** + * Constructs a new Count. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount); + + /** Count upTo. */ + public upTo?: (google.protobuf.IInt64Value|null); + + /** + * Creates a Count message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Count + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Count; + + /** + * Creates a plain object from a Count message. Also converts values to other types if specified. + * @param message Count + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Count, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Count to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Count + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Sum. */ + interface ISum { + + /** Sum field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } + + /** Represents a Sum. */ + class Sum implements ISum { + + /** + * Constructs a new Sum. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum); + + /** Sum field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** + * Creates a Sum message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Sum + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum; + + /** + * Creates a plain object from a Sum message. Also converts values to other types if specified. + * @param message Sum + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Sum to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Sum + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Avg. */ + interface IAvg { + + /** Avg field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } + + /** Represents an Avg. */ + class Avg implements IAvg { + + /** + * Constructs a new Avg. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg); + + /** Avg field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** + * Creates an Avg message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Avg + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg; + + /** + * Creates a plain object from an Avg message. Also converts values to other types if specified. + * @param message Avg + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Avg to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Avg + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** Properties of a Cursor. */ + interface ICursor { + + /** Cursor values */ + values?: (google.firestore.v1.IValue[]|null); + + /** Cursor before */ + before?: (boolean|null); + } + + /** Represents a Cursor. */ + class Cursor implements ICursor { + + /** + * Constructs a new Cursor. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICursor); + + /** Cursor values. */ + public values: google.firestore.v1.IValue[]; + + /** Cursor before. */ + public before: boolean; + + /** + * Creates a Cursor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Cursor + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Cursor; + + /** + * Creates a plain object from a Cursor message. Also converts values to other types if specified. + * @param message Cursor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Cursor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Cursor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Cursor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExplainOptions. */ + interface IExplainOptions { + + /** ExplainOptions analyze */ + analyze?: (boolean|null); + } + + /** Represents an ExplainOptions. */ + class ExplainOptions implements IExplainOptions { + + /** + * Constructs a new ExplainOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExplainOptions); + + /** ExplainOptions analyze. */ + public analyze: boolean; + + /** + * Creates an ExplainOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExplainOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainOptions; + + /** + * Creates a plain object from an ExplainOptions message. Also converts values to other types if specified. + * @param message ExplainOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExplainOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExplainOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExplainOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExplainMetrics. */ + interface IExplainMetrics { + + /** ExplainMetrics planSummary */ + planSummary?: (google.firestore.v1.IPlanSummary|null); + + /** ExplainMetrics executionStats */ + executionStats?: (google.firestore.v1.IExecutionStats|null); + } + + /** Represents an ExplainMetrics. */ + class ExplainMetrics implements IExplainMetrics { + + /** + * Constructs a new ExplainMetrics. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExplainMetrics); + + /** ExplainMetrics planSummary. */ + public planSummary?: (google.firestore.v1.IPlanSummary|null); + + /** ExplainMetrics executionStats. */ + public executionStats?: (google.firestore.v1.IExecutionStats|null); + + /** + * Creates an ExplainMetrics message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExplainMetrics + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainMetrics; + + /** + * Creates a plain object from an ExplainMetrics message. Also converts values to other types if specified. + * @param message ExplainMetrics + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExplainMetrics, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExplainMetrics to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExplainMetrics + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PlanSummary. */ + interface IPlanSummary { + + /** PlanSummary indexesUsed */ + indexesUsed?: (google.protobuf.IStruct[]|null); + } + + /** Represents a PlanSummary. */ + class PlanSummary implements IPlanSummary { + + /** + * Constructs a new PlanSummary. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPlanSummary); + + /** PlanSummary indexesUsed. */ + public indexesUsed: google.protobuf.IStruct[]; + + /** + * Creates a PlanSummary message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PlanSummary + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PlanSummary; + + /** + * Creates a plain object from a PlanSummary message. Also converts values to other types if specified. + * @param message PlanSummary + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.PlanSummary, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PlanSummary to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PlanSummary + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExecutionStats. */ + interface IExecutionStats { + + /** ExecutionStats resultsReturned */ + resultsReturned?: (number|string|null); + + /** ExecutionStats executionDuration */ + executionDuration?: (google.protobuf.IDuration|null); + + /** ExecutionStats readOperations */ + readOperations?: (number|string|null); + + /** ExecutionStats debugStats */ + debugStats?: (google.protobuf.IStruct|null); + } + + /** Represents an ExecutionStats. */ + class ExecutionStats implements IExecutionStats { + + /** + * Constructs a new ExecutionStats. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExecutionStats); + + /** ExecutionStats resultsReturned. */ + public resultsReturned: (number|string); + + /** ExecutionStats executionDuration. */ + public executionDuration?: (google.protobuf.IDuration|null); + + /** ExecutionStats readOperations. */ + public readOperations: (number|string); + + /** ExecutionStats debugStats. */ + public debugStats?: (google.protobuf.IStruct|null); + + /** + * Creates an ExecutionStats message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecutionStats + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutionStats; + + /** + * Creates a plain object from an ExecutionStats message. Also converts values to other types if specified. + * @param message ExecutionStats + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExecutionStats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecutionStats to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecutionStats + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Write. */ + interface IWrite { + + /** Write update */ + update?: (google.firestore.v1.IDocument|null); + + /** Write delete */ + "delete"?: (string|null); + + /** Write transform */ + transform?: (google.firestore.v1.IDocumentTransform|null); + + /** Write updateMask */ + updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** Write updateTransforms */ + updateTransforms?: (google.firestore.v1.DocumentTransform.IFieldTransform[]|null); + + /** Write currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); + } + + /** Represents a Write. */ + class Write implements IWrite { + + /** + * Constructs a new Write. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWrite); + + /** Write update. */ + public update?: (google.firestore.v1.IDocument|null); + + /** Write delete. */ + public delete?: (string|null); + + /** Write transform. */ + public transform?: (google.firestore.v1.IDocumentTransform|null); + + /** Write updateMask. */ + public updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** Write updateTransforms. */ + public updateTransforms: google.firestore.v1.DocumentTransform.IFieldTransform[]; + + /** Write currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); + + /** Write operation. */ + public operation?: ("update"|"delete"|"transform"); + + /** + * Creates a Write message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Write + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Write; + + /** + * Creates a plain object from a Write message. Also converts values to other types if specified. + * @param message Write + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Write, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Write to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Write + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentTransform. */ + interface IDocumentTransform { + + /** DocumentTransform document */ + document?: (string|null); + + /** DocumentTransform fieldTransforms */ + fieldTransforms?: (google.firestore.v1.DocumentTransform.IFieldTransform[]|null); + } + + /** Represents a DocumentTransform. */ + class DocumentTransform implements IDocumentTransform { + + /** + * Constructs a new DocumentTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentTransform); + + /** DocumentTransform document. */ + public document: string; + + /** DocumentTransform fieldTransforms. */ + public fieldTransforms: google.firestore.v1.DocumentTransform.IFieldTransform[]; + + /** + * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentTransform; + + /** + * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. + * @param message DocumentTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DocumentTransform { + + /** Properties of a FieldTransform. */ + interface IFieldTransform { + + /** FieldTransform fieldPath */ + fieldPath?: (string|null); + + /** FieldTransform setToServerValue */ + setToServerValue?: (google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment */ + increment?: (google.firestore.v1.IValue|null); + + /** FieldTransform maximum */ + maximum?: (google.firestore.v1.IValue|null); + + /** FieldTransform minimum */ + minimum?: (google.firestore.v1.IValue|null); + + /** FieldTransform appendMissingElements */ + appendMissingElements?: (google.firestore.v1.IArrayValue|null); + + /** FieldTransform removeAllFromArray */ + removeAllFromArray?: (google.firestore.v1.IArrayValue|null); + } + + /** Represents a FieldTransform. */ + class FieldTransform implements IFieldTransform { + + /** + * Constructs a new FieldTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.DocumentTransform.IFieldTransform); + + /** FieldTransform fieldPath. */ + public fieldPath: string; + + /** FieldTransform setToServerValue. */ + public setToServerValue?: (google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment. */ + public increment?: (google.firestore.v1.IValue|null); + + /** FieldTransform maximum. */ + public maximum?: (google.firestore.v1.IValue|null); + + /** FieldTransform minimum. */ + public minimum?: (google.firestore.v1.IValue|null); + + /** FieldTransform appendMissingElements. */ + public appendMissingElements?: (google.firestore.v1.IArrayValue|null); + + /** FieldTransform removeAllFromArray. */ + public removeAllFromArray?: (google.firestore.v1.IArrayValue|null); + + /** FieldTransform transformType. */ + public transformType?: ("setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"); + + /** + * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentTransform.FieldTransform; + + /** + * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. + * @param message FieldTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentTransform.FieldTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldTransform { + + /** ServerValue enum. */ + type ServerValue = + "SERVER_VALUE_UNSPECIFIED"| "REQUEST_TIME"; + } + } + + /** Properties of a WriteResult. */ + interface IWriteResult { + + /** WriteResult updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** WriteResult transformResults */ + transformResults?: (google.firestore.v1.IValue[]|null); + } + + /** Represents a WriteResult. */ + class WriteResult implements IWriteResult { + + /** + * Constructs a new WriteResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteResult); + + /** WriteResult updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** WriteResult transformResults. */ + public transformResults: google.firestore.v1.IValue[]; + + /** + * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResult + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteResult; + + /** + * Creates a plain object from a WriteResult message. Also converts values to other types if specified. + * @param message WriteResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentChange. */ + interface IDocumentChange { + + /** DocumentChange document */ + document?: (google.firestore.v1.IDocument|null); + + /** DocumentChange targetIds */ + targetIds?: (number[]|null); + + /** DocumentChange removedTargetIds */ + removedTargetIds?: (number[]|null); + } + + /** Represents a DocumentChange. */ + class DocumentChange implements IDocumentChange { + + /** + * Constructs a new DocumentChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentChange); + + /** DocumentChange document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** DocumentChange targetIds. */ + public targetIds: number[]; + + /** DocumentChange removedTargetIds. */ + public removedTargetIds: number[]; + + /** + * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentChange; + + /** + * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. + * @param message DocumentChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentDelete. */ + interface IDocumentDelete { + + /** DocumentDelete document */ + document?: (string|null); + + /** DocumentDelete removedTargetIds */ + removedTargetIds?: (number[]|null); + + /** DocumentDelete readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a DocumentDelete. */ + class DocumentDelete implements IDocumentDelete { + + /** + * Constructs a new DocumentDelete. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentDelete); + + /** DocumentDelete document. */ + public document: string; + + /** DocumentDelete removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentDelete readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentDelete + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentDelete; + + /** + * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. + * @param message DocumentDelete + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentDelete, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentDelete to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentDelete + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentRemove. */ + interface IDocumentRemove { + + /** DocumentRemove document */ + document?: (string|null); + + /** DocumentRemove removedTargetIds */ + removedTargetIds?: (number[]|null); + + /** DocumentRemove readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a DocumentRemove. */ + class DocumentRemove implements IDocumentRemove { + + /** + * Constructs a new DocumentRemove. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentRemove); + + /** DocumentRemove document. */ + public document: string; + + /** DocumentRemove removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentRemove readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentRemove + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentRemove; + + /** + * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. + * @param message DocumentRemove + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentRemove, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentRemove to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentRemove + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExistenceFilter. */ + interface IExistenceFilter { + + /** ExistenceFilter targetId */ + targetId?: (number|null); + + /** ExistenceFilter count */ + count?: (number|null); + + /** ExistenceFilter unchangedNames */ + unchangedNames?: (google.firestore.v1.IBloomFilter|null); + } + + /** Represents an ExistenceFilter. */ + class ExistenceFilter implements IExistenceFilter { + + /** + * Constructs a new ExistenceFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExistenceFilter); + + /** ExistenceFilter targetId. */ + public targetId: number; + + /** ExistenceFilter count. */ + public count: number; + + /** ExistenceFilter unchangedNames. */ + public unchangedNames?: (google.firestore.v1.IBloomFilter|null); + + /** + * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExistenceFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExistenceFilter; + + /** + * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. + * @param message ExistenceFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExistenceFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExistenceFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExistenceFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** Namespace api. */ + namespace api { + + /** FieldBehavior enum. */ + type FieldBehavior = + "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { + + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); + + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + } + + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { + + /** + * Constructs a new CommonLanguageSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICommonLanguageSettings); + + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; + + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; + + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommonLanguageSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { + + /** ClientLibrarySettings version */ + version?: (string|null); + + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|null); + + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); + + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } + + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { + + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); + + /** ClientLibrarySettings version. */ + public version: string; + + /** ClientLibrarySettings launchStage. */ + public launchStage: google.api.LaunchStage; + + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; + + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Publishing. */ + interface IPublishing { + + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); + + /** Publishing newIssueUri */ + newIssueUri?: (string|null); + + /** Publishing documentationUri */ + documentationUri?: (string|null); + + /** Publishing apiShortName */ + apiShortName?: (string|null); + + /** Publishing githubLabel */ + githubLabel?: (string|null); + + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); + + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); + + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|null); + + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); + + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); + + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } + + /** Represents a Publishing. */ + class Publishing implements IPublishing { + + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); + + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; + + /** Publishing newIssueUri. */ + public newIssueUri: string; + + /** Publishing documentationUri. */ + public documentationUri: string; + + /** Publishing apiShortName. */ + public apiShortName: string; + + /** Publishing githubLabel. */ + public githubLabel: string; + + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; + + /** Publishing docTagPrefix. */ + public docTagPrefix: string; + + /** Publishing organization. */ + public organization: google.api.ClientLibraryOrganization; + + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; + + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; + + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a JavaSettings. */ + interface IJavaSettings { + + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); + + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); + + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { + + /** + * Constructs a new JavaSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IJavaSettings); + + /** JavaSettings libraryPackage. */ + public libraryPackage: string; + + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; + + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns JavaSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this JavaSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CppSettings. */ + interface ICppSettings { + + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { + + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); + + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PhpSettings. */ + interface IPhpSettings { + + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { + + /** + * Constructs a new PhpSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPhpSettings); + + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PythonSettings. */ + interface IPythonSettings { + + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + } + + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { + + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); + + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PythonSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PythonSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PythonSettings { + + /** Properties of an ExperimentalFeatures. */ + interface IExperimentalFeatures { + + /** ExperimentalFeatures restAsyncIoEnabled */ + restAsyncIoEnabled?: (boolean|null); + + /** ExperimentalFeatures protobufPythonicTypesEnabled */ + protobufPythonicTypesEnabled?: (boolean|null); + + /** ExperimentalFeatures unversionedPackageDisabled */ + unversionedPackageDisabled?: (boolean|null); + } + + /** Represents an ExperimentalFeatures. */ + class ExperimentalFeatures implements IExperimentalFeatures { + + /** + * Constructs a new ExperimentalFeatures. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.PythonSettings.IExperimentalFeatures); + + /** ExperimentalFeatures restAsyncIoEnabled. */ + public restAsyncIoEnabled: boolean; + + /** ExperimentalFeatures protobufPythonicTypesEnabled. */ + public protobufPythonicTypesEnabled: boolean; + + /** ExperimentalFeatures unversionedPackageDisabled. */ + public unversionedPackageDisabled: boolean; + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExperimentalFeatures + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @param message ExperimentalFeatures + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings.ExperimentalFeatures, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExperimentalFeatures + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a NodeSettings. */ + interface INodeSettings { + + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { + + /** + * Constructs a new NodeSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.INodeSettings); + + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NodeSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NodeSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { + + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); + + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); + + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); + + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); + } + + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { + + /** + * Constructs a new DotnetSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IDotnetSettings); + + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; + + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; + + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; + + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DotnetSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DotnetSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RubySettings. */ + interface IRubySettings { + + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { + + /** + * Constructs a new RubySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRubySettings); + + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GoSettings. */ + interface IGoSettings { + + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + } + + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { + + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); + + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodSettings. */ + interface IMethodSettings { + + /** MethodSettings selector */ + selector?: (string|null); + + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); + } + + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { + + /** + * Constructs a new MethodSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IMethodSettings); + + /** MethodSettings selector. */ + public selector: string; + + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodSettings { + + /** Properties of a LongRunning. */ + interface ILongRunning { + + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); + + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); + } + + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { + + /** + * Constructs a new LongRunning. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.MethodSettings.ILongRunning); + + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; + + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LongRunning + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LongRunning to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LongRunning + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** ClientLibraryOrganization enum. */ + type ClientLibraryOrganization = + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; + + /** ClientLibraryDestination enum. */ + type ClientLibraryDestination = + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; + + /** Properties of a SelectiveGapicGeneration. */ + interface ISelectiveGapicGeneration { + + /** SelectiveGapicGeneration methods */ + methods?: (string[]|null); + + /** SelectiveGapicGeneration generateOmittedAsInternal */ + generateOmittedAsInternal?: (boolean|null); + } + + /** Represents a SelectiveGapicGeneration. */ + class SelectiveGapicGeneration implements ISelectiveGapicGeneration { + + /** + * Constructs a new SelectiveGapicGeneration. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ISelectiveGapicGeneration); + + /** SelectiveGapicGeneration methods. */ + public methods: string[]; + + /** SelectiveGapicGeneration generateOmittedAsInternal. */ + public generateOmittedAsInternal: boolean; + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SelectiveGapicGeneration + */ + public static fromObject(object: { [k: string]: any }): google.api.SelectiveGapicGeneration; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @param message SelectiveGapicGeneration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.SelectiveGapicGeneration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; + + /** Properties of a RoutingRule. */ + interface IRoutingRule { + + /** RoutingRule routingParameters */ + routingParameters?: (google.api.IRoutingParameter[]|null); + } + + /** Represents a RoutingRule. */ + class RoutingRule implements IRoutingRule { + + /** + * Constructs a new RoutingRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRoutingRule); + + /** RoutingRule routingParameters. */ + public routingParameters: google.api.IRoutingParameter[]; + + /** + * Creates a RoutingRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingRule + */ + public static fromObject(object: { [k: string]: any }): google.api.RoutingRule; + + /** + * Creates a plain object from a RoutingRule message. Also converts values to other types if specified. + * @param message RoutingRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RoutingRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RoutingParameter. */ + interface IRoutingParameter { + + /** RoutingParameter field */ + field?: (string|null); + + /** RoutingParameter pathTemplate */ + pathTemplate?: (string|null); + } + + /** Represents a RoutingParameter. */ + class RoutingParameter implements IRoutingParameter { + + /** + * Constructs a new RoutingParameter. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRoutingParameter); + + /** RoutingParameter field. */ + public field: string; + + /** RoutingParameter pathTemplate. */ + public pathTemplate: string; + + /** + * Creates a RoutingParameter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingParameter + */ + public static fromObject(object: { [k: string]: any }): google.api.RoutingParameter; + + /** + * Creates a plain object from a RoutingParameter message. Also converts values to other types if specified. + * @param message RoutingParameter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RoutingParameter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingParameter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingParameter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { + + /** ResourceDescriptor type */ + type?: (string|null); + + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); + + /** ResourceDescriptor nameField */ + nameField?: (string|null); + + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|null); + + /** ResourceDescriptor plural */ + plural?: (string|null); + + /** ResourceDescriptor singular */ + singular?: (string|null); + + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } + + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { + + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); + + /** ResourceDescriptor type. */ + public type: string; + + /** ResourceDescriptor pattern. */ + public pattern: string[]; + + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: google.api.ResourceDescriptor.History; + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ResourceDescriptor { + + /** History enum. */ + type History = + "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; + + /** Style enum. */ + type Style = + "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + } + + /** Properties of a ResourceReference. */ + interface IResourceReference { + + /** ResourceReference type */ + type?: (string|null); + + /** ResourceReference childType */ + childType?: (string|null); + } + + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { + + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); + + /** ResourceReference type. */ + public type: string; + + /** ResourceReference childType. */ + public childType: string; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); + + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Edition enum. */ + type Edition = + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; + + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { + + /** FileDescriptorProto name */ + name?: (string|null); + + /** FileDescriptorProto package */ + "package"?: (string|null); + + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); + + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); + + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); + + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); + + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); + + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax */ + syntax?: (string|null); + + /** FileDescriptorProto edition */ + edition?: (google.protobuf.Edition|null); + } + + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { + + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); + + /** FileDescriptorProto name. */ + public name: string; + + /** FileDescriptorProto package. */ + public package: string; + + /** FileDescriptorProto dependency. */ + public dependency: string[]; + + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; + + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; + + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; + + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; + + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax. */ + public syntax: string; + + /** FileDescriptorProto edition. */ + public edition: google.protobuf.Edition; + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { + + /** DescriptorProto name */ + name?: (string|null); + + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { + + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); + + /** DescriptorProto name. */ + public name: string; + + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; + + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + + /** DescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DescriptorProto { + + /** Properties of an ExtensionRange. */ + interface IExtensionRange { + + /** ExtensionRange start */ + start?: (number|null); + + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); + } + + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { + + /** + * Constructs a new ExtensionRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + + /** ExtensionRange start. */ + public start: number; + + /** ExtensionRange end. */ + public end: number; + + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReservedRange. */ + interface IReservedRange { + + /** ReservedRange start */ + start?: (number|null); + + /** ReservedRange end */ + end?: (number|null); + } + + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { + + /** + * Constructs a new ReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + + /** ReservedRange start. */ + public start: number; + + /** ReservedRange end. */ + public end: number; + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ExtensionRangeOptions declaration */ + declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); + + /** ExtensionRangeOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification */ + verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** ExtensionRangeOptions declaration. */ + public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; + + /** ExtensionRangeOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification. */ + public verification: google.protobuf.ExtensionRangeOptions.VerificationState; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExtensionRangeOptions { + + /** Properties of a Declaration. */ + interface IDeclaration { + + /** Declaration number */ + number?: (number|null); + + /** Declaration fullName */ + fullName?: (string|null); + + /** Declaration type */ + type?: (string|null); + + /** Declaration reserved */ + reserved?: (boolean|null); + + /** Declaration repeated */ + repeated?: (boolean|null); + } + + /** Represents a Declaration. */ + class Declaration implements IDeclaration { + + /** + * Constructs a new Declaration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); + + /** Declaration number. */ + public number: number; + + /** Declaration fullName. */ + public fullName: string; + + /** Declaration type. */ + public type: string; + + /** Declaration reserved. */ + public reserved: boolean; + + /** Declaration repeated. */ + public repeated: boolean; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Declaration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @param message Declaration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Declaration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Declaration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** VerificationState enum. */ + type VerificationState = + "DECLARATION"| "UNVERIFIED"; + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; + + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldDescriptorProto { + + /** Type enum. */ + type Type = + "TYPE_DOUBLE"| "TYPE_FLOAT"| "TYPE_INT64"| "TYPE_UINT64"| "TYPE_INT32"| "TYPE_FIXED64"| "TYPE_FIXED32"| "TYPE_BOOL"| "TYPE_STRING"| "TYPE_GROUP"| "TYPE_MESSAGE"| "TYPE_BYTES"| "TYPE_UINT32"| "TYPE_ENUM"| "TYPE_SFIXED32"| "TYPE_SFIXED64"| "TYPE_SINT32"| "TYPE_SINT64"; + + /** Label enum. */ + type Label = + "LABEL_OPTIONAL"| "LABEL_REPEATED"| "LABEL_REQUIRED"; + } + + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { + + /** OneofDescriptorProto name */ + name?: (string|null); + + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } + + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { + + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); + + /** OneofDescriptorProto name. */ + public name: string; + + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { + + /** EnumDescriptorProto name */ + name?: (string|null); + + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { + + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); + + /** EnumDescriptorProto name. */ + public name: string; + + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; + + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { + + /** EnumValueDescriptorProto name */ + name?: (string|null); + + /** EnumValueDescriptorProto number */ + number?: (number|null); + + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } + + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + + /** EnumValueDescriptorProto name. */ + public name: string; + + /** EnumValueDescriptorProto number. */ + public number: number; + + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { + + /** ServiceDescriptorProto name */ + name?: (string|null); + + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); + + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } + + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { + + /** FileOptions javaPackage */ + javaPackage?: (string|null); + + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); + + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); + + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); + + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); + + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + + /** FileOptions goPackage */ + goPackage?: (string|null); + + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); + + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); + + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); + + /** FileOptions deprecated */ + deprecated?: (boolean|null); + + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); + + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); + + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); + + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); + } + + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { + + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); + + /** FileOptions javaPackage. */ + public javaPackage: string; + + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; + + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; + + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; + + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; + + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + + /** FileOptions goPackage. */ + public goPackage: string; + + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; + + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; + + /** FileOptions deprecated. */ + public deprecated: boolean; + + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; + + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; + + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + type OptimizeMode = + "SPEED"| "CODE_SIZE"| "LITE_RUNTIME"; + } + + /** Properties of a MessageOptions. */ + interface IMessageOptions { + + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); + + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); + + /** MessageOptions deprecated */ + deprecated?: (boolean|null); + + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); + + /** MessageOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** MessageOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MessageOptions .google.api.resource */ + ".google.api.resource"?: (google.api.IResourceDescriptor|null); + } + + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { + + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); + + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; + + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; + + /** MessageOptions deprecated. */ + public deprecated: boolean; + + /** MessageOptions mapEntry. */ + public mapEntry: boolean; + + /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** MessageOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MessageOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldOptions. */ + interface IFieldOptions { + + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); + + /** FieldOptions packed */ + packed?: (boolean|null); + + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); + + /** FieldOptions lazy */ + lazy?: (boolean|null); + + /** FieldOptions unverifiedLazy */ + unverifiedLazy?: (boolean|null); + + /** FieldOptions deprecated */ + deprecated?: (boolean|null); + + /** FieldOptions weak */ + weak?: (boolean|null); + + /** FieldOptions debugRedact */ + debugRedact?: (boolean|null); + + /** FieldOptions retention */ + retention?: (google.protobuf.FieldOptions.OptionRetention|null); + + /** FieldOptions targets */ + targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); + + /** FieldOptions editionDefaults */ + editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); + + /** FieldOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FieldOptions .google.api.fieldBehavior */ + ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); + + /** FieldOptions .google.api.resourceReference */ + ".google.api.resourceReference"?: (google.api.IResourceReference|null); + } + + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { + + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); + + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; + + /** FieldOptions packed. */ + public packed: boolean; + + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; + + /** FieldOptions lazy. */ + public lazy: boolean; + + /** FieldOptions unverifiedLazy. */ + public unverifiedLazy: boolean; + + /** FieldOptions deprecated. */ + public deprecated: boolean; + + /** FieldOptions weak. */ + public weak: boolean; + + /** FieldOptions debugRedact. */ + public debugRedact: boolean; + + /** FieldOptions retention. */ + public retention: google.protobuf.FieldOptions.OptionRetention; + + /** FieldOptions targets. */ + public targets: google.protobuf.FieldOptions.OptionTargetType[]; + + /** FieldOptions editionDefaults. */ + public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; + + /** FieldOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldOptions { + + /** CType enum. */ + type CType = + "STRING"| "CORD"| "STRING_PIECE"; + + /** JSType enum. */ + type JSType = + "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; + + /** OptionRetention enum. */ + type OptionRetention = + "RETENTION_UNKNOWN"| "RETENTION_RUNTIME"| "RETENTION_SOURCE"; + + /** OptionTargetType enum. */ + type OptionTargetType = + "TARGET_TYPE_UNKNOWN"| "TARGET_TYPE_FILE"| "TARGET_TYPE_EXTENSION_RANGE"| "TARGET_TYPE_MESSAGE"| "TARGET_TYPE_FIELD"| "TARGET_TYPE_ONEOF"| "TARGET_TYPE_ENUM"| "TARGET_TYPE_ENUM_ENTRY"| "TARGET_TYPE_SERVICE"| "TARGET_TYPE_METHOD"; + + /** Properties of an EditionDefault. */ + interface IEditionDefault { + + /** EditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** EditionDefault value */ + value?: (string|null); + } + + /** Represents an EditionDefault. */ + class EditionDefault implements IEditionDefault { + + /** + * Constructs a new EditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); + + /** EditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** EditionDefault value. */ + public value: string; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @param message EditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an OneofOptions. */ + interface IOneofOptions { + + /** OneofOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { + + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); + + /** OneofOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumOptions. */ + interface IEnumOptions { + + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); + + /** EnumOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** EnumOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { + + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** EnumOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact */ + debugRedact?: (boolean|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { + + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); + + /** EnumValueOptions deprecated. */ + public deprecated: boolean; + + /** EnumValueOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact. */ + public debugRedact: boolean; + + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceOptions. */ + interface IServiceOptions { + + /** ServiceOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); + + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); + + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); + + /** ServiceOptions .google.api.apiVersion */ + ".google.api.apiVersion"?: (string|null); + } + + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { + + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); + + /** ServiceOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated. */ + public deprecated: boolean; + + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodOptions. */ + interface IMethodOptions { + + /** MethodOptions deprecated */ + deprecated?: (boolean|null); + + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); + + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); + + /** MethodOptions .google.api.routing */ + ".google.api.routing"?: (google.api.IRoutingRule|null); + + /** MethodOptions .google.longrunning.operationInfo */ + ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); + } + + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { + + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); + + /** MethodOptions deprecated. */ + public deprecated: boolean; + + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + type IdempotencyLevel = + "IDEMPOTENCY_UNKNOWN"| "NO_SIDE_EFFECTS"| "IDEMPOTENT"; + } + + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { + + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); + + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|string|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|string|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|string); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|string); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UninterpretedOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamePart + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a FeatureSet. */ + interface IFeatureSet { + + /** FeatureSet fieldPresence */ + fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|null); + + /** FeatureSet enumType */ + enumType?: (google.protobuf.FeatureSet.EnumType|null); + + /** FeatureSet repeatedFieldEncoding */ + repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|null); + + /** FeatureSet utf8Validation */ + utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|null); + + /** FeatureSet messageEncoding */ + messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|null); + + /** FeatureSet jsonFormat */ + jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|null); + } + + /** Represents a FeatureSet. */ + class FeatureSet implements IFeatureSet { + + /** + * Constructs a new FeatureSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSet); + + /** FeatureSet fieldPresence. */ + public fieldPresence: google.protobuf.FeatureSet.FieldPresence; + + /** FeatureSet enumType. */ + public enumType: google.protobuf.FeatureSet.EnumType; + + /** FeatureSet repeatedFieldEncoding. */ + public repeatedFieldEncoding: google.protobuf.FeatureSet.RepeatedFieldEncoding; + + /** FeatureSet utf8Validation. */ + public utf8Validation: google.protobuf.FeatureSet.Utf8Validation; + + /** FeatureSet messageEncoding. */ + public messageEncoding: google.protobuf.FeatureSet.MessageEncoding; + + /** FeatureSet jsonFormat. */ + public jsonFormat: google.protobuf.FeatureSet.JsonFormat; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @param message FeatureSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSet { + + /** FieldPresence enum. */ + type FieldPresence = + "FIELD_PRESENCE_UNKNOWN"| "EXPLICIT"| "IMPLICIT"| "LEGACY_REQUIRED"; + + /** EnumType enum. */ + type EnumType = + "ENUM_TYPE_UNKNOWN"| "OPEN"| "CLOSED"; + + /** RepeatedFieldEncoding enum. */ + type RepeatedFieldEncoding = + "REPEATED_FIELD_ENCODING_UNKNOWN"| "PACKED"| "EXPANDED"; + + /** Utf8Validation enum. */ + type Utf8Validation = + "UTF8_VALIDATION_UNKNOWN"| "VERIFY"| "NONE"; + + /** MessageEncoding enum. */ + type MessageEncoding = + "MESSAGE_ENCODING_UNKNOWN"| "LENGTH_PREFIXED"| "DELIMITED"; + + /** JsonFormat enum. */ + type JsonFormat = + "JSON_FORMAT_UNKNOWN"| "ALLOW"| "LEGACY_BEST_EFFORT"; + } + + /** Properties of a FeatureSetDefaults. */ + interface IFeatureSetDefaults { + + /** FeatureSetDefaults defaults */ + defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); + + /** FeatureSetDefaults minimumEdition */ + minimumEdition?: (google.protobuf.Edition|null); + + /** FeatureSetDefaults maximumEdition */ + maximumEdition?: (google.protobuf.Edition|null); + } + + /** Represents a FeatureSetDefaults. */ + class FeatureSetDefaults implements IFeatureSetDefaults { + + /** + * Constructs a new FeatureSetDefaults. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSetDefaults); + + /** FeatureSetDefaults defaults. */ + public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; + + /** FeatureSetDefaults minimumEdition. */ + public minimumEdition: google.protobuf.Edition; + + /** FeatureSetDefaults maximumEdition. */ + public maximumEdition: google.protobuf.Edition; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetDefaults + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @param message FeatureSetDefaults + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetDefaults + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSetDefaults { + + /** Properties of a FeatureSetEditionDefault. */ + interface IFeatureSetEditionDefault { + + /** FeatureSetEditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); + } + + /** Represents a FeatureSetEditionDefault. */ + class FeatureSetEditionDefault implements IFeatureSetEditionDefault { + + /** + * Constructs a new FeatureSetEditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); + + /** FeatureSetEditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetEditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @param message FeatureSetEditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { + + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } + + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { + + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); + + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SourceCodeInfo { + + /** Properties of a Location. */ + interface ILocation { + + /** Location path */ + path?: (number[]|null); + + /** Location span */ + span?: (number[]|null); + + /** Location leadingComments */ + leadingComments?: (string|null); + + /** Location trailingComments */ + trailingComments?: (string|null); + + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + + /** Location path. */ + public path: number[]; + + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Location + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { + + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } + + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { + + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); + + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + + /** Annotation semantic */ + semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); + } + + /** Represents an Annotation. */ + class Annotation implements IAnnotation { + + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); + + /** Annotation path. */ + public path: number[]; + + /** Annotation sourceFile. */ + public sourceFile: string; + + /** Annotation begin. */ + public begin: number; + + /** Annotation end. */ + public end: number; + + /** Annotation semantic. */ + public semantic: google.protobuf.GeneratedCodeInfo.Annotation.Semantic; + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Annotation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Annotation { + + /** Semantic enum. */ + type Semantic = + "NONE"| "SET"| "ALIAS"; + } + } + + /** Properties of a Struct. */ + interface IStruct { + + /** Struct fields */ + fields?: ({ [k: string]: google.protobuf.IValue }|null); + } + + /** Represents a Struct. */ + class Struct implements IStruct { + + /** + * Constructs a new Struct. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStruct); + + /** Struct fields. */ + public fields: { [k: string]: google.protobuf.IValue }; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Struct + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @param message Struct + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Struct to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Struct + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue */ + numberValue?: (number|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value boolValue */ + boolValue?: (boolean|null); + + /** Value structValue */ + structValue?: (google.protobuf.IStruct|null); + + /** Value listValue */ + listValue?: (google.protobuf.IListValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue. */ + public numberValue?: (number|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value boolValue. */ + public boolValue?: (boolean|null); + + /** Value structValue. */ + public structValue?: (google.protobuf.IStruct|null); + + /** Value listValue. */ + public listValue?: (google.protobuf.IListValue|null); + + /** Value kind. */ + public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** NullValue enum. */ + type NullValue = + "NULL_VALUE"; + + /** Properties of a ListValue. */ + interface IListValue { + + /** ListValue values */ + values?: (google.protobuf.IValue[]|null); + } + + /** Represents a ListValue. */ + class ListValue implements IListValue { + + /** + * Constructs a new ListValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IListValue); + + /** ListValue values. */ + public values: google.protobuf.IValue[]; + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @param message ListValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Timestamp. */ + interface ITimestamp { + + /** Timestamp seconds */ + seconds?: (number|string|null); + + /** Timestamp nanos */ + nanos?: (number|null); + } + + /** Represents a Timestamp. */ + class Timestamp implements ITimestamp { + + /** + * Constructs a new Timestamp. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ITimestamp); + + /** Timestamp seconds. */ + public seconds: (number|string); + + /** Timestamp nanos. */ + public nanos: number; + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Timestamp + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @param message Timestamp + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Timestamp to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Timestamp + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Any. */ + interface IAny { + + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|null); + } + + /** Represents an Any. */ + class Any implements IAny { + + /** + * Constructs a new Any. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IAny); + + /** Any type_url. */ + public type_url: string; + + /** Any value. */ + public value: Uint8Array; + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Any + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Any to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Any + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Duration. */ + interface IDuration { + + /** Duration seconds */ + seconds?: (number|string|null); + + /** Duration nanos */ + nanos?: (number|null); + } + + /** Represents a Duration. */ + class Duration implements IDuration { + + /** + * Constructs a new Duration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDuration); + + /** Duration seconds. */ + public seconds: (number|string); + + /** Duration nanos. */ + public nanos: number; + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Duration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Duration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Duration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DoubleValue. */ + interface IDoubleValue { + + /** DoubleValue value */ + value?: (number|null); + } + + /** Represents a DoubleValue. */ + class DoubleValue implements IDoubleValue { + + /** + * Constructs a new DoubleValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDoubleValue); + + /** DoubleValue value. */ + public value: number; + + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DoubleValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; + + /** + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @param message DoubleValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DoubleValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DoubleValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FloatValue. */ + interface IFloatValue { + + /** FloatValue value */ + value?: (number|null); + } + + /** Represents a FloatValue. */ + class FloatValue implements IFloatValue { + + /** + * Constructs a new FloatValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFloatValue); + + /** FloatValue value. */ + public value: number; + + /** + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FloatValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; + + /** + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. + * @param message FloatValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FloatValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FloatValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int64Value. */ + interface IInt64Value { + + /** Int64Value value */ + value?: (number|string|null); + } + + /** Represents an Int64Value. */ + class Int64Value implements IInt64Value { + + /** + * Constructs a new Int64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt64Value); + + /** Int64Value value. */ + public value: (number|string); + + /** + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; + + /** + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. + * @param message Int64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt64Value. */ + interface IUInt64Value { + + /** UInt64Value value */ + value?: (number|string|null); + } + + /** Represents a UInt64Value. */ + class UInt64Value implements IUInt64Value { + + /** + * Constructs a new UInt64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt64Value); + + /** UInt64Value value. */ + public value: (number|string); + + /** + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; + + /** + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. + * @param message UInt64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int32Value. */ + interface IInt32Value { + + /** Int32Value value */ + value?: (number|null); + } + + /** Represents an Int32Value. */ + class Int32Value implements IInt32Value { + + /** + * Constructs a new Int32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt32Value); + + /** Int32Value value. */ + public value: number; + + /** + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; + + /** + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. + * @param message Int32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt32Value. */ + interface IUInt32Value { + + /** UInt32Value value */ + value?: (number|null); + } + + /** Represents a UInt32Value. */ + class UInt32Value implements IUInt32Value { + + /** + * Constructs a new UInt32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt32Value); + + /** UInt32Value value. */ + public value: number; + + /** + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; + + /** + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. + * @param message UInt32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BoolValue. */ + interface IBoolValue { + + /** BoolValue value */ + value?: (boolean|null); + } + + /** Represents a BoolValue. */ + class BoolValue implements IBoolValue { + + /** + * Constructs a new BoolValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBoolValue); + + /** BoolValue value. */ + public value: boolean; + + /** + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BoolValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; + + /** + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. + * @param message BoolValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BoolValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BoolValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StringValue. */ + interface IStringValue { + + /** StringValue value */ + value?: (string|null); + } + + /** Represents a StringValue. */ + class StringValue implements IStringValue { + + /** + * Constructs a new StringValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStringValue); + + /** StringValue value. */ + public value: string; + + /** + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StringValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; + + /** + * Creates a plain object from a StringValue message. Also converts values to other types if specified. + * @param message StringValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StringValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StringValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BytesValue. */ + interface IBytesValue { + + /** BytesValue value */ + value?: (Uint8Array|null); + } + + /** Represents a BytesValue. */ + class BytesValue implements IBytesValue { + + /** + * Constructs a new BytesValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBytesValue); + + /** BytesValue value. */ + public value: Uint8Array; + + /** + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BytesValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; + + /** + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. + * @param message BytesValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BytesValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BytesValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Empty. */ + interface IEmpty { + } + + /** Represents an Empty. */ + class Empty implements IEmpty { + + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Empty + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldMask. */ + interface IFieldMask { + + /** FieldMask paths */ + paths?: (string[]|null); + } + + /** Represents a FieldMask. */ + class FieldMask implements IFieldMask { + + /** + * Constructs a new FieldMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldMask); + + /** FieldMask paths. */ + public paths: string[]; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldMask + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @param message FieldMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace type. */ + namespace type { + + /** Properties of a LatLng. */ + interface ILatLng { + + /** LatLng latitude */ + latitude?: (number|null); + + /** LatLng longitude */ + longitude?: (number|null); + } + + /** Represents a LatLng. */ + class LatLng implements ILatLng { + + /** + * Constructs a new LatLng. + * @param [properties] Properties to set + */ + constructor(properties?: google.type.ILatLng); + + /** LatLng latitude. */ + public latitude: number; + + /** LatLng longitude. */ + public longitude: number; + + /** + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LatLng + */ + public static fromObject(object: { [k: string]: any }): google.type.LatLng; + + /** + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @param message LatLng + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LatLng to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LatLng + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** DayOfWeek enum. */ + type DayOfWeek = + "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; + } + + /** Namespace rpc. */ + namespace rpc { + + /** Properties of a Status. */ + interface IStatus { + + /** Status code */ + code?: (number|null); + + /** Status message */ + message?: (string|null); + + /** Status details */ + details?: (google.protobuf.IAny[]|null); + } + + /** Represents a Status. */ + class Status implements IStatus { + + /** + * Constructs a new Status. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IStatus); + + /** Status code. */ + public code: number; + + /** Status message. */ + public message: string; + + /** Status details. */ + public details: google.protobuf.IAny[]; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Status + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Status; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @param message Status + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Status to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Status + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace longrunning. */ + namespace longrunning { + + /** Represents an Operations */ + class Operations extends $protobuf.rpc.Service { + + /** + * Constructs a new Operations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListOperationsResponse + */ + public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void; + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @returns Promise + */ + public listOperations(request: google.longrunning.IListOperationsRequest): Promise; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @returns Promise + */ + public getOperation(request: google.longrunning.IGetOperationRequest): Promise; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @returns Promise + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @returns Promise + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @returns Promise + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise; + } + + namespace Operations { + + /** + * Callback as used by {@link google.longrunning.Operations#listOperations}. + * @param error Error, if any + * @param [response] ListOperationsResponse + */ + type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#getOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#deleteOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#cancelOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#waitOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of an Operation. */ + interface IOperation { + + /** Operation name */ + name?: (string|null); + + /** Operation metadata */ + metadata?: (google.protobuf.IAny|null); + + /** Operation done */ + done?: (boolean|null); + + /** Operation error */ + error?: (google.rpc.IStatus|null); + + /** Operation response */ + response?: (google.protobuf.IAny|null); + } + + /** Represents an Operation. */ + class Operation implements IOperation { + + /** + * Constructs a new Operation. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperation); + + /** Operation name. */ + public name: string; + + /** Operation metadata. */ + public metadata?: (google.protobuf.IAny|null); + + /** Operation done. */ + public done: boolean; + + /** Operation error. */ + public error?: (google.rpc.IStatus|null); + + /** Operation response. */ + public response?: (google.protobuf.IAny|null); + + /** Operation result. */ + public result?: ("error"|"response"); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Operation + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.Operation; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @param message Operation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Operation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Operation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetOperationRequest. */ + interface IGetOperationRequest { + + /** GetOperationRequest name */ + name?: (string|null); + } + + /** Represents a GetOperationRequest. */ + class GetOperationRequest implements IGetOperationRequest { + + /** + * Constructs a new GetOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IGetOperationRequest); + + /** GetOperationRequest name. */ + public name: string; + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @param message GetOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsRequest. */ + interface IListOperationsRequest { + + /** ListOperationsRequest name */ + name?: (string|null); + + /** ListOperationsRequest filter */ + filter?: (string|null); + + /** ListOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListOperationsRequest pageToken */ + pageToken?: (string|null); + + /** ListOperationsRequest returnPartialSuccess */ + returnPartialSuccess?: (boolean|null); + } + + /** Represents a ListOperationsRequest. */ + class ListOperationsRequest implements IListOperationsRequest { + + /** + * Constructs a new ListOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsRequest); + + /** ListOperationsRequest name. */ + public name: string; + + /** ListOperationsRequest filter. */ + public filter: string; + + /** ListOperationsRequest pageSize. */ + public pageSize: number; + + /** ListOperationsRequest pageToken. */ + public pageToken: string; + + /** ListOperationsRequest returnPartialSuccess. */ + public returnPartialSuccess: boolean; + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @param message ListOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsResponse. */ + interface IListOperationsResponse { + + /** ListOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + + /** ListOperationsResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListOperationsResponse. */ + class ListOperationsResponse implements IListOperationsResponse { + + /** + * Constructs a new ListOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsResponse); + + /** ListOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** ListOperationsResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @param message ListOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CancelOperationRequest. */ + interface ICancelOperationRequest { + + /** CancelOperationRequest name */ + name?: (string|null); + } + + /** Represents a CancelOperationRequest. */ + class CancelOperationRequest implements ICancelOperationRequest { + + /** + * Constructs a new CancelOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.ICancelOperationRequest); + + /** CancelOperationRequest name. */ + public name: string; + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CancelOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @param message CancelOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CancelOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteOperationRequest. */ + interface IDeleteOperationRequest { + + /** DeleteOperationRequest name */ + name?: (string|null); + } + + /** Represents a DeleteOperationRequest. */ + class DeleteOperationRequest implements IDeleteOperationRequest { + + /** + * Constructs a new DeleteOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IDeleteOperationRequest); + + /** DeleteOperationRequest name. */ + public name: string; + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @param message DeleteOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WaitOperationRequest. */ + interface IWaitOperationRequest { + + /** WaitOperationRequest name */ + name?: (string|null); + + /** WaitOperationRequest timeout */ + timeout?: (google.protobuf.IDuration|null); + } + + /** Represents a WaitOperationRequest. */ + class WaitOperationRequest implements IWaitOperationRequest { + + /** + * Constructs a new WaitOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IWaitOperationRequest); + + /** WaitOperationRequest name. */ + public name: string; + + /** WaitOperationRequest timeout. */ + public timeout?: (google.protobuf.IDuration|null); + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @param message WaitOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WaitOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an OperationInfo. */ + interface IOperationInfo { + + /** OperationInfo responseType */ + responseType?: (string|null); + + /** OperationInfo metadataType */ + metadataType?: (string|null); + } + + /** Represents an OperationInfo. */ + class OperationInfo implements IOperationInfo { + + /** + * Constructs a new OperationInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperationInfo); + + /** OperationInfo responseType. */ + public responseType: string; + + /** OperationInfo metadataType. */ + public metadataType: string; + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationInfo + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @param message OperationInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } +} diff --git a/handwritten/firestore/types/protos/firestore_v1beta1_proto_api.d.ts b/handwritten/firestore/types/protos/firestore_v1beta1_proto_api.d.ts new file mode 100644 index 00000000000..d92f57608e5 --- /dev/null +++ b/handwritten/firestore/types/protos/firestore_v1beta1_proto_api.d.ts @@ -0,0 +1,9487 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as $protobuf from "protobufjs"; + +/** Namespace google. */ +export namespace google { + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a Timestamp. */ + interface ITimestamp { + + /** Timestamp seconds */ + seconds?: (number|string|null); + + /** Timestamp nanos */ + nanos?: (number|null); + } + + /** Represents a Timestamp. */ + class Timestamp implements ITimestamp { + + /** + * Constructs a new Timestamp. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ITimestamp); + + /** Timestamp seconds. */ + public seconds: (number|string); + + /** Timestamp nanos. */ + public nanos: number; + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Timestamp + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @param message Timestamp + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Timestamp to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Timestamp + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Struct. */ + interface IStruct { + + /** Struct fields */ + fields?: ({ [k: string]: google.protobuf.IValue }|null); + } + + /** Represents a Struct. */ + class Struct implements IStruct { + + /** + * Constructs a new Struct. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStruct); + + /** Struct fields. */ + public fields: { [k: string]: google.protobuf.IValue }; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Struct + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @param message Struct + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Struct to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Struct + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue */ + numberValue?: (number|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value boolValue */ + boolValue?: (boolean|null); + + /** Value structValue */ + structValue?: (google.protobuf.IStruct|null); + + /** Value listValue */ + listValue?: (google.protobuf.IListValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue. */ + public numberValue?: (number|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value boolValue. */ + public boolValue?: (boolean|null); + + /** Value structValue. */ + public structValue?: (google.protobuf.IStruct|null); + + /** Value listValue. */ + public listValue?: (google.protobuf.IListValue|null); + + /** Value kind. */ + public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** NullValue enum. */ + type NullValue = + "NULL_VALUE"; + + /** Properties of a ListValue. */ + interface IListValue { + + /** ListValue values */ + values?: (google.protobuf.IValue[]|null); + } + + /** Represents a ListValue. */ + class ListValue implements IListValue { + + /** + * Constructs a new ListValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IListValue); + + /** ListValue values. */ + public values: google.protobuf.IValue[]; + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @param message ListValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); + + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Edition enum. */ + type Edition = + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; + + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { + + /** FileDescriptorProto name */ + name?: (string|null); + + /** FileDescriptorProto package */ + "package"?: (string|null); + + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); + + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); + + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); + + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); + + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); + + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax */ + syntax?: (string|null); + + /** FileDescriptorProto edition */ + edition?: (google.protobuf.Edition|null); + } + + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { + + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); + + /** FileDescriptorProto name. */ + public name: string; + + /** FileDescriptorProto package. */ + public package: string; + + /** FileDescriptorProto dependency. */ + public dependency: string[]; + + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; + + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; + + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; + + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; + + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax. */ + public syntax: string; + + /** FileDescriptorProto edition. */ + public edition: google.protobuf.Edition; + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { + + /** DescriptorProto name */ + name?: (string|null); + + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { + + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); + + /** DescriptorProto name. */ + public name: string; + + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; + + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + + /** DescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DescriptorProto { + + /** Properties of an ExtensionRange. */ + interface IExtensionRange { + + /** ExtensionRange start */ + start?: (number|null); + + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); + } + + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { + + /** + * Constructs a new ExtensionRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + + /** ExtensionRange start. */ + public start: number; + + /** ExtensionRange end. */ + public end: number; + + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReservedRange. */ + interface IReservedRange { + + /** ReservedRange start */ + start?: (number|null); + + /** ReservedRange end */ + end?: (number|null); + } + + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { + + /** + * Constructs a new ReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + + /** ReservedRange start. */ + public start: number; + + /** ReservedRange end. */ + public end: number; + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ExtensionRangeOptions declaration */ + declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); + + /** ExtensionRangeOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification */ + verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** ExtensionRangeOptions declaration. */ + public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; + + /** ExtensionRangeOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification. */ + public verification: google.protobuf.ExtensionRangeOptions.VerificationState; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExtensionRangeOptions { + + /** Properties of a Declaration. */ + interface IDeclaration { + + /** Declaration number */ + number?: (number|null); + + /** Declaration fullName */ + fullName?: (string|null); + + /** Declaration type */ + type?: (string|null); + + /** Declaration reserved */ + reserved?: (boolean|null); + + /** Declaration repeated */ + repeated?: (boolean|null); + } + + /** Represents a Declaration. */ + class Declaration implements IDeclaration { + + /** + * Constructs a new Declaration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); + + /** Declaration number. */ + public number: number; + + /** Declaration fullName. */ + public fullName: string; + + /** Declaration type. */ + public type: string; + + /** Declaration reserved. */ + public reserved: boolean; + + /** Declaration repeated. */ + public repeated: boolean; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Declaration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @param message Declaration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Declaration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Declaration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** VerificationState enum. */ + type VerificationState = + "DECLARATION"| "UNVERIFIED"; + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; + + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldDescriptorProto { + + /** Type enum. */ + type Type = + "TYPE_DOUBLE"| "TYPE_FLOAT"| "TYPE_INT64"| "TYPE_UINT64"| "TYPE_INT32"| "TYPE_FIXED64"| "TYPE_FIXED32"| "TYPE_BOOL"| "TYPE_STRING"| "TYPE_GROUP"| "TYPE_MESSAGE"| "TYPE_BYTES"| "TYPE_UINT32"| "TYPE_ENUM"| "TYPE_SFIXED32"| "TYPE_SFIXED64"| "TYPE_SINT32"| "TYPE_SINT64"; + + /** Label enum. */ + type Label = + "LABEL_OPTIONAL"| "LABEL_REPEATED"| "LABEL_REQUIRED"; + } + + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { + + /** OneofDescriptorProto name */ + name?: (string|null); + + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } + + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { + + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); + + /** OneofDescriptorProto name. */ + public name: string; + + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { + + /** EnumDescriptorProto name */ + name?: (string|null); + + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { + + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); + + /** EnumDescriptorProto name. */ + public name: string; + + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; + + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { + + /** EnumValueDescriptorProto name */ + name?: (string|null); + + /** EnumValueDescriptorProto number */ + number?: (number|null); + + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } + + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + + /** EnumValueDescriptorProto name. */ + public name: string; + + /** EnumValueDescriptorProto number. */ + public number: number; + + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { + + /** ServiceDescriptorProto name */ + name?: (string|null); + + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); + + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } + + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { + + /** FileOptions javaPackage */ + javaPackage?: (string|null); + + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); + + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); + + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); + + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); + + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + + /** FileOptions goPackage */ + goPackage?: (string|null); + + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); + + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); + + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); + + /** FileOptions deprecated */ + deprecated?: (boolean|null); + + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); + + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); + + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); + + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); + } + + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { + + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); + + /** FileOptions javaPackage. */ + public javaPackage: string; + + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; + + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; + + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; + + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; + + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + + /** FileOptions goPackage. */ + public goPackage: string; + + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; + + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; + + /** FileOptions deprecated. */ + public deprecated: boolean; + + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; + + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; + + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + type OptimizeMode = + "SPEED"| "CODE_SIZE"| "LITE_RUNTIME"; + } + + /** Properties of a MessageOptions. */ + interface IMessageOptions { + + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); + + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); + + /** MessageOptions deprecated */ + deprecated?: (boolean|null); + + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); + + /** MessageOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** MessageOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MessageOptions .google.api.resource */ + ".google.api.resource"?: (google.api.IResourceDescriptor|null); + } + + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { + + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); + + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; + + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; + + /** MessageOptions deprecated. */ + public deprecated: boolean; + + /** MessageOptions mapEntry. */ + public mapEntry: boolean; + + /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** MessageOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MessageOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldOptions. */ + interface IFieldOptions { + + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); + + /** FieldOptions packed */ + packed?: (boolean|null); + + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); + + /** FieldOptions lazy */ + lazy?: (boolean|null); + + /** FieldOptions unverifiedLazy */ + unverifiedLazy?: (boolean|null); + + /** FieldOptions deprecated */ + deprecated?: (boolean|null); + + /** FieldOptions weak */ + weak?: (boolean|null); + + /** FieldOptions debugRedact */ + debugRedact?: (boolean|null); + + /** FieldOptions retention */ + retention?: (google.protobuf.FieldOptions.OptionRetention|null); + + /** FieldOptions targets */ + targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); + + /** FieldOptions editionDefaults */ + editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); + + /** FieldOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FieldOptions .google.api.fieldBehavior */ + ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); + + /** FieldOptions .google.api.resourceReference */ + ".google.api.resourceReference"?: (google.api.IResourceReference|null); + } + + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { + + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); + + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; + + /** FieldOptions packed. */ + public packed: boolean; + + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; + + /** FieldOptions lazy. */ + public lazy: boolean; + + /** FieldOptions unverifiedLazy. */ + public unverifiedLazy: boolean; + + /** FieldOptions deprecated. */ + public deprecated: boolean; + + /** FieldOptions weak. */ + public weak: boolean; + + /** FieldOptions debugRedact. */ + public debugRedact: boolean; + + /** FieldOptions retention. */ + public retention: google.protobuf.FieldOptions.OptionRetention; + + /** FieldOptions targets. */ + public targets: google.protobuf.FieldOptions.OptionTargetType[]; + + /** FieldOptions editionDefaults. */ + public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; + + /** FieldOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldOptions { + + /** CType enum. */ + type CType = + "STRING"| "CORD"| "STRING_PIECE"; + + /** JSType enum. */ + type JSType = + "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; + + /** OptionRetention enum. */ + type OptionRetention = + "RETENTION_UNKNOWN"| "RETENTION_RUNTIME"| "RETENTION_SOURCE"; + + /** OptionTargetType enum. */ + type OptionTargetType = + "TARGET_TYPE_UNKNOWN"| "TARGET_TYPE_FILE"| "TARGET_TYPE_EXTENSION_RANGE"| "TARGET_TYPE_MESSAGE"| "TARGET_TYPE_FIELD"| "TARGET_TYPE_ONEOF"| "TARGET_TYPE_ENUM"| "TARGET_TYPE_ENUM_ENTRY"| "TARGET_TYPE_SERVICE"| "TARGET_TYPE_METHOD"; + + /** Properties of an EditionDefault. */ + interface IEditionDefault { + + /** EditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** EditionDefault value */ + value?: (string|null); + } + + /** Represents an EditionDefault. */ + class EditionDefault implements IEditionDefault { + + /** + * Constructs a new EditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); + + /** EditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** EditionDefault value. */ + public value: string; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @param message EditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an OneofOptions. */ + interface IOneofOptions { + + /** OneofOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { + + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); + + /** OneofOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumOptions. */ + interface IEnumOptions { + + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); + + /** EnumOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** EnumOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { + + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** EnumOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact */ + debugRedact?: (boolean|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { + + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); + + /** EnumValueOptions deprecated. */ + public deprecated: boolean; + + /** EnumValueOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact. */ + public debugRedact: boolean; + + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceOptions. */ + interface IServiceOptions { + + /** ServiceOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); + + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); + + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); + + /** ServiceOptions .google.api.apiVersion */ + ".google.api.apiVersion"?: (string|null); + } + + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { + + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); + + /** ServiceOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated. */ + public deprecated: boolean; + + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodOptions. */ + interface IMethodOptions { + + /** MethodOptions deprecated */ + deprecated?: (boolean|null); + + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); + + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); + + /** MethodOptions .google.api.routing */ + ".google.api.routing"?: (google.api.IRoutingRule|null); + + /** MethodOptions .google.longrunning.operationInfo */ + ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); + } + + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { + + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); + + /** MethodOptions deprecated. */ + public deprecated: boolean; + + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + type IdempotencyLevel = + "IDEMPOTENCY_UNKNOWN"| "NO_SIDE_EFFECTS"| "IDEMPOTENT"; + } + + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { + + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); + + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|string|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|string|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|string); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|string); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UninterpretedOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamePart + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a FeatureSet. */ + interface IFeatureSet { + + /** FeatureSet fieldPresence */ + fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|null); + + /** FeatureSet enumType */ + enumType?: (google.protobuf.FeatureSet.EnumType|null); + + /** FeatureSet repeatedFieldEncoding */ + repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|null); + + /** FeatureSet utf8Validation */ + utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|null); + + /** FeatureSet messageEncoding */ + messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|null); + + /** FeatureSet jsonFormat */ + jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|null); + } + + /** Represents a FeatureSet. */ + class FeatureSet implements IFeatureSet { + + /** + * Constructs a new FeatureSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSet); + + /** FeatureSet fieldPresence. */ + public fieldPresence: google.protobuf.FeatureSet.FieldPresence; + + /** FeatureSet enumType. */ + public enumType: google.protobuf.FeatureSet.EnumType; + + /** FeatureSet repeatedFieldEncoding. */ + public repeatedFieldEncoding: google.protobuf.FeatureSet.RepeatedFieldEncoding; + + /** FeatureSet utf8Validation. */ + public utf8Validation: google.protobuf.FeatureSet.Utf8Validation; + + /** FeatureSet messageEncoding. */ + public messageEncoding: google.protobuf.FeatureSet.MessageEncoding; + + /** FeatureSet jsonFormat. */ + public jsonFormat: google.protobuf.FeatureSet.JsonFormat; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @param message FeatureSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSet { + + /** FieldPresence enum. */ + type FieldPresence = + "FIELD_PRESENCE_UNKNOWN"| "EXPLICIT"| "IMPLICIT"| "LEGACY_REQUIRED"; + + /** EnumType enum. */ + type EnumType = + "ENUM_TYPE_UNKNOWN"| "OPEN"| "CLOSED"; + + /** RepeatedFieldEncoding enum. */ + type RepeatedFieldEncoding = + "REPEATED_FIELD_ENCODING_UNKNOWN"| "PACKED"| "EXPANDED"; + + /** Utf8Validation enum. */ + type Utf8Validation = + "UTF8_VALIDATION_UNKNOWN"| "VERIFY"| "NONE"; + + /** MessageEncoding enum. */ + type MessageEncoding = + "MESSAGE_ENCODING_UNKNOWN"| "LENGTH_PREFIXED"| "DELIMITED"; + + /** JsonFormat enum. */ + type JsonFormat = + "JSON_FORMAT_UNKNOWN"| "ALLOW"| "LEGACY_BEST_EFFORT"; + } + + /** Properties of a FeatureSetDefaults. */ + interface IFeatureSetDefaults { + + /** FeatureSetDefaults defaults */ + defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); + + /** FeatureSetDefaults minimumEdition */ + minimumEdition?: (google.protobuf.Edition|null); + + /** FeatureSetDefaults maximumEdition */ + maximumEdition?: (google.protobuf.Edition|null); + } + + /** Represents a FeatureSetDefaults. */ + class FeatureSetDefaults implements IFeatureSetDefaults { + + /** + * Constructs a new FeatureSetDefaults. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSetDefaults); + + /** FeatureSetDefaults defaults. */ + public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; + + /** FeatureSetDefaults minimumEdition. */ + public minimumEdition: google.protobuf.Edition; + + /** FeatureSetDefaults maximumEdition. */ + public maximumEdition: google.protobuf.Edition; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetDefaults + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @param message FeatureSetDefaults + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetDefaults + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSetDefaults { + + /** Properties of a FeatureSetEditionDefault. */ + interface IFeatureSetEditionDefault { + + /** FeatureSetEditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); + } + + /** Represents a FeatureSetEditionDefault. */ + class FeatureSetEditionDefault implements IFeatureSetEditionDefault { + + /** + * Constructs a new FeatureSetEditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); + + /** FeatureSetEditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetEditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @param message FeatureSetEditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { + + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } + + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { + + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); + + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SourceCodeInfo { + + /** Properties of a Location. */ + interface ILocation { + + /** Location path */ + path?: (number[]|null); + + /** Location span */ + span?: (number[]|null); + + /** Location leadingComments */ + leadingComments?: (string|null); + + /** Location trailingComments */ + trailingComments?: (string|null); + + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + + /** Location path. */ + public path: number[]; + + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Location + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { + + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } + + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { + + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); + + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + + /** Annotation semantic */ + semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); + } + + /** Represents an Annotation. */ + class Annotation implements IAnnotation { + + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); + + /** Annotation path. */ + public path: number[]; + + /** Annotation sourceFile. */ + public sourceFile: string; + + /** Annotation begin. */ + public begin: number; + + /** Annotation end. */ + public end: number; + + /** Annotation semantic. */ + public semantic: google.protobuf.GeneratedCodeInfo.Annotation.Semantic; + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Annotation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Annotation { + + /** Semantic enum. */ + type Semantic = + "NONE"| "SET"| "ALIAS"; + } + } + + /** Properties of a Duration. */ + interface IDuration { + + /** Duration seconds */ + seconds?: (number|string|null); + + /** Duration nanos */ + nanos?: (number|null); + } + + /** Represents a Duration. */ + class Duration implements IDuration { + + /** + * Constructs a new Duration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDuration); + + /** Duration seconds. */ + public seconds: (number|string); + + /** Duration nanos. */ + public nanos: number; + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Duration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Duration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Duration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DoubleValue. */ + interface IDoubleValue { + + /** DoubleValue value */ + value?: (number|null); + } + + /** Represents a DoubleValue. */ + class DoubleValue implements IDoubleValue { + + /** + * Constructs a new DoubleValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDoubleValue); + + /** DoubleValue value. */ + public value: number; + + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DoubleValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; + + /** + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @param message DoubleValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DoubleValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DoubleValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FloatValue. */ + interface IFloatValue { + + /** FloatValue value */ + value?: (number|null); + } + + /** Represents a FloatValue. */ + class FloatValue implements IFloatValue { + + /** + * Constructs a new FloatValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFloatValue); + + /** FloatValue value. */ + public value: number; + + /** + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FloatValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; + + /** + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. + * @param message FloatValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FloatValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FloatValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int64Value. */ + interface IInt64Value { + + /** Int64Value value */ + value?: (number|string|null); + } + + /** Represents an Int64Value. */ + class Int64Value implements IInt64Value { + + /** + * Constructs a new Int64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt64Value); + + /** Int64Value value. */ + public value: (number|string); + + /** + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; + + /** + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. + * @param message Int64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt64Value. */ + interface IUInt64Value { + + /** UInt64Value value */ + value?: (number|string|null); + } + + /** Represents a UInt64Value. */ + class UInt64Value implements IUInt64Value { + + /** + * Constructs a new UInt64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt64Value); + + /** UInt64Value value. */ + public value: (number|string); + + /** + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; + + /** + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. + * @param message UInt64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int32Value. */ + interface IInt32Value { + + /** Int32Value value */ + value?: (number|null); + } + + /** Represents an Int32Value. */ + class Int32Value implements IInt32Value { + + /** + * Constructs a new Int32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt32Value); + + /** Int32Value value. */ + public value: number; + + /** + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; + + /** + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. + * @param message Int32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt32Value. */ + interface IUInt32Value { + + /** UInt32Value value */ + value?: (number|null); + } + + /** Represents a UInt32Value. */ + class UInt32Value implements IUInt32Value { + + /** + * Constructs a new UInt32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt32Value); + + /** UInt32Value value. */ + public value: number; + + /** + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; + + /** + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. + * @param message UInt32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BoolValue. */ + interface IBoolValue { + + /** BoolValue value */ + value?: (boolean|null); + } + + /** Represents a BoolValue. */ + class BoolValue implements IBoolValue { + + /** + * Constructs a new BoolValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBoolValue); + + /** BoolValue value. */ + public value: boolean; + + /** + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BoolValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; + + /** + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. + * @param message BoolValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BoolValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BoolValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StringValue. */ + interface IStringValue { + + /** StringValue value */ + value?: (string|null); + } + + /** Represents a StringValue. */ + class StringValue implements IStringValue { + + /** + * Constructs a new StringValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStringValue); + + /** StringValue value. */ + public value: string; + + /** + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StringValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; + + /** + * Creates a plain object from a StringValue message. Also converts values to other types if specified. + * @param message StringValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StringValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StringValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BytesValue. */ + interface IBytesValue { + + /** BytesValue value */ + value?: (Uint8Array|null); + } + + /** Represents a BytesValue. */ + class BytesValue implements IBytesValue { + + /** + * Constructs a new BytesValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBytesValue); + + /** BytesValue value. */ + public value: Uint8Array; + + /** + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BytesValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; + + /** + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. + * @param message BytesValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BytesValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BytesValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Empty. */ + interface IEmpty { + } + + /** Represents an Empty. */ + class Empty implements IEmpty { + + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Empty + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Any. */ + interface IAny { + + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|null); + } + + /** Represents an Any. */ + class Any implements IAny { + + /** + * Constructs a new Any. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IAny); + + /** Any type_url. */ + public type_url: string; + + /** Any value. */ + public value: Uint8Array; + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Any + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Any to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Any + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldMask. */ + interface IFieldMask { + + /** FieldMask paths */ + paths?: (string[]|null); + } + + /** Represents a FieldMask. */ + class FieldMask implements IFieldMask { + + /** + * Constructs a new FieldMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldMask); + + /** FieldMask paths. */ + public paths: string[]; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldMask + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @param message FieldMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace firestore. */ + namespace firestore { + + /** Namespace v1beta1. */ + namespace v1beta1 { + + /** Properties of a DocumentMask. */ + interface IDocumentMask { + + /** DocumentMask fieldPaths */ + fieldPaths?: (string[]|null); + } + + /** Represents a DocumentMask. */ + class DocumentMask implements IDocumentMask { + + /** + * Constructs a new DocumentMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentMask); + + /** DocumentMask fieldPaths. */ + public fieldPaths: string[]; + + /** + * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentMask + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentMask; + + /** + * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. + * @param message DocumentMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Precondition. */ + interface IPrecondition { + + /** Precondition exists */ + exists?: (boolean|null); + + /** Precondition updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a Precondition. */ + class Precondition implements IPrecondition { + + /** + * Constructs a new Precondition. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IPrecondition); + + /** Precondition exists. */ + public exists?: (boolean|null); + + /** Precondition updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** Precondition conditionType. */ + public conditionType?: ("exists"|"updateTime"); + + /** + * Creates a Precondition message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Precondition + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Precondition; + + /** + * Creates a plain object from a Precondition message. Also converts values to other types if specified. + * @param message Precondition + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Precondition, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Precondition to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Precondition + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TransactionOptions. */ + interface ITransactionOptions { + + /** TransactionOptions readOnly */ + readOnly?: (google.firestore.v1beta1.TransactionOptions.IReadOnly|null); + + /** TransactionOptions readWrite */ + readWrite?: (google.firestore.v1beta1.TransactionOptions.IReadWrite|null); + } + + /** Represents a TransactionOptions. */ + class TransactionOptions implements ITransactionOptions { + + /** + * Constructs a new TransactionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ITransactionOptions); + + /** TransactionOptions readOnly. */ + public readOnly?: (google.firestore.v1beta1.TransactionOptions.IReadOnly|null); + + /** TransactionOptions readWrite. */ + public readWrite?: (google.firestore.v1beta1.TransactionOptions.IReadWrite|null); + + /** TransactionOptions mode. */ + public mode?: ("readOnly"|"readWrite"); + + /** + * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TransactionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TransactionOptions; + + /** + * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. + * @param message TransactionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.TransactionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TransactionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TransactionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TransactionOptions { + + /** Properties of a ReadWrite. */ + interface IReadWrite { + + /** ReadWrite retryTransaction */ + retryTransaction?: (Uint8Array|null); + } + + /** Represents a ReadWrite. */ + class ReadWrite implements IReadWrite { + + /** + * Constructs a new ReadWrite. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.TransactionOptions.IReadWrite); + + /** ReadWrite retryTransaction. */ + public retryTransaction: Uint8Array; + + /** + * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadWrite + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TransactionOptions.ReadWrite; + + /** + * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. + * @param message ReadWrite + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.TransactionOptions.ReadWrite, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadWrite to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadWrite + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReadOnly. */ + interface IReadOnly { + + /** ReadOnly readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a ReadOnly. */ + class ReadOnly implements IReadOnly { + + /** + * Constructs a new ReadOnly. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.TransactionOptions.IReadOnly); + + /** ReadOnly readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ReadOnly consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadOnly + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TransactionOptions.ReadOnly; + + /** + * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. + * @param message ReadOnly + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.TransactionOptions.ReadOnly, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadOnly to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadOnly + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a Document. */ + interface IDocument { + + /** Document name */ + name?: (string|null); + + /** Document fields */ + fields?: ({ [k: string]: google.firestore.v1beta1.IValue }|null); + + /** Document createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** Document updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a Document. */ + class Document implements IDocument { + + /** + * Constructs a new Document. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocument); + + /** Document name. */ + public name: string; + + /** Document fields. */ + public fields: { [k: string]: google.firestore.v1beta1.IValue }; + + /** Document createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** Document updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a Document message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Document + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Document; + + /** + * Creates a plain object from a Document message. Also converts values to other types if specified. + * @param message Document + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Document, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Document to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Document + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value booleanValue */ + booleanValue?: (boolean|null); + + /** Value integerValue */ + integerValue?: (number|string|null); + + /** Value doubleValue */ + doubleValue?: (number|null); + + /** Value timestampValue */ + timestampValue?: (google.protobuf.ITimestamp|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value bytesValue */ + bytesValue?: (Uint8Array|null); + + /** Value referenceValue */ + referenceValue?: (string|null); + + /** Value geoPointValue */ + geoPointValue?: (google.type.ILatLng|null); + + /** Value arrayValue */ + arrayValue?: (google.firestore.v1beta1.IArrayValue|null); + + /** Value mapValue */ + mapValue?: (google.firestore.v1beta1.IMapValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value booleanValue. */ + public booleanValue?: (boolean|null); + + /** Value integerValue. */ + public integerValue?: (number|string|null); + + /** Value doubleValue. */ + public doubleValue?: (number|null); + + /** Value timestampValue. */ + public timestampValue?: (google.protobuf.ITimestamp|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value bytesValue. */ + public bytesValue?: (Uint8Array|null); + + /** Value referenceValue. */ + public referenceValue?: (string|null); + + /** Value geoPointValue. */ + public geoPointValue?: (google.type.ILatLng|null); + + /** Value arrayValue. */ + public arrayValue?: (google.firestore.v1beta1.IArrayValue|null); + + /** Value mapValue. */ + public mapValue?: (google.firestore.v1beta1.IMapValue|null); + + /** Value valueType. */ + public valueType?: ("nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ArrayValue. */ + interface IArrayValue { + + /** ArrayValue values */ + values?: (google.firestore.v1beta1.IValue[]|null); + } + + /** Represents an ArrayValue. */ + class ArrayValue implements IArrayValue { + + /** + * Constructs a new ArrayValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IArrayValue); + + /** ArrayValue values. */ + public values: google.firestore.v1beta1.IValue[]; + + /** + * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ArrayValue + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ArrayValue; + + /** + * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. + * @param message ArrayValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ArrayValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ArrayValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ArrayValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MapValue. */ + interface IMapValue { + + /** MapValue fields */ + fields?: ({ [k: string]: google.firestore.v1beta1.IValue }|null); + } + + /** Represents a MapValue. */ + class MapValue implements IMapValue { + + /** + * Constructs a new MapValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IMapValue); + + /** MapValue fields. */ + public fields: { [k: string]: google.firestore.v1beta1.IValue }; + + /** + * Creates a MapValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MapValue + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.MapValue; + + /** + * Creates a plain object from a MapValue message. Also converts values to other types if specified. + * @param message MapValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.MapValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MapValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MapValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Represents a Firestore */ + class Firestore extends $protobuf.rpc.Service { + + /** + * Constructs a new Firestore service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls GetDocument. + * @param request GetDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public getDocument(request: google.firestore.v1beta1.IGetDocumentRequest, callback: google.firestore.v1beta1.Firestore.GetDocumentCallback): void; + + /** + * Calls GetDocument. + * @param request GetDocumentRequest message or plain object + * @returns Promise + */ + public getDocument(request: google.firestore.v1beta1.IGetDocumentRequest): Promise; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDocumentsResponse + */ + public listDocuments(request: google.firestore.v1beta1.IListDocumentsRequest, callback: google.firestore.v1beta1.Firestore.ListDocumentsCallback): void; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @returns Promise + */ + public listDocuments(request: google.firestore.v1beta1.IListDocumentsRequest): Promise; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public updateDocument(request: google.firestore.v1beta1.IUpdateDocumentRequest, callback: google.firestore.v1beta1.Firestore.UpdateDocumentCallback): void; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @returns Promise + */ + public updateDocument(request: google.firestore.v1beta1.IUpdateDocumentRequest): Promise; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteDocument(request: google.firestore.v1beta1.IDeleteDocumentRequest, callback: google.firestore.v1beta1.Firestore.DeleteDocumentCallback): void; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @returns Promise + */ + public deleteDocument(request: google.firestore.v1beta1.IDeleteDocumentRequest): Promise; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse + */ + public batchGetDocuments(request: google.firestore.v1beta1.IBatchGetDocumentsRequest, callback: google.firestore.v1beta1.Firestore.BatchGetDocumentsCallback): void; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @returns Promise + */ + public batchGetDocuments(request: google.firestore.v1beta1.IBatchGetDocumentsRequest): Promise; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BeginTransactionResponse + */ + public beginTransaction(request: google.firestore.v1beta1.IBeginTransactionRequest, callback: google.firestore.v1beta1.Firestore.BeginTransactionCallback): void; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @returns Promise + */ + public beginTransaction(request: google.firestore.v1beta1.IBeginTransactionRequest): Promise; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @param callback Node-style callback called with the error, if any, and CommitResponse + */ + public commit(request: google.firestore.v1beta1.ICommitRequest, callback: google.firestore.v1beta1.Firestore.CommitCallback): void; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @returns Promise + */ + public commit(request: google.firestore.v1beta1.ICommitRequest): Promise; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public rollback(request: google.firestore.v1beta1.IRollbackRequest, callback: google.firestore.v1beta1.Firestore.RollbackCallback): void; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @returns Promise + */ + public rollback(request: google.firestore.v1beta1.IRollbackRequest): Promise; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RunQueryResponse + */ + public runQuery(request: google.firestore.v1beta1.IRunQueryRequest, callback: google.firestore.v1beta1.Firestore.RunQueryCallback): void; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @returns Promise + */ + public runQuery(request: google.firestore.v1beta1.IRunQueryRequest): Promise; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and PartitionQueryResponse + */ + public partitionQuery(request: google.firestore.v1beta1.IPartitionQueryRequest, callback: google.firestore.v1beta1.Firestore.PartitionQueryCallback): void; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @returns Promise + */ + public partitionQuery(request: google.firestore.v1beta1.IPartitionQueryRequest): Promise; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and WriteResponse + */ + public write(request: google.firestore.v1beta1.IWriteRequest, callback: google.firestore.v1beta1.Firestore.WriteCallback): void; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @returns Promise + */ + public write(request: google.firestore.v1beta1.IWriteRequest): Promise; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListenResponse + */ + public listen(request: google.firestore.v1beta1.IListenRequest, callback: google.firestore.v1beta1.Firestore.ListenCallback): void; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @returns Promise + */ + public listen(request: google.firestore.v1beta1.IListenRequest): Promise; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListCollectionIdsResponse + */ + public listCollectionIds(request: google.firestore.v1beta1.IListCollectionIdsRequest, callback: google.firestore.v1beta1.Firestore.ListCollectionIdsCallback): void; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @returns Promise + */ + public listCollectionIds(request: google.firestore.v1beta1.IListCollectionIdsRequest): Promise; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchWriteResponse + */ + public batchWrite(request: google.firestore.v1beta1.IBatchWriteRequest, callback: google.firestore.v1beta1.Firestore.BatchWriteCallback): void; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @returns Promise + */ + public batchWrite(request: google.firestore.v1beta1.IBatchWriteRequest): Promise; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public createDocument(request: google.firestore.v1beta1.ICreateDocumentRequest, callback: google.firestore.v1beta1.Firestore.CreateDocumentCallback): void; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @returns Promise + */ + public createDocument(request: google.firestore.v1beta1.ICreateDocumentRequest): Promise; + } + + namespace Firestore { + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#getDocument}. + * @param error Error, if any + * @param [response] Document + */ + type GetDocumentCallback = (error: (Error|null), response?: google.firestore.v1beta1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#listDocuments}. + * @param error Error, if any + * @param [response] ListDocumentsResponse + */ + type ListDocumentsCallback = (error: (Error|null), response?: google.firestore.v1beta1.ListDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#updateDocument}. + * @param error Error, if any + * @param [response] Document + */ + type UpdateDocumentCallback = (error: (Error|null), response?: google.firestore.v1beta1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#deleteDocument}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteDocumentCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#batchGetDocuments}. + * @param error Error, if any + * @param [response] BatchGetDocumentsResponse + */ + type BatchGetDocumentsCallback = (error: (Error|null), response?: google.firestore.v1beta1.BatchGetDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#beginTransaction}. + * @param error Error, if any + * @param [response] BeginTransactionResponse + */ + type BeginTransactionCallback = (error: (Error|null), response?: google.firestore.v1beta1.BeginTransactionResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#commit}. + * @param error Error, if any + * @param [response] CommitResponse + */ + type CommitCallback = (error: (Error|null), response?: google.firestore.v1beta1.CommitResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#rollback}. + * @param error Error, if any + * @param [response] Empty + */ + type RollbackCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#runQuery}. + * @param error Error, if any + * @param [response] RunQueryResponse + */ + type RunQueryCallback = (error: (Error|null), response?: google.firestore.v1beta1.RunQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#partitionQuery}. + * @param error Error, if any + * @param [response] PartitionQueryResponse + */ + type PartitionQueryCallback = (error: (Error|null), response?: google.firestore.v1beta1.PartitionQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#write}. + * @param error Error, if any + * @param [response] WriteResponse + */ + type WriteCallback = (error: (Error|null), response?: google.firestore.v1beta1.WriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#listen}. + * @param error Error, if any + * @param [response] ListenResponse + */ + type ListenCallback = (error: (Error|null), response?: google.firestore.v1beta1.ListenResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#listCollectionIds}. + * @param error Error, if any + * @param [response] ListCollectionIdsResponse + */ + type ListCollectionIdsCallback = (error: (Error|null), response?: google.firestore.v1beta1.ListCollectionIdsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#batchWrite}. + * @param error Error, if any + * @param [response] BatchWriteResponse + */ + type BatchWriteCallback = (error: (Error|null), response?: google.firestore.v1beta1.BatchWriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#createDocument}. + * @param error Error, if any + * @param [response] Document + */ + type CreateDocumentCallback = (error: (Error|null), response?: google.firestore.v1beta1.Document) => void; + } + + /** Properties of a GetDocumentRequest. */ + interface IGetDocumentRequest { + + /** GetDocumentRequest name */ + name?: (string|null); + + /** GetDocumentRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** GetDocumentRequest transaction */ + transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a GetDocumentRequest. */ + class GetDocumentRequest implements IGetDocumentRequest { + + /** + * Constructs a new GetDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IGetDocumentRequest); + + /** GetDocumentRequest name. */ + public name: string; + + /** GetDocumentRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** GetDocumentRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** GetDocumentRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.GetDocumentRequest; + + /** + * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. + * @param message GetDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.GetDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsRequest. */ + interface IListDocumentsRequest { + + /** ListDocumentsRequest parent */ + parent?: (string|null); + + /** ListDocumentsRequest collectionId */ + collectionId?: (string|null); + + /** ListDocumentsRequest pageSize */ + pageSize?: (number|null); + + /** ListDocumentsRequest pageToken */ + pageToken?: (string|null); + + /** ListDocumentsRequest orderBy */ + orderBy?: (string|null); + + /** ListDocumentsRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** ListDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing */ + showMissing?: (boolean|null); + } + + /** Represents a ListDocumentsRequest. */ + class ListDocumentsRequest implements IListDocumentsRequest { + + /** + * Constructs a new ListDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListDocumentsRequest); + + /** ListDocumentsRequest parent. */ + public parent: string; + + /** ListDocumentsRequest collectionId. */ + public collectionId: string; + + /** ListDocumentsRequest pageSize. */ + public pageSize: number; + + /** ListDocumentsRequest pageToken. */ + public pageToken: string; + + /** ListDocumentsRequest orderBy. */ + public orderBy: string; + + /** ListDocumentsRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** ListDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing. */ + public showMissing: boolean; + + /** ListDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListDocumentsRequest; + + /** + * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. + * @param message ListDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsResponse. */ + interface IListDocumentsResponse { + + /** ListDocumentsResponse documents */ + documents?: (google.firestore.v1beta1.IDocument[]|null); + + /** ListDocumentsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListDocumentsResponse. */ + class ListDocumentsResponse implements IListDocumentsResponse { + + /** + * Constructs a new ListDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListDocumentsResponse); + + /** ListDocumentsResponse documents. */ + public documents: google.firestore.v1beta1.IDocument[]; + + /** ListDocumentsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListDocumentsResponse; + + /** + * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. + * @param message ListDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDocumentRequest. */ + interface ICreateDocumentRequest { + + /** CreateDocumentRequest parent */ + parent?: (string|null); + + /** CreateDocumentRequest collectionId */ + collectionId?: (string|null); + + /** CreateDocumentRequest documentId */ + documentId?: (string|null); + + /** CreateDocumentRequest document */ + document?: (google.firestore.v1beta1.IDocument|null); + + /** CreateDocumentRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + } + + /** Represents a CreateDocumentRequest. */ + class CreateDocumentRequest implements ICreateDocumentRequest { + + /** + * Constructs a new CreateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ICreateDocumentRequest); + + /** CreateDocumentRequest parent. */ + public parent: string; + + /** CreateDocumentRequest collectionId. */ + public collectionId: string; + + /** CreateDocumentRequest documentId. */ + public documentId: string; + + /** CreateDocumentRequest document. */ + public document?: (google.firestore.v1beta1.IDocument|null); + + /** CreateDocumentRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** + * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.CreateDocumentRequest; + + /** + * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. + * @param message CreateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.CreateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDocumentRequest. */ + interface IUpdateDocumentRequest { + + /** UpdateDocumentRequest document */ + document?: (google.firestore.v1beta1.IDocument|null); + + /** UpdateDocumentRequest updateMask */ + updateMask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** UpdateDocumentRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + } + + /** Represents an UpdateDocumentRequest. */ + class UpdateDocumentRequest implements IUpdateDocumentRequest { + + /** + * Constructs a new UpdateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IUpdateDocumentRequest); + + /** UpdateDocumentRequest document. */ + public document?: (google.firestore.v1beta1.IDocument|null); + + /** UpdateDocumentRequest updateMask. */ + public updateMask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** UpdateDocumentRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + + /** + * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.UpdateDocumentRequest; + + /** + * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. + * @param message UpdateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.UpdateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDocumentRequest. */ + interface IDeleteDocumentRequest { + + /** DeleteDocumentRequest name */ + name?: (string|null); + + /** DeleteDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + } + + /** Represents a DeleteDocumentRequest. */ + class DeleteDocumentRequest implements IDeleteDocumentRequest { + + /** + * Constructs a new DeleteDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDeleteDocumentRequest); + + /** DeleteDocumentRequest name. */ + public name: string; + + /** DeleteDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + + /** + * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DeleteDocumentRequest; + + /** + * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. + * @param message DeleteDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DeleteDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsRequest. */ + interface IBatchGetDocumentsRequest { + + /** BatchGetDocumentsRequest database */ + database?: (string|null); + + /** BatchGetDocumentsRequest documents */ + documents?: (string[]|null); + + /** BatchGetDocumentsRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction */ + newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsRequest. */ + class BatchGetDocumentsRequest implements IBatchGetDocumentsRequest { + + /** + * Constructs a new BatchGetDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBatchGetDocumentsRequest); + + /** BatchGetDocumentsRequest database. */ + public database: string; + + /** BatchGetDocumentsRequest documents. */ + public documents: string[]; + + /** BatchGetDocumentsRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction. */ + public newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchGetDocumentsRequest; + + /** + * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. + * @param message BatchGetDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BatchGetDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsResponse. */ + interface IBatchGetDocumentsResponse { + + /** BatchGetDocumentsResponse found */ + found?: (google.firestore.v1beta1.IDocument|null); + + /** BatchGetDocumentsResponse missing */ + missing?: (string|null); + + /** BatchGetDocumentsResponse transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsResponse. */ + class BatchGetDocumentsResponse implements IBatchGetDocumentsResponse { + + /** + * Constructs a new BatchGetDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBatchGetDocumentsResponse); + + /** BatchGetDocumentsResponse found. */ + public found?: (google.firestore.v1beta1.IDocument|null); + + /** BatchGetDocumentsResponse missing. */ + public missing?: (string|null); + + /** BatchGetDocumentsResponse transaction. */ + public transaction: Uint8Array; + + /** BatchGetDocumentsResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsResponse result. */ + public result?: ("found"|"missing"); + + /** + * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchGetDocumentsResponse; + + /** + * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. + * @param message BatchGetDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BatchGetDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionRequest. */ + interface IBeginTransactionRequest { + + /** BeginTransactionRequest database */ + database?: (string|null); + + /** BeginTransactionRequest options */ + options?: (google.firestore.v1beta1.ITransactionOptions|null); + } + + /** Represents a BeginTransactionRequest. */ + class BeginTransactionRequest implements IBeginTransactionRequest { + + /** + * Constructs a new BeginTransactionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBeginTransactionRequest); + + /** BeginTransactionRequest database. */ + public database: string; + + /** BeginTransactionRequest options. */ + public options?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** + * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BeginTransactionRequest; + + /** + * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. + * @param message BeginTransactionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BeginTransactionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionResponse. */ + interface IBeginTransactionResponse { + + /** BeginTransactionResponse transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a BeginTransactionResponse. */ + class BeginTransactionResponse implements IBeginTransactionResponse { + + /** + * Constructs a new BeginTransactionResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBeginTransactionResponse); + + /** BeginTransactionResponse transaction. */ + public transaction: Uint8Array; + + /** + * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BeginTransactionResponse; + + /** + * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. + * @param message BeginTransactionResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BeginTransactionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitRequest. */ + interface ICommitRequest { + + /** CommitRequest database */ + database?: (string|null); + + /** CommitRequest writes */ + writes?: (google.firestore.v1beta1.IWrite[]|null); + + /** CommitRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a CommitRequest. */ + class CommitRequest implements ICommitRequest { + + /** + * Constructs a new CommitRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ICommitRequest); + + /** CommitRequest database. */ + public database: string; + + /** CommitRequest writes. */ + public writes: google.firestore.v1beta1.IWrite[]; + + /** CommitRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.CommitRequest; + + /** + * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. + * @param message CommitRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.CommitRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitResponse. */ + interface ICommitResponse { + + /** CommitResponse writeResults */ + writeResults?: (google.firestore.v1beta1.IWriteResult[]|null); + + /** CommitResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a CommitResponse. */ + class CommitResponse implements ICommitResponse { + + /** + * Constructs a new CommitResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ICommitResponse); + + /** CommitResponse writeResults. */ + public writeResults: google.firestore.v1beta1.IWriteResult[]; + + /** CommitResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.CommitResponse; + + /** + * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. + * @param message CommitResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.CommitResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RollbackRequest. */ + interface IRollbackRequest { + + /** RollbackRequest database */ + database?: (string|null); + + /** RollbackRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a RollbackRequest. */ + class RollbackRequest implements IRollbackRequest { + + /** + * Constructs a new RollbackRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IRollbackRequest); + + /** RollbackRequest database. */ + public database: string; + + /** RollbackRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RollbackRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.RollbackRequest; + + /** + * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. + * @param message RollbackRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.RollbackRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RollbackRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RollbackRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryRequest. */ + interface IRunQueryRequest { + + /** RunQueryRequest parent */ + parent?: (string|null); + + /** RunQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** RunQueryRequest transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction */ + newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** RunQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a RunQueryRequest. */ + class RunQueryRequest implements IRunQueryRequest { + + /** + * Constructs a new RunQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IRunQueryRequest); + + /** RunQueryRequest parent. */ + public parent: string; + + /** RunQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** RunQueryRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction. */ + public newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** RunQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** RunQueryRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.RunQueryRequest; + + /** + * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. + * @param message RunQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.RunQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryResponse. */ + interface IRunQueryResponse { + + /** RunQueryResponse transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryResponse document */ + document?: (google.firestore.v1beta1.IDocument|null); + + /** RunQueryResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults */ + skippedResults?: (number|null); + } + + /** Represents a RunQueryResponse. */ + class RunQueryResponse implements IRunQueryResponse { + + /** + * Constructs a new RunQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IRunQueryResponse); + + /** RunQueryResponse transaction. */ + public transaction: Uint8Array; + + /** RunQueryResponse document. */ + public document?: (google.firestore.v1beta1.IDocument|null); + + /** RunQueryResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults. */ + public skippedResults: number; + + /** + * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.RunQueryResponse; + + /** + * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. + * @param message RunQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.RunQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryRequest. */ + interface IPartitionQueryRequest { + + /** PartitionQueryRequest parent */ + parent?: (string|null); + + /** PartitionQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount */ + partitionCount?: (number|string|null); + + /** PartitionQueryRequest pageToken */ + pageToken?: (string|null); + + /** PartitionQueryRequest pageSize */ + pageSize?: (number|null); + } + + /** Represents a PartitionQueryRequest. */ + class PartitionQueryRequest implements IPartitionQueryRequest { + + /** + * Constructs a new PartitionQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IPartitionQueryRequest); + + /** PartitionQueryRequest parent. */ + public parent: string; + + /** PartitionQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount. */ + public partitionCount: (number|string); + + /** PartitionQueryRequest pageToken. */ + public pageToken: string; + + /** PartitionQueryRequest pageSize. */ + public pageSize: number; + + /** PartitionQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.PartitionQueryRequest; + + /** + * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. + * @param message PartitionQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.PartitionQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryResponse. */ + interface IPartitionQueryResponse { + + /** PartitionQueryResponse partitions */ + partitions?: (google.firestore.v1beta1.ICursor[]|null); + + /** PartitionQueryResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a PartitionQueryResponse. */ + class PartitionQueryResponse implements IPartitionQueryResponse { + + /** + * Constructs a new PartitionQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IPartitionQueryResponse); + + /** PartitionQueryResponse partitions. */ + public partitions: google.firestore.v1beta1.ICursor[]; + + /** PartitionQueryResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.PartitionQueryResponse; + + /** + * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. + * @param message PartitionQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.PartitionQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteRequest. */ + interface IWriteRequest { + + /** WriteRequest database */ + database?: (string|null); + + /** WriteRequest streamId */ + streamId?: (string|null); + + /** WriteRequest writes */ + writes?: (google.firestore.v1beta1.IWrite[]|null); + + /** WriteRequest streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a WriteRequest. */ + class WriteRequest implements IWriteRequest { + + /** + * Constructs a new WriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IWriteRequest); + + /** WriteRequest database. */ + public database: string; + + /** WriteRequest streamId. */ + public streamId: string; + + /** WriteRequest writes. */ + public writes: google.firestore.v1beta1.IWrite[]; + + /** WriteRequest streamToken. */ + public streamToken: Uint8Array; + + /** WriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.WriteRequest; + + /** + * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. + * @param message WriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.WriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteResponse. */ + interface IWriteResponse { + + /** WriteResponse streamId */ + streamId?: (string|null); + + /** WriteResponse streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteResponse writeResults */ + writeResults?: (google.firestore.v1beta1.IWriteResult[]|null); + + /** WriteResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a WriteResponse. */ + class WriteResponse implements IWriteResponse { + + /** + * Constructs a new WriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IWriteResponse); + + /** WriteResponse streamId. */ + public streamId: string; + + /** WriteResponse streamToken. */ + public streamToken: Uint8Array; + + /** WriteResponse writeResults. */ + public writeResults: google.firestore.v1beta1.IWriteResult[]; + + /** WriteResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.WriteResponse; + + /** + * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. + * @param message WriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.WriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenRequest. */ + interface IListenRequest { + + /** ListenRequest database */ + database?: (string|null); + + /** ListenRequest addTarget */ + addTarget?: (google.firestore.v1beta1.ITarget|null); + + /** ListenRequest removeTarget */ + removeTarget?: (number|null); + + /** ListenRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a ListenRequest. */ + class ListenRequest implements IListenRequest { + + /** + * Constructs a new ListenRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListenRequest); + + /** ListenRequest database. */ + public database: string; + + /** ListenRequest addTarget. */ + public addTarget?: (google.firestore.v1beta1.ITarget|null); + + /** ListenRequest removeTarget. */ + public removeTarget?: (number|null); + + /** ListenRequest labels. */ + public labels: { [k: string]: string }; + + /** ListenRequest targetChange. */ + public targetChange?: ("addTarget"|"removeTarget"); + + /** + * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListenRequest; + + /** + * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. + * @param message ListenRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListenRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenResponse. */ + interface IListenResponse { + + /** ListenResponse targetChange */ + targetChange?: (google.firestore.v1beta1.ITargetChange|null); + + /** ListenResponse documentChange */ + documentChange?: (google.firestore.v1beta1.IDocumentChange|null); + + /** ListenResponse documentDelete */ + documentDelete?: (google.firestore.v1beta1.IDocumentDelete|null); + + /** ListenResponse documentRemove */ + documentRemove?: (google.firestore.v1beta1.IDocumentRemove|null); + + /** ListenResponse filter */ + filter?: (google.firestore.v1beta1.IExistenceFilter|null); + } + + /** Represents a ListenResponse. */ + class ListenResponse implements IListenResponse { + + /** + * Constructs a new ListenResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListenResponse); + + /** ListenResponse targetChange. */ + public targetChange?: (google.firestore.v1beta1.ITargetChange|null); + + /** ListenResponse documentChange. */ + public documentChange?: (google.firestore.v1beta1.IDocumentChange|null); + + /** ListenResponse documentDelete. */ + public documentDelete?: (google.firestore.v1beta1.IDocumentDelete|null); + + /** ListenResponse documentRemove. */ + public documentRemove?: (google.firestore.v1beta1.IDocumentRemove|null); + + /** ListenResponse filter. */ + public filter?: (google.firestore.v1beta1.IExistenceFilter|null); + + /** ListenResponse responseType. */ + public responseType?: ("targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"); + + /** + * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListenResponse; + + /** + * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. + * @param message ListenResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListenResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Target. */ + interface ITarget { + + /** Target query */ + query?: (google.firestore.v1beta1.Target.IQueryTarget|null); + + /** Target documents */ + documents?: (google.firestore.v1beta1.Target.IDocumentsTarget|null); + + /** Target resumeToken */ + resumeToken?: (Uint8Array|null); + + /** Target readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId */ + targetId?: (number|null); + + /** Target once */ + once?: (boolean|null); + } + + /** Represents a Target. */ + class Target implements ITarget { + + /** + * Constructs a new Target. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ITarget); + + /** Target query. */ + public query?: (google.firestore.v1beta1.Target.IQueryTarget|null); + + /** Target documents. */ + public documents?: (google.firestore.v1beta1.Target.IDocumentsTarget|null); + + /** Target resumeToken. */ + public resumeToken?: (Uint8Array|null); + + /** Target readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId. */ + public targetId: number; + + /** Target once. */ + public once: boolean; + + /** Target targetType. */ + public targetType?: ("query"|"documents"); + + /** Target resumeType. */ + public resumeType?: ("resumeToken"|"readTime"); + + /** + * Creates a Target message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Target + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Target; + + /** + * Creates a plain object from a Target message. Also converts values to other types if specified. + * @param message Target + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Target, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Target to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Target + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Target { + + /** Properties of a DocumentsTarget. */ + interface IDocumentsTarget { + + /** DocumentsTarget documents */ + documents?: (string[]|null); + } + + /** Represents a DocumentsTarget. */ + class DocumentsTarget implements IDocumentsTarget { + + /** + * Constructs a new DocumentsTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.Target.IDocumentsTarget); + + /** DocumentsTarget documents. */ + public documents: string[]; + + /** + * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentsTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Target.DocumentsTarget; + + /** + * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. + * @param message DocumentsTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Target.DocumentsTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentsTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentsTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a QueryTarget. */ + interface IQueryTarget { + + /** QueryTarget parent */ + parent?: (string|null); + + /** QueryTarget structuredQuery */ + structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + } + + /** Represents a QueryTarget. */ + class QueryTarget implements IQueryTarget { + + /** + * Constructs a new QueryTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.Target.IQueryTarget); + + /** QueryTarget parent. */ + public parent: string; + + /** QueryTarget structuredQuery. */ + public structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** QueryTarget queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QueryTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Target.QueryTarget; + + /** + * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. + * @param message QueryTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Target.QueryTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this QueryTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QueryTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a TargetChange. */ + interface ITargetChange { + + /** TargetChange targetChangeType */ + targetChangeType?: (google.firestore.v1beta1.TargetChange.TargetChangeType|null); + + /** TargetChange targetIds */ + targetIds?: (number[]|null); + + /** TargetChange cause */ + cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken */ + resumeToken?: (Uint8Array|null); + + /** TargetChange readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a TargetChange. */ + class TargetChange implements ITargetChange { + + /** + * Constructs a new TargetChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ITargetChange); + + /** TargetChange targetChangeType. */ + public targetChangeType: google.firestore.v1beta1.TargetChange.TargetChangeType; + + /** TargetChange targetIds. */ + public targetIds: number[]; + + /** TargetChange cause. */ + public cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken. */ + public resumeToken: Uint8Array; + + /** TargetChange readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TargetChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TargetChange; + + /** + * Creates a plain object from a TargetChange message. Also converts values to other types if specified. + * @param message TargetChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.TargetChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TargetChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TargetChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TargetChange { + + /** TargetChangeType enum. */ + type TargetChangeType = + "NO_CHANGE"| "ADD"| "REMOVE"| "CURRENT"| "RESET"; + } + + /** Properties of a ListCollectionIdsRequest. */ + interface IListCollectionIdsRequest { + + /** ListCollectionIdsRequest parent */ + parent?: (string|null); + + /** ListCollectionIdsRequest pageSize */ + pageSize?: (number|null); + + /** ListCollectionIdsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListCollectionIdsRequest. */ + class ListCollectionIdsRequest implements IListCollectionIdsRequest { + + /** + * Constructs a new ListCollectionIdsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListCollectionIdsRequest); + + /** ListCollectionIdsRequest parent. */ + public parent: string; + + /** ListCollectionIdsRequest pageSize. */ + public pageSize: number; + + /** ListCollectionIdsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListCollectionIdsRequest; + + /** + * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. + * @param message ListCollectionIdsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListCollectionIdsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListCollectionIdsResponse. */ + interface IListCollectionIdsResponse { + + /** ListCollectionIdsResponse collectionIds */ + collectionIds?: (string[]|null); + + /** ListCollectionIdsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListCollectionIdsResponse. */ + class ListCollectionIdsResponse implements IListCollectionIdsResponse { + + /** + * Constructs a new ListCollectionIdsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListCollectionIdsResponse); + + /** ListCollectionIdsResponse collectionIds. */ + public collectionIds: string[]; + + /** ListCollectionIdsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListCollectionIdsResponse; + + /** + * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. + * @param message ListCollectionIdsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListCollectionIdsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteRequest. */ + interface IBatchWriteRequest { + + /** BatchWriteRequest database */ + database?: (string|null); + + /** BatchWriteRequest writes */ + writes?: (google.firestore.v1beta1.IWrite[]|null); + + /** BatchWriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a BatchWriteRequest. */ + class BatchWriteRequest implements IBatchWriteRequest { + + /** + * Constructs a new BatchWriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBatchWriteRequest); + + /** BatchWriteRequest database. */ + public database: string; + + /** BatchWriteRequest writes. */ + public writes: google.firestore.v1beta1.IWrite[]; + + /** BatchWriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchWriteRequest; + + /** + * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. + * @param message BatchWriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BatchWriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteResponse. */ + interface IBatchWriteResponse { + + /** BatchWriteResponse writeResults */ + writeResults?: (google.firestore.v1beta1.IWriteResult[]|null); + + /** BatchWriteResponse status */ + status?: (google.rpc.IStatus[]|null); + } + + /** Represents a BatchWriteResponse. */ + class BatchWriteResponse implements IBatchWriteResponse { + + /** + * Constructs a new BatchWriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBatchWriteResponse); + + /** BatchWriteResponse writeResults. */ + public writeResults: google.firestore.v1beta1.IWriteResult[]; + + /** BatchWriteResponse status. */ + public status: google.rpc.IStatus[]; + + /** + * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchWriteResponse; + + /** + * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. + * @param message BatchWriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BatchWriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StructuredQuery. */ + interface IStructuredQuery { + + /** StructuredQuery select */ + select?: (google.firestore.v1beta1.StructuredQuery.IProjection|null); + + /** StructuredQuery from */ + from?: (google.firestore.v1beta1.StructuredQuery.ICollectionSelector[]|null); + + /** StructuredQuery where */ + where?: (google.firestore.v1beta1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy */ + orderBy?: (google.firestore.v1beta1.StructuredQuery.IOrder[]|null); + + /** StructuredQuery startAt */ + startAt?: (google.firestore.v1beta1.ICursor|null); + + /** StructuredQuery endAt */ + endAt?: (google.firestore.v1beta1.ICursor|null); + + /** StructuredQuery offset */ + offset?: (number|null); + + /** StructuredQuery limit */ + limit?: (google.protobuf.IInt32Value|null); + } + + /** Represents a StructuredQuery. */ + class StructuredQuery implements IStructuredQuery { + + /** + * Constructs a new StructuredQuery. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IStructuredQuery); + + /** StructuredQuery select. */ + public select?: (google.firestore.v1beta1.StructuredQuery.IProjection|null); + + /** StructuredQuery from. */ + public from: google.firestore.v1beta1.StructuredQuery.ICollectionSelector[]; + + /** StructuredQuery where. */ + public where?: (google.firestore.v1beta1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy. */ + public orderBy: google.firestore.v1beta1.StructuredQuery.IOrder[]; + + /** StructuredQuery startAt. */ + public startAt?: (google.firestore.v1beta1.ICursor|null); + + /** StructuredQuery endAt. */ + public endAt?: (google.firestore.v1beta1.ICursor|null); + + /** StructuredQuery offset. */ + public offset: number; + + /** StructuredQuery limit. */ + public limit?: (google.protobuf.IInt32Value|null); + + /** + * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredQuery + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery; + + /** + * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. + * @param message StructuredQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructuredQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace StructuredQuery { + + /** Properties of a CollectionSelector. */ + interface ICollectionSelector { + + /** CollectionSelector collectionId */ + collectionId?: (string|null); + + /** CollectionSelector allDescendants */ + allDescendants?: (boolean|null); + } + + /** Represents a CollectionSelector. */ + class CollectionSelector implements ICollectionSelector { + + /** + * Constructs a new CollectionSelector. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.ICollectionSelector); + + /** CollectionSelector collectionId. */ + public collectionId: string; + + /** CollectionSelector allDescendants. */ + public allDescendants: boolean; + + /** + * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CollectionSelector + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.CollectionSelector; + + /** + * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. + * @param message CollectionSelector + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.CollectionSelector, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CollectionSelector to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CollectionSelector + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Filter. */ + interface IFilter { + + /** Filter compositeFilter */ + compositeFilter?: (google.firestore.v1beta1.StructuredQuery.ICompositeFilter|null); + + /** Filter fieldFilter */ + fieldFilter?: (google.firestore.v1beta1.StructuredQuery.IFieldFilter|null); + + /** Filter unaryFilter */ + unaryFilter?: (google.firestore.v1beta1.StructuredQuery.IUnaryFilter|null); + } + + /** Represents a Filter. */ + class Filter implements IFilter { + + /** + * Constructs a new Filter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IFilter); + + /** Filter compositeFilter. */ + public compositeFilter?: (google.firestore.v1beta1.StructuredQuery.ICompositeFilter|null); + + /** Filter fieldFilter. */ + public fieldFilter?: (google.firestore.v1beta1.StructuredQuery.IFieldFilter|null); + + /** Filter unaryFilter. */ + public unaryFilter?: (google.firestore.v1beta1.StructuredQuery.IUnaryFilter|null); + + /** Filter filterType. */ + public filterType?: ("compositeFilter"|"fieldFilter"|"unaryFilter"); + + /** + * Creates a Filter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Filter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.Filter; + + /** + * Creates a plain object from a Filter message. Also converts values to other types if specified. + * @param message Filter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.Filter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Filter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Filter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CompositeFilter. */ + interface ICompositeFilter { + + /** CompositeFilter op */ + op?: (google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator|null); + + /** CompositeFilter filters */ + filters?: (google.firestore.v1beta1.StructuredQuery.IFilter[]|null); + } + + /** Represents a CompositeFilter. */ + class CompositeFilter implements ICompositeFilter { + + /** + * Constructs a new CompositeFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.ICompositeFilter); + + /** CompositeFilter op. */ + public op: google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator; + + /** CompositeFilter filters. */ + public filters: google.firestore.v1beta1.StructuredQuery.IFilter[]; + + /** + * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CompositeFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.CompositeFilter; + + /** + * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. + * @param message CompositeFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.CompositeFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CompositeFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CompositeFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace CompositeFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "AND"; + } + + /** Properties of a FieldFilter. */ + interface IFieldFilter { + + /** FieldFilter field */ + field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op */ + op?: (google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator|null); + + /** FieldFilter value */ + value?: (google.firestore.v1beta1.IValue|null); + } + + /** Represents a FieldFilter. */ + class FieldFilter implements IFieldFilter { + + /** + * Constructs a new FieldFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IFieldFilter); + + /** FieldFilter field. */ + public field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op. */ + public op: google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator; + + /** FieldFilter value. */ + public value?: (google.firestore.v1beta1.IValue|null); + + /** + * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.FieldFilter; + + /** + * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. + * @param message FieldFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.FieldFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "LESS_THAN"| "LESS_THAN_OR_EQUAL"| "GREATER_THAN"| "GREATER_THAN_OR_EQUAL"| "EQUAL"| "NOT_EQUAL"| "ARRAY_CONTAINS"| "IN"| "ARRAY_CONTAINS_ANY"| "NOT_IN"; + } + + /** Properties of an UnaryFilter. */ + interface IUnaryFilter { + + /** UnaryFilter op */ + op?: (google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator|null); + + /** UnaryFilter field */ + field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + } + + /** Represents an UnaryFilter. */ + class UnaryFilter implements IUnaryFilter { + + /** + * Constructs a new UnaryFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IUnaryFilter); + + /** UnaryFilter op. */ + public op: google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator; + + /** UnaryFilter field. */ + public field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** UnaryFilter operandType. */ + public operandType?: "field"; + + /** + * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UnaryFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.UnaryFilter; + + /** + * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. + * @param message UnaryFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.UnaryFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UnaryFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UnaryFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UnaryFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "IS_NAN"| "IS_NULL"| "IS_NOT_NAN"| "IS_NOT_NULL"; + } + + /** Properties of a FieldReference. */ + interface IFieldReference { + + /** FieldReference fieldPath */ + fieldPath?: (string|null); + } + + /** Represents a FieldReference. */ + class FieldReference implements IFieldReference { + + /** + * Constructs a new FieldReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IFieldReference); + + /** FieldReference fieldPath. */ + public fieldPath: string; + + /** + * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldReference + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.FieldReference; + + /** + * Creates a plain object from a FieldReference message. Also converts values to other types if specified. + * @param message FieldReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.FieldReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Order. */ + interface IOrder { + + /** Order field */ + field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** Order direction */ + direction?: (google.firestore.v1beta1.StructuredQuery.Direction|null); + } + + /** Represents an Order. */ + class Order implements IOrder { + + /** + * Constructs a new Order. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IOrder); + + /** Order field. */ + public field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** Order direction. */ + public direction: google.firestore.v1beta1.StructuredQuery.Direction; + + /** + * Creates an Order message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Order + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.Order; + + /** + * Creates a plain object from an Order message. Also converts values to other types if specified. + * @param message Order + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.Order, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Order to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Order + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Projection. */ + interface IProjection { + + /** Projection fields */ + fields?: (google.firestore.v1beta1.StructuredQuery.IFieldReference[]|null); + } + + /** Represents a Projection. */ + class Projection implements IProjection { + + /** + * Constructs a new Projection. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IProjection); + + /** Projection fields. */ + public fields: google.firestore.v1beta1.StructuredQuery.IFieldReference[]; + + /** + * Creates a Projection message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Projection + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.Projection; + + /** + * Creates a plain object from a Projection message. Also converts values to other types if specified. + * @param message Projection + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.Projection, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Projection to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Projection + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Direction enum. */ + type Direction = + "DIRECTION_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; + } + + /** Properties of a Cursor. */ + interface ICursor { + + /** Cursor values */ + values?: (google.firestore.v1beta1.IValue[]|null); + + /** Cursor before */ + before?: (boolean|null); + } + + /** Represents a Cursor. */ + class Cursor implements ICursor { + + /** + * Constructs a new Cursor. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ICursor); + + /** Cursor values. */ + public values: google.firestore.v1beta1.IValue[]; + + /** Cursor before. */ + public before: boolean; + + /** + * Creates a Cursor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Cursor + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Cursor; + + /** + * Creates a plain object from a Cursor message. Also converts values to other types if specified. + * @param message Cursor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Cursor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Cursor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Cursor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Write. */ + interface IWrite { + + /** Write update */ + update?: (google.firestore.v1beta1.IDocument|null); + + /** Write delete */ + "delete"?: (string|null); + + /** Write transform */ + transform?: (google.firestore.v1beta1.IDocumentTransform|null); + + /** Write updateMask */ + updateMask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** Write updateTransforms */ + updateTransforms?: (google.firestore.v1beta1.DocumentTransform.IFieldTransform[]|null); + + /** Write currentDocument */ + currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + } + + /** Represents a Write. */ + class Write implements IWrite { + + /** + * Constructs a new Write. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IWrite); + + /** Write update. */ + public update?: (google.firestore.v1beta1.IDocument|null); + + /** Write delete. */ + public delete?: (string|null); + + /** Write transform. */ + public transform?: (google.firestore.v1beta1.IDocumentTransform|null); + + /** Write updateMask. */ + public updateMask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** Write updateTransforms. */ + public updateTransforms: google.firestore.v1beta1.DocumentTransform.IFieldTransform[]; + + /** Write currentDocument. */ + public currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + + /** Write operation. */ + public operation?: ("update"|"delete"|"transform"); + + /** + * Creates a Write message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Write + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Write; + + /** + * Creates a plain object from a Write message. Also converts values to other types if specified. + * @param message Write + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Write, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Write to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Write + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentTransform. */ + interface IDocumentTransform { + + /** DocumentTransform document */ + document?: (string|null); + + /** DocumentTransform fieldTransforms */ + fieldTransforms?: (google.firestore.v1beta1.DocumentTransform.IFieldTransform[]|null); + } + + /** Represents a DocumentTransform. */ + class DocumentTransform implements IDocumentTransform { + + /** + * Constructs a new DocumentTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentTransform); + + /** DocumentTransform document. */ + public document: string; + + /** DocumentTransform fieldTransforms. */ + public fieldTransforms: google.firestore.v1beta1.DocumentTransform.IFieldTransform[]; + + /** + * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentTransform; + + /** + * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. + * @param message DocumentTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DocumentTransform { + + /** Properties of a FieldTransform. */ + interface IFieldTransform { + + /** FieldTransform fieldPath */ + fieldPath?: (string|null); + + /** FieldTransform setToServerValue */ + setToServerValue?: (google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment */ + increment?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform maximum */ + maximum?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform minimum */ + minimum?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform appendMissingElements */ + appendMissingElements?: (google.firestore.v1beta1.IArrayValue|null); + + /** FieldTransform removeAllFromArray */ + removeAllFromArray?: (google.firestore.v1beta1.IArrayValue|null); + } + + /** Represents a FieldTransform. */ + class FieldTransform implements IFieldTransform { + + /** + * Constructs a new FieldTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.DocumentTransform.IFieldTransform); + + /** FieldTransform fieldPath. */ + public fieldPath: string; + + /** FieldTransform setToServerValue. */ + public setToServerValue?: (google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment. */ + public increment?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform maximum. */ + public maximum?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform minimum. */ + public minimum?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform appendMissingElements. */ + public appendMissingElements?: (google.firestore.v1beta1.IArrayValue|null); + + /** FieldTransform removeAllFromArray. */ + public removeAllFromArray?: (google.firestore.v1beta1.IArrayValue|null); + + /** FieldTransform transformType. */ + public transformType?: ("setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"); + + /** + * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentTransform.FieldTransform; + + /** + * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. + * @param message FieldTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentTransform.FieldTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldTransform { + + /** ServerValue enum. */ + type ServerValue = + "SERVER_VALUE_UNSPECIFIED"| "REQUEST_TIME"; + } + } + + /** Properties of a WriteResult. */ + interface IWriteResult { + + /** WriteResult updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** WriteResult transformResults */ + transformResults?: (google.firestore.v1beta1.IValue[]|null); + } + + /** Represents a WriteResult. */ + class WriteResult implements IWriteResult { + + /** + * Constructs a new WriteResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IWriteResult); + + /** WriteResult updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** WriteResult transformResults. */ + public transformResults: google.firestore.v1beta1.IValue[]; + + /** + * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResult + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.WriteResult; + + /** + * Creates a plain object from a WriteResult message. Also converts values to other types if specified. + * @param message WriteResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.WriteResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentChange. */ + interface IDocumentChange { + + /** DocumentChange document */ + document?: (google.firestore.v1beta1.IDocument|null); + + /** DocumentChange targetIds */ + targetIds?: (number[]|null); + + /** DocumentChange removedTargetIds */ + removedTargetIds?: (number[]|null); + } + + /** Represents a DocumentChange. */ + class DocumentChange implements IDocumentChange { + + /** + * Constructs a new DocumentChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentChange); + + /** DocumentChange document. */ + public document?: (google.firestore.v1beta1.IDocument|null); + + /** DocumentChange targetIds. */ + public targetIds: number[]; + + /** DocumentChange removedTargetIds. */ + public removedTargetIds: number[]; + + /** + * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentChange; + + /** + * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. + * @param message DocumentChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentDelete. */ + interface IDocumentDelete { + + /** DocumentDelete document */ + document?: (string|null); + + /** DocumentDelete removedTargetIds */ + removedTargetIds?: (number[]|null); + + /** DocumentDelete readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a DocumentDelete. */ + class DocumentDelete implements IDocumentDelete { + + /** + * Constructs a new DocumentDelete. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentDelete); + + /** DocumentDelete document. */ + public document: string; + + /** DocumentDelete removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentDelete readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentDelete + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentDelete; + + /** + * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. + * @param message DocumentDelete + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentDelete, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentDelete to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentDelete + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentRemove. */ + interface IDocumentRemove { + + /** DocumentRemove document */ + document?: (string|null); + + /** DocumentRemove removedTargetIds */ + removedTargetIds?: (number[]|null); + + /** DocumentRemove readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a DocumentRemove. */ + class DocumentRemove implements IDocumentRemove { + + /** + * Constructs a new DocumentRemove. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentRemove); + + /** DocumentRemove document. */ + public document: string; + + /** DocumentRemove removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentRemove readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentRemove + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentRemove; + + /** + * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. + * @param message DocumentRemove + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentRemove, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentRemove to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentRemove + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExistenceFilter. */ + interface IExistenceFilter { + + /** ExistenceFilter targetId */ + targetId?: (number|null); + + /** ExistenceFilter count */ + count?: (number|null); + } + + /** Represents an ExistenceFilter. */ + class ExistenceFilter implements IExistenceFilter { + + /** + * Constructs a new ExistenceFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IExistenceFilter); + + /** ExistenceFilter targetId. */ + public targetId: number; + + /** ExistenceFilter count. */ + public count: number; + + /** + * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExistenceFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ExistenceFilter; + + /** + * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. + * @param message ExistenceFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ExistenceFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExistenceFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExistenceFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UndeliverableFirstGenEvent. */ + interface IUndeliverableFirstGenEvent { + + /** UndeliverableFirstGenEvent message */ + message?: (string|null); + + /** UndeliverableFirstGenEvent reason */ + reason?: (google.firestore.v1beta1.UndeliverableFirstGenEvent.Reason|null); + + /** UndeliverableFirstGenEvent documentName */ + documentName?: (string|null); + + /** UndeliverableFirstGenEvent documentChangeType */ + documentChangeType?: (google.firestore.v1beta1.UndeliverableFirstGenEvent.DocumentChangeType|null); + + /** UndeliverableFirstGenEvent functionName */ + functionName?: (string[]|null); + + /** UndeliverableFirstGenEvent triggeredTime */ + triggeredTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an UndeliverableFirstGenEvent. */ + class UndeliverableFirstGenEvent implements IUndeliverableFirstGenEvent { + + /** + * Constructs a new UndeliverableFirstGenEvent. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IUndeliverableFirstGenEvent); + + /** UndeliverableFirstGenEvent message. */ + public message: string; + + /** UndeliverableFirstGenEvent reason. */ + public reason: google.firestore.v1beta1.UndeliverableFirstGenEvent.Reason; + + /** UndeliverableFirstGenEvent documentName. */ + public documentName: string; + + /** UndeliverableFirstGenEvent documentChangeType. */ + public documentChangeType: google.firestore.v1beta1.UndeliverableFirstGenEvent.DocumentChangeType; + + /** UndeliverableFirstGenEvent functionName. */ + public functionName: string[]; + + /** UndeliverableFirstGenEvent triggeredTime. */ + public triggeredTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates an UndeliverableFirstGenEvent message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UndeliverableFirstGenEvent + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.UndeliverableFirstGenEvent; + + /** + * Creates a plain object from an UndeliverableFirstGenEvent message. Also converts values to other types if specified. + * @param message UndeliverableFirstGenEvent + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.UndeliverableFirstGenEvent, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UndeliverableFirstGenEvent to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UndeliverableFirstGenEvent + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UndeliverableFirstGenEvent { + + /** Reason enum. */ + type Reason = + "REASON_UNSPECIFIED"| "EXCEEDING_SIZE_LIMIT"; + + /** DocumentChangeType enum. */ + type DocumentChangeType = + "DOCUMENT_CHANGE_TYPE_UNSPECIFIED"| "CREATE"| "DELETE"| "UPDATE"; + } + } + } + + /** Namespace type. */ + namespace type { + + /** Properties of a LatLng. */ + interface ILatLng { + + /** LatLng latitude */ + latitude?: (number|null); + + /** LatLng longitude */ + longitude?: (number|null); + } + + /** Represents a LatLng. */ + class LatLng implements ILatLng { + + /** + * Constructs a new LatLng. + * @param [properties] Properties to set + */ + constructor(properties?: google.type.ILatLng); + + /** LatLng latitude. */ + public latitude: number; + + /** LatLng longitude. */ + public longitude: number; + + /** + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LatLng + */ + public static fromObject(object: { [k: string]: any }): google.type.LatLng; + + /** + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @param message LatLng + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LatLng to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LatLng + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** DayOfWeek enum. */ + type DayOfWeek = + "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; + } + + /** Namespace api. */ + namespace api { + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { + + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); + + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + } + + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { + + /** + * Constructs a new CommonLanguageSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICommonLanguageSettings); + + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; + + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; + + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommonLanguageSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { + + /** ClientLibrarySettings version */ + version?: (string|null); + + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|null); + + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); + + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } + + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { + + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); + + /** ClientLibrarySettings version. */ + public version: string; + + /** ClientLibrarySettings launchStage. */ + public launchStage: google.api.LaunchStage; + + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; + + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Publishing. */ + interface IPublishing { + + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); + + /** Publishing newIssueUri */ + newIssueUri?: (string|null); + + /** Publishing documentationUri */ + documentationUri?: (string|null); + + /** Publishing apiShortName */ + apiShortName?: (string|null); + + /** Publishing githubLabel */ + githubLabel?: (string|null); + + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); + + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); + + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|null); + + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); + + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); + + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } + + /** Represents a Publishing. */ + class Publishing implements IPublishing { + + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); + + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; + + /** Publishing newIssueUri. */ + public newIssueUri: string; + + /** Publishing documentationUri. */ + public documentationUri: string; + + /** Publishing apiShortName. */ + public apiShortName: string; + + /** Publishing githubLabel. */ + public githubLabel: string; + + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; + + /** Publishing docTagPrefix. */ + public docTagPrefix: string; + + /** Publishing organization. */ + public organization: google.api.ClientLibraryOrganization; + + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; + + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; + + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a JavaSettings. */ + interface IJavaSettings { + + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); + + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); + + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { + + /** + * Constructs a new JavaSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IJavaSettings); + + /** JavaSettings libraryPackage. */ + public libraryPackage: string; + + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; + + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns JavaSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this JavaSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CppSettings. */ + interface ICppSettings { + + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { + + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); + + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PhpSettings. */ + interface IPhpSettings { + + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { + + /** + * Constructs a new PhpSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPhpSettings); + + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PythonSettings. */ + interface IPythonSettings { + + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + } + + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { + + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); + + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PythonSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PythonSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PythonSettings { + + /** Properties of an ExperimentalFeatures. */ + interface IExperimentalFeatures { + + /** ExperimentalFeatures restAsyncIoEnabled */ + restAsyncIoEnabled?: (boolean|null); + + /** ExperimentalFeatures protobufPythonicTypesEnabled */ + protobufPythonicTypesEnabled?: (boolean|null); + + /** ExperimentalFeatures unversionedPackageDisabled */ + unversionedPackageDisabled?: (boolean|null); + } + + /** Represents an ExperimentalFeatures. */ + class ExperimentalFeatures implements IExperimentalFeatures { + + /** + * Constructs a new ExperimentalFeatures. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.PythonSettings.IExperimentalFeatures); + + /** ExperimentalFeatures restAsyncIoEnabled. */ + public restAsyncIoEnabled: boolean; + + /** ExperimentalFeatures protobufPythonicTypesEnabled. */ + public protobufPythonicTypesEnabled: boolean; + + /** ExperimentalFeatures unversionedPackageDisabled. */ + public unversionedPackageDisabled: boolean; + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExperimentalFeatures + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @param message ExperimentalFeatures + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings.ExperimentalFeatures, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExperimentalFeatures + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a NodeSettings. */ + interface INodeSettings { + + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { + + /** + * Constructs a new NodeSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.INodeSettings); + + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NodeSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NodeSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { + + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); + + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); + + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); + + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); + } + + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { + + /** + * Constructs a new DotnetSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IDotnetSettings); + + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; + + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; + + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; + + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DotnetSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DotnetSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RubySettings. */ + interface IRubySettings { + + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { + + /** + * Constructs a new RubySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRubySettings); + + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GoSettings. */ + interface IGoSettings { + + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + } + + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { + + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); + + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodSettings. */ + interface IMethodSettings { + + /** MethodSettings selector */ + selector?: (string|null); + + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); + } + + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { + + /** + * Constructs a new MethodSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IMethodSettings); + + /** MethodSettings selector. */ + public selector: string; + + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodSettings { + + /** Properties of a LongRunning. */ + interface ILongRunning { + + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); + + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); + } + + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { + + /** + * Constructs a new LongRunning. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.MethodSettings.ILongRunning); + + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; + + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LongRunning + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LongRunning to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LongRunning + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** ClientLibraryOrganization enum. */ + type ClientLibraryOrganization = + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; + + /** ClientLibraryDestination enum. */ + type ClientLibraryDestination = + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; + + /** Properties of a SelectiveGapicGeneration. */ + interface ISelectiveGapicGeneration { + + /** SelectiveGapicGeneration methods */ + methods?: (string[]|null); + + /** SelectiveGapicGeneration generateOmittedAsInternal */ + generateOmittedAsInternal?: (boolean|null); + } + + /** Represents a SelectiveGapicGeneration. */ + class SelectiveGapicGeneration implements ISelectiveGapicGeneration { + + /** + * Constructs a new SelectiveGapicGeneration. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ISelectiveGapicGeneration); + + /** SelectiveGapicGeneration methods. */ + public methods: string[]; + + /** SelectiveGapicGeneration generateOmittedAsInternal. */ + public generateOmittedAsInternal: boolean; + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SelectiveGapicGeneration + */ + public static fromObject(object: { [k: string]: any }): google.api.SelectiveGapicGeneration; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @param message SelectiveGapicGeneration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.SelectiveGapicGeneration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; + + /** FieldBehavior enum. */ + type FieldBehavior = + "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; + + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { + + /** ResourceDescriptor type */ + type?: (string|null); + + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); + + /** ResourceDescriptor nameField */ + nameField?: (string|null); + + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|null); + + /** ResourceDescriptor plural */ + plural?: (string|null); + + /** ResourceDescriptor singular */ + singular?: (string|null); + + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } + + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { + + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); + + /** ResourceDescriptor type. */ + public type: string; + + /** ResourceDescriptor pattern. */ + public pattern: string[]; + + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: google.api.ResourceDescriptor.History; + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ResourceDescriptor { + + /** History enum. */ + type History = + "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; + + /** Style enum. */ + type Style = + "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + } + + /** Properties of a ResourceReference. */ + interface IResourceReference { + + /** ResourceReference type */ + type?: (string|null); + + /** ResourceReference childType */ + childType?: (string|null); + } + + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { + + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); + + /** ResourceReference type. */ + public type: string; + + /** ResourceReference childType. */ + public childType: string; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RoutingRule. */ + interface IRoutingRule { + + /** RoutingRule routingParameters */ + routingParameters?: (google.api.IRoutingParameter[]|null); + } + + /** Represents a RoutingRule. */ + class RoutingRule implements IRoutingRule { + + /** + * Constructs a new RoutingRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRoutingRule); + + /** RoutingRule routingParameters. */ + public routingParameters: google.api.IRoutingParameter[]; + + /** + * Creates a RoutingRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingRule + */ + public static fromObject(object: { [k: string]: any }): google.api.RoutingRule; + + /** + * Creates a plain object from a RoutingRule message. Also converts values to other types if specified. + * @param message RoutingRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RoutingRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RoutingParameter. */ + interface IRoutingParameter { + + /** RoutingParameter field */ + field?: (string|null); + + /** RoutingParameter pathTemplate */ + pathTemplate?: (string|null); + } + + /** Represents a RoutingParameter. */ + class RoutingParameter implements IRoutingParameter { + + /** + * Constructs a new RoutingParameter. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRoutingParameter); + + /** RoutingParameter field. */ + public field: string; + + /** RoutingParameter pathTemplate. */ + public pathTemplate: string; + + /** + * Creates a RoutingParameter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingParameter + */ + public static fromObject(object: { [k: string]: any }): google.api.RoutingParameter; + + /** + * Creates a plain object from a RoutingParameter message. Also converts values to other types if specified. + * @param message RoutingParameter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RoutingParameter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingParameter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingParameter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace rpc. */ + namespace rpc { + + /** Properties of a Status. */ + interface IStatus { + + /** Status code */ + code?: (number|null); + + /** Status message */ + message?: (string|null); + + /** Status details */ + details?: (google.protobuf.IAny[]|null); + } + + /** Represents a Status. */ + class Status implements IStatus { + + /** + * Constructs a new Status. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IStatus); + + /** Status code. */ + public code: number; + + /** Status message. */ + public message: string; + + /** Status details. */ + public details: google.protobuf.IAny[]; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Status + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Status; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @param message Status + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Status to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Status + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace longrunning. */ + namespace longrunning { + + /** Represents an Operations */ + class Operations extends $protobuf.rpc.Service { + + /** + * Constructs a new Operations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListOperationsResponse + */ + public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void; + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @returns Promise + */ + public listOperations(request: google.longrunning.IListOperationsRequest): Promise; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @returns Promise + */ + public getOperation(request: google.longrunning.IGetOperationRequest): Promise; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @returns Promise + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @returns Promise + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @returns Promise + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise; + } + + namespace Operations { + + /** + * Callback as used by {@link google.longrunning.Operations#listOperations}. + * @param error Error, if any + * @param [response] ListOperationsResponse + */ + type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#getOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#deleteOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#cancelOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#waitOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of an Operation. */ + interface IOperation { + + /** Operation name */ + name?: (string|null); + + /** Operation metadata */ + metadata?: (google.protobuf.IAny|null); + + /** Operation done */ + done?: (boolean|null); + + /** Operation error */ + error?: (google.rpc.IStatus|null); + + /** Operation response */ + response?: (google.protobuf.IAny|null); + } + + /** Represents an Operation. */ + class Operation implements IOperation { + + /** + * Constructs a new Operation. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperation); + + /** Operation name. */ + public name: string; + + /** Operation metadata. */ + public metadata?: (google.protobuf.IAny|null); + + /** Operation done. */ + public done: boolean; + + /** Operation error. */ + public error?: (google.rpc.IStatus|null); + + /** Operation response. */ + public response?: (google.protobuf.IAny|null); + + /** Operation result. */ + public result?: ("error"|"response"); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Operation + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.Operation; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @param message Operation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Operation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Operation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetOperationRequest. */ + interface IGetOperationRequest { + + /** GetOperationRequest name */ + name?: (string|null); + } + + /** Represents a GetOperationRequest. */ + class GetOperationRequest implements IGetOperationRequest { + + /** + * Constructs a new GetOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IGetOperationRequest); + + /** GetOperationRequest name. */ + public name: string; + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @param message GetOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsRequest. */ + interface IListOperationsRequest { + + /** ListOperationsRequest name */ + name?: (string|null); + + /** ListOperationsRequest filter */ + filter?: (string|null); + + /** ListOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListOperationsRequest pageToken */ + pageToken?: (string|null); + + /** ListOperationsRequest returnPartialSuccess */ + returnPartialSuccess?: (boolean|null); + } + + /** Represents a ListOperationsRequest. */ + class ListOperationsRequest implements IListOperationsRequest { + + /** + * Constructs a new ListOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsRequest); + + /** ListOperationsRequest name. */ + public name: string; + + /** ListOperationsRequest filter. */ + public filter: string; + + /** ListOperationsRequest pageSize. */ + public pageSize: number; + + /** ListOperationsRequest pageToken. */ + public pageToken: string; + + /** ListOperationsRequest returnPartialSuccess. */ + public returnPartialSuccess: boolean; + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @param message ListOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsResponse. */ + interface IListOperationsResponse { + + /** ListOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + + /** ListOperationsResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListOperationsResponse. */ + class ListOperationsResponse implements IListOperationsResponse { + + /** + * Constructs a new ListOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsResponse); + + /** ListOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** ListOperationsResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @param message ListOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CancelOperationRequest. */ + interface ICancelOperationRequest { + + /** CancelOperationRequest name */ + name?: (string|null); + } + + /** Represents a CancelOperationRequest. */ + class CancelOperationRequest implements ICancelOperationRequest { + + /** + * Constructs a new CancelOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.ICancelOperationRequest); + + /** CancelOperationRequest name. */ + public name: string; + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CancelOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @param message CancelOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CancelOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteOperationRequest. */ + interface IDeleteOperationRequest { + + /** DeleteOperationRequest name */ + name?: (string|null); + } + + /** Represents a DeleteOperationRequest. */ + class DeleteOperationRequest implements IDeleteOperationRequest { + + /** + * Constructs a new DeleteOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IDeleteOperationRequest); + + /** DeleteOperationRequest name. */ + public name: string; + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @param message DeleteOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WaitOperationRequest. */ + interface IWaitOperationRequest { + + /** WaitOperationRequest name */ + name?: (string|null); + + /** WaitOperationRequest timeout */ + timeout?: (google.protobuf.IDuration|null); + } + + /** Represents a WaitOperationRequest. */ + class WaitOperationRequest implements IWaitOperationRequest { + + /** + * Constructs a new WaitOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IWaitOperationRequest); + + /** WaitOperationRequest name. */ + public name: string; + + /** WaitOperationRequest timeout. */ + public timeout?: (google.protobuf.IDuration|null); + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @param message WaitOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WaitOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an OperationInfo. */ + interface IOperationInfo { + + /** OperationInfo responseType */ + responseType?: (string|null); + + /** OperationInfo metadataType */ + metadataType?: (string|null); + } + + /** Represents an OperationInfo. */ + class OperationInfo implements IOperationInfo { + + /** + * Constructs a new OperationInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperationInfo); + + /** OperationInfo responseType. */ + public responseType: string; + + /** OperationInfo metadataType. */ + public metadataType: string; + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationInfo + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @param message OperationInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } +} diff --git a/handwritten/firestore/types/v1/firestore_admin_client.d.ts b/handwritten/firestore/types/v1/firestore_admin_client.d.ts new file mode 100644 index 00000000000..1682d760531 --- /dev/null +++ b/handwritten/firestore/types/v1/firestore_admin_client.d.ts @@ -0,0 +1,2405 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type * as gax from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + LROperation, + PaginationCallback, + LocationsClient, + LocationProtos, +} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../protos/firestore_admin_v1_proto_api'; +/** + * The Cloud Firestore Admin API. + * + * This API provides several administrative services for Cloud Firestore. + * + * Project, Database, Namespace, Collection, Collection Group, and Document are + * used as defined in the Google Cloud Firestore API. + * + * Operation: An Operation represents work being performed in the background. + * + * The index service manages Cloud Firestore indexes. + * + * Index creation is performed asynchronously. + * An Operation resource is created for each such asynchronous operation. + * The state of the operation (including any errors encountered) + * may be queried via the Operation resource. + * + * The Operations collection provides a record of actions performed for the + * specified Project (including any Operations in progress). Operations are not + * created directly but through calls on other collections or resources. + * + * An Operation that is done may be deleted so that it is no longer listed as + * part of the Operation collection. Operations are garbage collected after + * 30 days. By default, ListOperations will only return in progress and failed + * operations. To list completed operation, issue a ListOperations request with + * the filter `done: true`. + * + * Operations are created by service `FirestoreAdmin`, but are accessed via + * service `google.longrunning.Operations`. + * @class + * @memberof v1 + */ +export declare class FirestoreAdminClient { + private _terminated; + private _opts; + private _providedCustomServicePath; + private _gaxModule; + private _gaxGrpc; + private _protos; + private _defaults; + private _universeDomain; + private _servicePath; + auth: gax.GoogleAuth; + descriptors: Descriptors; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: { + [name: string]: Function; + }; + locationsClient: LocationsClient; + pathTemplates: { + [name: string]: gax.PathTemplate; + }; + operationsClient: gax.OperationsClient; + firestoreAdminStub?: Promise<{ + [name: string]: Function; + }>; + /** + * Construct an instance of FirestoreAdminClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreAdminClient({fallback: true}, gax); + * ``` + */ + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ); + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize(): Promise<{ + [name: string]: Function; + }>; + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath(): string; + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint(): string; + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint(): string; + get universeDomain(): string; + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port(): number; + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes(): string[]; + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Gets a composite index. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Index|Index}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example

+ * region_tag:firestore_v1_generated_FirestoreAdmin_GetIndex_async + */ + getIndex( + request?: protos.google.firestore.admin.v1.IGetIndexRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | undefined, + {} | undefined, + ] + >; + getIndex( + request: protos.google.firestore.admin.v1.IGetIndexRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, + {} | null | undefined + >, + ): void; + getIndex( + request: protos.google.firestore.admin.v1.IGetIndexRequest, + callback: Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Deletes a composite index. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteIndex_async + */ + deleteIndex( + request?: protos.google.firestore.admin.v1.IDeleteIndexRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | undefined, + {} | undefined, + ] + >; + deleteIndex( + request: protos.google.firestore.admin.v1.IDeleteIndexRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | null | undefined, + {} | null | undefined + >, + ): void; + deleteIndex( + request: protos.google.firestore.admin.v1.IDeleteIndexRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Gets the metadata and configuration for a Field. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Field|Field}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetField_async + */ + getField( + request?: protos.google.firestore.admin.v1.IGetFieldRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | undefined, + {} | undefined, + ] + >; + getField( + request: protos.google.firestore.admin.v1.IGetFieldRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, + {} | null | undefined + >, + ): void; + getField( + request: protos.google.firestore.admin.v1.IGetFieldRequest, + callback: Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Gets information about a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Database|Database}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetDatabase_async + */ + getDatabase( + request?: protos.google.firestore.admin.v1.IGetDatabaseRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | undefined, + {} | undefined, + ] + >; + getDatabase( + request: protos.google.firestore.admin.v1.IGetDatabaseRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | null | undefined, + {} | null | undefined + >, + ): void; + getDatabase( + request: protos.google.firestore.admin.v1.IGetDatabaseRequest, + callback: Callback< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * List all the databases in the project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}` + * @param {boolean} request.showDeleted + * If true, also returns deleted resources. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListDatabasesResponse|ListDatabasesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListDatabases_async + */ + listDatabases( + request?: protos.google.firestore.admin.v1.IListDatabasesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | undefined, + {} | undefined, + ] + >; + listDatabases( + request: protos.google.firestore.admin.v1.IListDatabasesRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | null | undefined, + {} | null | undefined + >, + ): void; + listDatabases( + request: protos.google.firestore.admin.v1.IListDatabasesRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Gets information about a backup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the backup to fetch. + * + * Format is `projects/{project}/locations/{location}/backups/{backup}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Backup|Backup}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackup_async + */ + getBackup( + request?: protos.google.firestore.admin.v1.IGetBackupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | undefined, + {} | undefined, + ] + >; + getBackup( + request: protos.google.firestore.admin.v1.IGetBackupRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, + {} | null | undefined + >, + ): void; + getBackup( + request: protos.google.firestore.admin.v1.IGetBackupRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Lists all the backups. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The location to list backups from. + * + * Format is `projects/{project}/locations/{location}`. + * Use `{location} = '-'` to list backups from all locations for the given + * project. This allows listing backups from a single location or from all + * locations. + * @param {string} request.filter + * An expression that filters the list of returned backups. + * + * A filter expression consists of a field name, a comparison operator, and a + * value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the {@link protos.google.firestore.admin.v1.Backup|Backup} are + * eligible for filtering: + * + * * `database_uid` (supports `=` only) + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupsResponse|ListBackupsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackups_async + */ + listBackups( + request?: protos.google.firestore.admin.v1.IListBackupsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | undefined, + {} | undefined, + ] + >; + listBackups( + request: protos.google.firestore.admin.v1.IListBackupsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | null | undefined, + {} | null | undefined + >, + ): void; + listBackups( + request: protos.google.firestore.admin.v1.IListBackupsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Deletes a backup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the backup to delete. + * + * format is `projects/{project}/locations/{location}/backups/{backup}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackup_async + */ + deleteBackup( + request?: protos.google.firestore.admin.v1.IDeleteBackupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | undefined, + {} | undefined, + ] + >; + deleteBackup( + request: protos.google.firestore.admin.v1.IDeleteBackupRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | null | undefined, + {} | null | undefined + >, + ): void; + deleteBackup( + request: protos.google.firestore.admin.v1.IDeleteBackupRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Creates a backup schedule on a database. + * At most two backup schedules can be configured on a database, one daily + * backup schedule and one weekly backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent database. + * + * Format `projects/{project}/databases/{database}` + * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule + * Required. The backup schedule to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateBackupSchedule_async + */ + createBackupSchedule( + request?: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.ICreateBackupScheduleRequest | undefined, + {} | undefined, + ] + >; + createBackupSchedule( + request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + createBackupSchedule( + request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + /** + * Gets information about a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the backup schedule. + * + * Format + * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackupSchedule_async + */ + getBackupSchedule( + request?: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IGetBackupScheduleRequest | undefined, + {} | undefined, + ] + >; + getBackupSchedule( + request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getBackupSchedule( + request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + /** + * List backup schedules. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent database. + * + * Format is `projects/{project}/databases/{database}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupSchedulesResponse|ListBackupSchedulesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackupSchedules_async + */ + listBackupSchedules( + request?: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + protos.google.firestore.admin.v1.IListBackupSchedulesRequest | undefined, + {} | undefined, + ] + >; + listBackupSchedules( + request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + listBackupSchedules( + request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + /** + * Updates a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule + * Required. The backup schedule to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The list of fields to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateBackupSchedule_async + */ + updateBackupSchedule( + request?: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest | undefined, + {} | undefined, + ] + >; + updateBackupSchedule( + request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + updateBackupSchedule( + request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + /** + * Deletes a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the backup schedule. + * + * Format + * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackupSchedule_async + */ + deleteBackupSchedule( + request?: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest | undefined, + {} | undefined, + ] + >; + deleteBackupSchedule( + request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + deleteBackupSchedule( + request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + /** + * Creates a composite index. This returns a + * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be + * used to track the status of the creation. The metadata for the operation + * will be the type + * {@link protos.google.firestore.admin.v1.IndexOperationMetadata|IndexOperationMetadata}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {google.firestore.admin.v1.Index} request.index + * Required. The composite index to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async + */ + createIndex( + request?: protos.google.firestore.admin.v1.ICreateIndexRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + createIndex( + request: protos.google.firestore.admin.v1.ICreateIndexRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + createIndex( + request: protos.google.firestore.admin.v1.ICreateIndexRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Check the status of the long running operation returned by `createIndex()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async + */ + checkCreateIndexProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Index, + protos.google.firestore.admin.v1.IndexOperationMetadata + > + >; + /** + * Updates a field configuration. Currently, field updates apply only to + * single field index configuration. However, calls to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.UpdateField|FirestoreAdmin.UpdateField} + * should provide a field mask to avoid changing any configuration that the + * caller isn't aware of. The field mask should be specified as: `{ paths: + * "index_config" }`. + * + * This call returns a + * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be + * used to track the status of the field update. The metadata for the + * operation will be the type + * {@link protos.google.firestore.admin.v1.FieldOperationMetadata|FieldOperationMetadata}. + * + * To configure the default field settings for the database, use + * the special `Field` with resource name: + * `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.Field} request.field + * Required. The field to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * A mask, relative to the field. If specified, only configuration specified + * by this field_mask will be updated in the field. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async + */ + updateField( + request?: protos.google.firestore.admin.v1.IUpdateFieldRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + updateField( + request: protos.google.firestore.admin.v1.IUpdateFieldRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + updateField( + request: protos.google.firestore.admin.v1.IUpdateFieldRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Check the status of the long running operation returned by `updateField()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async + */ + checkUpdateFieldProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Field, + protos.google.firestore.admin.v1.FieldOperationMetadata + > + >; + /** + * Exports a copy of all or a subset of documents from Google Cloud Firestore + * to another storage system, such as Google Cloud Storage. Recent updates to + * documents may not be reflected in the export. The export occurs in the + * background and its progress can be monitored and managed via the + * Operation resource that is created. The output of an export may only be + * used once the associated operation is done. If an export operation is + * cancelled before completion it may leave partial data behind in Google + * Cloud Storage. + * + * For more details on export behavior and output format, refer to: + * https://cloud.google.com/firestore/docs/manage-data/export-import + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to export. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.collectionIds + * Which collection IDs to export. Unspecified means all collections. Each + * collection ID in this list must be unique. + * @param {string} request.outputUriPrefix + * The output URI. Currently only supports Google Cloud Storage URIs of the + * form: `gs://BUCKET_NAME[/NAMESPACE_PATH]`, where `BUCKET_NAME` is the name + * of the Google Cloud Storage bucket and `NAMESPACE_PATH` is an optional + * Google Cloud Storage namespace path. When + * choosing a name, be sure to consider Google Cloud Storage naming + * guidelines: https://cloud.google.com/storage/docs/naming. + * If the URI is a bucket (without a namespace path), a prefix will be + * generated based on the start time. + * @param {string[]} request.namespaceIds + * An empty list represents all namespaces. This is the preferred + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to include them. Each namespace in this list must be unique. + * @param {google.protobuf.Timestamp} request.snapshotTime + * The timestamp that corresponds to the version of the database to be + * exported. The timestamp must be in the past, rounded to the minute and not + * older than + * {@link protos.google.firestore.admin.v1.Database.earliest_version_time|earliestVersionTime}. + * If specified, then the exported documents will represent a consistent view + * of the database at the provided time. Otherwise, there are no guarantees + * about the consistency of the exported documents. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async + */ + exportDocuments( + request?: protos.google.firestore.admin.v1.IExportDocumentsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + exportDocuments( + request: protos.google.firestore.admin.v1.IExportDocumentsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + exportDocuments( + request: protos.google.firestore.admin.v1.IExportDocumentsRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Check the status of the long running operation returned by `exportDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async + */ + checkExportDocumentsProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.ExportDocumentsResponse, + protos.google.firestore.admin.v1.ExportDocumentsMetadata + > + >; + /** + * Imports documents into Google Cloud Firestore. Existing documents with the + * same name are overwritten. The import occurs in the background and its + * progress can be monitored and managed via the Operation resource that is + * created. If an ImportDocuments operation is cancelled, it is possible + * that a subset of the data has already been imported to Cloud Firestore. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to import into. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.collectionIds + * Which collection IDs to import. Unspecified means all collections included + * in the import. Each collection ID in this list must be unique. + * @param {string} request.inputUriPrefix + * Location of the exported files. + * This must match the output_uri_prefix of an ExportDocumentsResponse from + * an export that has completed successfully. + * See: + * {@link protos.google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix|google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix}. + * @param {string[]} request.namespaceIds + * An empty list represents all namespaces. This is the preferred + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to include them. Each namespace in this list must be unique. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async + */ + importDocuments( + request?: protos.google.firestore.admin.v1.IImportDocumentsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + importDocuments( + request: protos.google.firestore.admin.v1.IImportDocumentsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + importDocuments( + request: protos.google.firestore.admin.v1.IImportDocumentsRequest, + callback: Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Check the status of the long running operation returned by `importDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async + */ + checkImportDocumentsProgress( + name: string, + ): Promise< + LROperation< + protos.google.protobuf.Empty, + protos.google.firestore.admin.v1.ImportDocumentsMetadata + > + >; + /** + * Bulk deletes a subset of documents from Google Cloud Firestore. + * Documents created or updated after the underlying system starts to process + * the request will not be deleted. The bulk delete occurs in the background + * and its progress can be monitored and managed via the Operation resource + * that is created. + * + * For more details on bulk delete behavior, refer to: + * https://cloud.google.com/firestore/docs/manage-data/bulk-delete + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to operate. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} [request.collectionIds] + * Optional. IDs of the collection groups to delete. Unspecified means all + * collection groups. + * + * Each collection group in this list must be unique. + * @param {string[]} [request.namespaceIds] + * Optional. Namespaces to delete. + * + * An empty list means all namespaces. This is the recommended + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to delete from them. + * + * Each namespace in this list must be unique. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async + */ + bulkDeleteDocuments( + request?: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + bulkDeleteDocuments( + request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + bulkDeleteDocuments( + request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Check the status of the long running operation returned by `bulkDeleteDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async + */ + checkBulkDeleteDocumentsProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.BulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.BulkDeleteDocumentsMetadata + > + >; + /** + * Create a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}` + * @param {google.firestore.admin.v1.Database} request.database + * Required. The Database to create. + * @param {string} request.databaseId + * Required. The ID to use for the database, which will become the final + * component of the database's resource name. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * + * "(default)" database ID is also valid. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async + */ + createDatabase( + request?: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + createDatabase( + request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + createDatabase( + request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Check the status of the long running operation returned by `createDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async + */ + checkCreateDatabaseProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.CreateDatabaseMetadata + > + >; + /** + * Updates a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.Database} request.database + * Required. The database to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The list of fields to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + */ + updateDatabase( + request?: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + updateDatabase( + request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + updateDatabase( + request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Check the status of the long running operation returned by `updateDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + */ + checkUpdateDatabaseProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.UpdateDatabaseMetadata + > + >; + /** + * Deletes a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {string} request.etag + * The current etag of the Database. + * If an etag is provided and does not match the current etag of the database, + * deletion will be blocked and a FAILED_PRECONDITION error will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async + */ + deleteDatabase( + request?: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + deleteDatabase( + request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + deleteDatabase( + request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Check the status of the long running operation returned by `deleteDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async + */ + checkDeleteDatabaseProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.DeleteDatabaseMetadata + > + >; + /** + * Creates a new database by restoring from an existing backup. + * + * The new database must be in the same cloud region or multi-region location + * as the existing backup. This behaves similar to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.CreateDatabase|FirestoreAdmin.CreateDatabase} + * except instead of creating a new empty database, a new database is created + * with the database type, index configuration, and documents from an existing + * backup. + * + * The {@link protos.google.longrunning.Operation|long-running operation} can be used to + * track the progress of the restore, with the Operation's + * {@link protos.google.longrunning.Operation.metadata|metadata} field type being the + * {@link protos.google.firestore.admin.v1.RestoreDatabaseMetadata|RestoreDatabaseMetadata}. + * The {@link protos.google.longrunning.Operation.response|response} type is the + * {@link protos.google.firestore.admin.v1.Database|Database} if the restore was + * successful. The new database is not readable or writeable until the LRO has + * completed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project to restore the database in. Format is + * `projects/{project_id}`. + * @param {string} request.databaseId + * Required. The ID to use for the database, which will become the final + * component of the database's resource name. This database ID must not be + * associated with an existing database. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * + * "(default)" database ID is also valid. + * @param {string} request.backup + * Required. Backup to restore from. Must be from the same project as the + * parent. + * + * The restored database will be created in the same location as the source + * backup. + * + * Format is: `projects/{project_id}/locations/{location}/backups/{backup}` + * @param {google.firestore.admin.v1.Database.EncryptionConfig} [request.encryptionConfig] + * Optional. Encryption configuration for the restored database. + * + * If this field is not specified, the restored database will use + * the same encryption configuration as the backup, namely + * {@link protos.google.firestore.admin.v1.Database.EncryptionConfig.use_source_encryption|use_source_encryption}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async + */ + restoreDatabase( + request?: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + restoreDatabase( + request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + restoreDatabase( + request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Check the status of the long running operation returned by `restoreDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async + */ + checkRestoreDatabaseProgress( + name: string, + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.RestoreDatabaseMetadata + > + >; + /** + * Lists composite indexes. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Index|Index}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listIndexesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listIndexes( + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IIndex[], + protos.google.firestore.admin.v1.IListIndexesRequest | null, + protos.google.firestore.admin.v1.IListIndexesResponse, + ] + >; + listIndexes( + request: protos.google.firestore.admin.v1.IListIndexesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + protos.google.firestore.admin.v1.IListIndexesResponse | null | undefined, + protos.google.firestore.admin.v1.IIndex + >, + ): void; + listIndexes( + request: protos.google.firestore.admin.v1.IListIndexesRequest, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + protos.google.firestore.admin.v1.IListIndexesResponse | null | undefined, + protos.google.firestore.admin.v1.IIndex + >, + ): void; + /** + * Equivalent to `listIndexes`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Index|Index} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listIndexesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listIndexesStream( + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + options?: CallOptions, + ): Transform; + /** + * Equivalent to `listIndexes`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.admin.v1.Index|Index}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListIndexes_async + */ + listIndexesAsync( + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + options?: CallOptions, + ): AsyncIterable; + /** + * Lists the field configuration and metadata for this database. + * + * Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with the filter set to `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Field|Field}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listFieldsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listFields( + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.admin.v1.IField[], + protos.google.firestore.admin.v1.IListFieldsRequest | null, + protos.google.firestore.admin.v1.IListFieldsResponse, + ] + >; + listFields( + request: protos.google.firestore.admin.v1.IListFieldsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + protos.google.firestore.admin.v1.IListFieldsResponse | null | undefined, + protos.google.firestore.admin.v1.IField + >, + ): void; + listFields( + request: protos.google.firestore.admin.v1.IListFieldsRequest, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + protos.google.firestore.admin.v1.IListFieldsResponse | null | undefined, + protos.google.firestore.admin.v1.IField + >, + ): void; + /** + * Equivalent to `listFields`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Field|Field} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listFieldsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listFieldsStream( + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + options?: CallOptions, + ): Transform; + /** + * Equivalent to `listFields`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.admin.v1.Field|Field}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListFields_async + */ + listFieldsAsync( + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + options?: CallOptions, + ): AsyncIterable; + /** + * Gets information about a location. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Resource name for the location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html | CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.cloud.location.Location | Location}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * ``` + * const [response] = await client.getLocation(request); + * ``` + */ + getLocation( + request: LocationProtos.google.cloud.location.IGetLocationRequest, + options?: + | gax.CallOptions + | Callback< + LocationProtos.google.cloud.location.ILocation, + | LocationProtos.google.cloud.location.IGetLocationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + LocationProtos.google.cloud.location.ILocation, + | LocationProtos.google.cloud.location.IGetLocationRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise; + /** + * Lists information about the supported locations for this service. Returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link google.cloud.location.Location | Location}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * ``` + * const iterable = client.listLocationsAsync(request); + * for await (const response of iterable) { + * // process response + * } + * ``` + */ + listLocationsAsync( + request: LocationProtos.google.cloud.location.IListLocationsRequest, + options?: CallOptions, + ): AsyncIterable; + /** + * Gets the latest state of a long-running operation. Clients can use this + * method to poll the operation result at intervals as recommended by the API + * service. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} + * for the details. + * @param {function(?Error, ?Object)=} callback + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing + * {@link google.longrunning.Operation | google.longrunning.Operation}. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * {@link google.longrunning.Operation | google.longrunning.Operation}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * const name = ''; + * const [response] = await client.getOperation({name}); + * // doThingsWith(response) + * ``` + */ + getOperation( + request: protos.google.longrunning.GetOperationRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protos.google.longrunning.Operation, + protos.google.longrunning.GetOperationRequest, + {} | null | undefined + >, + callback?: Callback< + protos.google.longrunning.Operation, + protos.google.longrunning.GetOperationRequest, + {} | null | undefined + >, + ): Promise<[protos.google.longrunning.Operation]>; + /** + * Lists operations that match the specified filter in the request. If the + * server doesn't support this method, it returns `UNIMPLEMENTED`. Returns an iterable object. + * + * For-await-of syntax is used with the iterable to recursively get response element on-demand. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation collection. + * @param {string} request.filter - The standard list filter. + * @param {number=} request.pageSize - + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} for the + * details. + * @returns {Object} + * An iterable Object that conforms to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | iteration protocols}. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * for await (const response of client.listOperationsAsync(request)); + * // doThingsWith(response) + * ``` + */ + listOperationsAsync( + request: protos.google.longrunning.ListOperationsRequest, + options?: gax.CallOptions, + ): AsyncIterable; + /** + * Starts asynchronous cancellation on a long-running operation. The server + * makes a best effort to cancel the operation, but success is not + * guaranteed. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. Clients can use + * {@link Operations.GetOperation} or + * other methods to check whether the cancellation succeeded or whether the + * operation completed despite cancellation. On successful cancellation, + * the operation is not deleted; instead, it becomes an operation with + * an {@link Operation.error} value with a {@link google.rpc.Status.code} of + * 1, corresponding to `Code.CANCELLED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be cancelled. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} for the + * details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @returns {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.cancelOperation({name: ''}); + * ``` + */ + cancelOperation( + request: protos.google.longrunning.CancelOperationRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protos.google.longrunning.CancelOperationRequest, + protos.google.protobuf.Empty, + {} | undefined | null + >, + callback?: Callback< + protos.google.longrunning.CancelOperationRequest, + protos.google.protobuf.Empty, + {} | undefined | null + >, + ): Promise; + /** + * Deletes a long-running operation. This method indicates that the client is + * no longer interested in the operation result. It does not cancel the + * operation. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be deleted. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} + * for the details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @returns {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.deleteOperation({name: ''}); + * ``` + */ + deleteOperation( + request: protos.google.longrunning.DeleteOperationRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protos.google.protobuf.Empty, + protos.google.longrunning.DeleteOperationRequest, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.Empty, + protos.google.longrunning.DeleteOperationRequest, + {} | null | undefined + >, + ): Promise; + /** + * Return a fully-qualified backup resource name string. + * + * @param {string} project + * @param {string} location + * @param {string} backup + * @returns {string} Resource name string. + */ + backupPath(project: string, location: string, backup: string): string; + /** + * Parse the project from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the project. + */ + matchProjectFromBackupName(backupName: string): string | number; + /** + * Parse the location from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the location. + */ + matchLocationFromBackupName(backupName: string): string | number; + /** + * Parse the backup from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the backup. + */ + matchBackupFromBackupName(backupName: string): string | number; + /** + * Return a fully-qualified backupSchedule resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} backup_schedule + * @returns {string} Resource name string. + */ + backupSchedulePath( + project: string, + database: string, + backupSchedule: string, + ): string; + /** + * Parse the project from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the project. + */ + matchProjectFromBackupScheduleName( + backupScheduleName: string, + ): string | number; + /** + * Parse the database from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromBackupScheduleName( + backupScheduleName: string, + ): string | number; + /** + * Parse the backup_schedule from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the backup_schedule. + */ + matchBackupScheduleFromBackupScheduleName( + backupScheduleName: string, + ): string | number; + /** + * Return a fully-qualified collectionGroup resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} collection + * @returns {string} Resource name string. + */ + collectionGroupPath( + project: string, + database: string, + collection: string, + ): string; + /** + * Parse the project from CollectionGroup resource. + * + * @param {string} collectionGroupName + * A fully-qualified path representing CollectionGroup resource. + * @returns {string} A string representing the project. + */ + matchProjectFromCollectionGroupName( + collectionGroupName: string, + ): string | number; + /** + * Parse the database from CollectionGroup resource. + * + * @param {string} collectionGroupName + * A fully-qualified path representing CollectionGroup resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromCollectionGroupName( + collectionGroupName: string, + ): string | number; + /** + * Parse the collection from CollectionGroup resource. + * + * @param {string} collectionGroupName + * A fully-qualified path representing CollectionGroup resource. + * @returns {string} A string representing the collection. + */ + matchCollectionFromCollectionGroupName( + collectionGroupName: string, + ): string | number; + /** + * Return a fully-qualified database resource name string. + * + * @param {string} project + * @param {string} database + * @returns {string} Resource name string. + */ + databasePath(project: string, database: string): string; + /** + * Parse the project from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the project. + */ + matchProjectFromDatabaseName(databaseName: string): string | number; + /** + * Parse the database from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromDatabaseName(databaseName: string): string | number; + /** + * Return a fully-qualified field resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} collection + * @param {string} field + * @returns {string} Resource name string. + */ + fieldPath( + project: string, + database: string, + collection: string, + field: string, + ): string; + /** + * Parse the project from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the project. + */ + matchProjectFromFieldName(fieldName: string): string | number; + /** + * Parse the database from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromFieldName(fieldName: string): string | number; + /** + * Parse the collection from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the collection. + */ + matchCollectionFromFieldName(fieldName: string): string | number; + /** + * Parse the field from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the field. + */ + matchFieldFromFieldName(fieldName: string): string | number; + /** + * Return a fully-qualified index resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} collection + * @param {string} index + * @returns {string} Resource name string. + */ + indexPath( + project: string, + database: string, + collection: string, + index: string, + ): string; + /** + * Parse the project from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the project. + */ + matchProjectFromIndexName(indexName: string): string | number; + /** + * Parse the database from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromIndexName(indexName: string): string | number; + /** + * Parse the collection from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the collection. + */ + matchCollectionFromIndexName(indexName: string): string | number; + /** + * Parse the index from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the index. + */ + matchIndexFromIndexName(indexName: string): string | number; + /** + * Return a fully-qualified location resource name string. + * + * @param {string} project + * @param {string} location + * @returns {string} Resource name string. + */ + locationPath(project: string, location: string): string; + /** + * Parse the project from Location resource. + * + * @param {string} locationName + * A fully-qualified path representing Location resource. + * @returns {string} A string representing the project. + */ + matchProjectFromLocationName(locationName: string): string | number; + /** + * Parse the location from Location resource. + * + * @param {string} locationName + * A fully-qualified path representing Location resource. + * @returns {string} A string representing the location. + */ + matchLocationFromLocationName(locationName: string): string | number; + /** + * Return a fully-qualified project resource name string. + * + * @param {string} project + * @returns {string} Resource name string. + */ + projectPath(project: string): string; + /** + * Parse the project from Project resource. + * + * @param {string} projectName + * A fully-qualified path representing Project resource. + * @returns {string} A string representing the project. + */ + matchProjectFromProjectName(projectName: string): string | number; + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise; +} diff --git a/handwritten/firestore/types/v1/firestore_client.d.ts b/handwritten/firestore/types/v1/firestore_client.d.ts new file mode 100644 index 00000000000..cc56770e5fb --- /dev/null +++ b/handwritten/firestore/types/v1/firestore_client.d.ts @@ -0,0 +1,1450 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type * as gax from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + LocationsClient, + LocationProtos, +} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../protos/firestore_v1_proto_api'; +/** + * 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. + * @class + * @memberof v1 + */ +export declare class FirestoreClient { + private _terminated; + private _opts; + private _providedCustomServicePath; + private _gaxModule; + private _gaxGrpc; + private _protos; + private _defaults; + private _universeDomain; + private _servicePath; + auth: gax.GoogleAuth; + descriptors: Descriptors; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: { + [name: string]: Function; + }; + locationsClient: LocationsClient; + firestoreStub?: Promise<{ + [name: string]: Function; + }>; + /** + * Construct an instance of FirestoreClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreClient({fallback: true}, gax); + * ``` + */ + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ); + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize(): Promise<{ + [name: string]: Function; + }>; + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath(): string; + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint(): string; + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint(): string; + get universeDomain(): string; + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port(): number; + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes(): string[]; + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Gets a single document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to get. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1.DocumentMask} request.mask + * 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. + * @param {Buffer} request.transaction + * Reads the document in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_GetDocument_async + */ + getDocument( + request?: protos.google.firestore.v1.IGetDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | undefined, + {} | undefined, + ] + >; + getDocument( + request: protos.google.firestore.v1.IGetDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + getDocument( + request: protos.google.firestore.v1.IGetDocumentRequest, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Updates or inserts a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.v1.Document} request.document + * Required. The updated document. + * Creates the document if it does not already exist. + * @param {google.firestore.v1.DocumentMask} request.updateMask + * 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. + * @param {google.firestore.v1.DocumentMask} request.mask + * 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. + * @param {google.firestore.v1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_UpdateDocument_async + */ + updateDocument( + request?: protos.google.firestore.v1.IUpdateDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | undefined, + {} | undefined, + ] + >; + updateDocument( + request: protos.google.firestore.v1.IUpdateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + updateDocument( + request: protos.google.firestore.v1.IUpdateDocumentRequest, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Deletes a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to delete. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_DeleteDocument_async + */ + deleteDocument( + request?: protos.google.firestore.v1.IDeleteDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | undefined, + {} | undefined, + ] + >; + deleteDocument( + request: protos.google.firestore.v1.IDeleteDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + deleteDocument( + request: protos.google.firestore.v1.IDeleteDocumentRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Starts a new transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {google.firestore.v1.TransactionOptions} request.options + * The options for the transaction. + * Defaults to a read-write transaction. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.BeginTransactionResponse|BeginTransactionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_BeginTransaction_async + */ + beginTransaction( + request?: protos.google.firestore.v1.IBeginTransactionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | undefined, + {} | undefined, + ] + >; + beginTransaction( + request: protos.google.firestore.v1.IBeginTransactionRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | null | undefined, + {} | null | undefined + >, + ): void; + beginTransaction( + request: protos.google.firestore.v1.IBeginTransactionRequest, + callback: Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Commits a transaction, while optionally updating documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * The writes to apply. + * + * Always executed atomically and in order. + * @param {Buffer} request.transaction + * If set, applies all writes in this transaction, and commits it. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.CommitResponse|CommitResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_Commit_async + */ + commit( + request?: protos.google.firestore.v1.ICommitRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | undefined, + {} | undefined, + ] + >; + commit( + request: protos.google.firestore.v1.ICommitRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | null | undefined, + {} | null | undefined + >, + ): void; + commit( + request: protos.google.firestore.v1.ICommitRequest, + callback: Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Rolls back a transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {Buffer} request.transaction + * Required. The transaction to roll back. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_Rollback_async + */ + rollback( + request?: protos.google.firestore.v1.IRollbackRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | undefined, + {} | undefined, + ] + >; + rollback( + request: protos.google.firestore.v1.IRollbackRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + ): void; + rollback( + request: protos.google.firestore.v1.IRollbackRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * 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 + * {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse} for the + * success status of each write. + * + * If you require an atomically applied set of writes, use + * {@link protos.google.firestore.v1.Firestore.Commit|Commit} instead. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * 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. + * @param {number[]} request.labels + * Labels associated with this batch write. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_BatchWrite_async + */ + batchWrite( + request?: protos.google.firestore.v1.IBatchWriteRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | undefined, + {} | undefined, + ] + >; + batchWrite( + request: protos.google.firestore.v1.IBatchWriteRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | null | undefined, + {} | null | undefined + >, + ): void; + batchWrite( + request: protos.google.firestore.v1.IBatchWriteRequest, + callback: Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Creates a new document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource. For example: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: + * `chatrooms`. + * @param {string} request.documentId + * The client-assigned document ID to use for this document. + * + * Optional. If not specified, an ID will be assigned by the service. + * @param {google.firestore.v1.Document} request.document + * Required. The document to create. `name` must not be set. + * @param {google.firestore.v1.DocumentMask} request.mask + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_CreateDocument_async + */ + createDocument( + request?: protos.google.firestore.v1.ICreateDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | undefined, + {} | undefined, + ] + >; + createDocument( + request: protos.google.firestore.v1.ICreateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + createDocument( + request: protos.google.firestore.v1.ICreateDocumentRequest, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Gets multiple documents. + * + * Documents returned by this method are not guaranteed to be returned in the + * same order that they were requested. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.documents + * 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. + * @param {google.firestore.v1.DocumentMask} request.mask + * 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. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * 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. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_BatchGetDocuments_async + */ + batchGetDocuments( + request?: protos.google.firestore.v1.IBatchGetDocumentsRequest, + options?: CallOptions, + ): gax.CancellableStream; + /** + * Runs a query. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * @param {Buffer} request.transaction + * Run the query within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * 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. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] + * Optional. Explain options for the query. If set, additional query + * statistics will be returned. If not, only query results will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.RunQueryResponse|RunQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_RunQuery_async + */ + runQuery( + request?: protos.google.firestore.v1.IRunQueryRequest, + options?: CallOptions, + ): gax.CancellableStream; + /** + * Runs an aggregation query. + * + * Rather than producing {@link protos.google.firestore.v1.Document|Document} results like + * {@link protos.google.firestore.v1.Firestore.RunQuery|Firestore.RunQuery}, this API + * allows running an aggregation to produce a series of + * {@link protos.google.firestore.v1.AggregationResult|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 ); + * ``` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {google.firestore.v1.StructuredAggregationQuery} request.structuredAggregationQuery + * An aggregation query. + * @param {Buffer} request.transaction + * Run the aggregation within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * 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. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] + * Optional. Explain options for the query. If set, additional query + * statistics will be returned. If not, only query results will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.RunAggregationQueryResponse|RunAggregationQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_RunAggregationQuery_async + */ + runAggregationQuery( + request?: protos.google.firestore.v1.IRunAggregationQueryRequest, + options?: CallOptions, + ): gax.CancellableStream; + /** + * Streams batches of document updates and deletes, in order. This method is + * only available via gRPC or WebChannel (not REST). + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1.WriteRequest|WriteRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1.WriteResponse|WriteResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_Write_async + */ + write(options?: CallOptions): gax.CancellableStream; + /** + * Listens to changes. This method is only available via gRPC or WebChannel + * (not REST). + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1.ListenRequest|ListenRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1.ListenResponse|ListenResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_Listen_async + */ + listen(options?: CallOptions): gax.CancellableStream; + /** + * Lists documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {string} [request.collectionId] + * 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`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * 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. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * 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. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {boolean} request.showMissing + * 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, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1.Document|Document}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocuments( + request?: protos.google.firestore.v1.IListDocumentsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1.IDocument[], + protos.google.firestore.v1.IListDocumentsRequest | null, + protos.google.firestore.v1.IListDocumentsResponse, + ] + >; + listDocuments( + request: protos.google.firestore.v1.IListDocumentsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1.IDocument + >, + ): void; + listDocuments( + request: protos.google.firestore.v1.IListDocumentsRequest, + callback: PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1.IDocument + >, + ): void; + /** + * Equivalent to `listDocuments`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {string} [request.collectionId] + * 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`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * 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. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * 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. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {boolean} request.showMissing + * 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, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1.Document|Document} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocumentsStream( + request?: protos.google.firestore.v1.IListDocumentsRequest, + options?: CallOptions, + ): Transform; + /** + * Equivalent to `listDocuments`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {string} [request.collectionId] + * 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`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * 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. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * 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. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {boolean} request.showMissing + * 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, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1.Document|Document}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_ListDocuments_async + */ + listDocumentsAsync( + request?: protos.google.firestore.v1.IListDocumentsRequest, + options?: CallOptions, + ): AsyncIterable; + /** + * 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. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * 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. + * @param {number} request.partitionCount + * 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. + * @param {string} request.pageToken + * 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 + * @param {number} request.pageSize + * 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`. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1.Cursor|Cursor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQuery( + request?: protos.google.firestore.v1.IPartitionQueryRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1.ICursor[], + protos.google.firestore.v1.IPartitionQueryRequest | null, + protos.google.firestore.v1.IPartitionQueryResponse, + ] + >; + partitionQuery( + request: protos.google.firestore.v1.IPartitionQueryRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, + protos.google.firestore.v1.ICursor + >, + ): void; + partitionQuery( + request: protos.google.firestore.v1.IPartitionQueryRequest, + callback: PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, + protos.google.firestore.v1.ICursor + >, + ): void; + /** + * Equivalent to `partitionQuery`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * 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. + * @param {number} request.partitionCount + * 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. + * @param {string} request.pageToken + * 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 + * @param {number} request.pageSize + * 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`. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1.Cursor|Cursor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQueryStream( + request?: protos.google.firestore.v1.IPartitionQueryRequest, + options?: CallOptions, + ): Transform; + /** + * Equivalent to `partitionQuery`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * 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. + * @param {number} request.partitionCount + * 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. + * @param {string} request.pageToken + * 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 + * @param {number} request.pageSize + * 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`. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1.Cursor|Cursor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_PartitionQuery_async + */ + partitionQueryAsync( + request?: protos.google.firestore.v1.IPartitionQueryRequest, + options?: CallOptions, + ): AsyncIterable; + /** + * Lists all the collection IDs underneath a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of string. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIds( + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + options?: CallOptions, + ): Promise< + [ + string[], + protos.google.firestore.v1.IListCollectionIdsRequest | null, + protos.google.firestore.v1.IListCollectionIdsResponse, + ] + >; + listCollectionIds( + request: protos.google.firestore.v1.IListCollectionIdsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + protos.google.firestore.v1.IListCollectionIdsResponse | null | undefined, + string + >, + ): void; + listCollectionIds( + request: protos.google.firestore.v1.IListCollectionIdsRequest, + callback: PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + protos.google.firestore.v1.IListCollectionIdsResponse | null | undefined, + string + >, + ): void; + /** + * Equivalent to `listCollectionIds`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing string on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIdsStream( + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + options?: CallOptions, + ): Transform; + /** + * Equivalent to `listCollectionIds`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * string. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_ListCollectionIds_async + */ + listCollectionIdsAsync( + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + options?: CallOptions, + ): AsyncIterable; + /** + * Gets information about a location. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Resource name for the location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html | CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.cloud.location.Location | Location}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * ``` + * const [response] = await client.getLocation(request); + * ``` + */ + getLocation( + request: LocationProtos.google.cloud.location.IGetLocationRequest, + options?: + | gax.CallOptions + | Callback< + LocationProtos.google.cloud.location.ILocation, + | LocationProtos.google.cloud.location.IGetLocationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + LocationProtos.google.cloud.location.ILocation, + | LocationProtos.google.cloud.location.IGetLocationRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise; + /** + * Lists information about the supported locations for this service. Returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link google.cloud.location.Location | Location}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * ``` + * const iterable = client.listLocationsAsync(request); + * for await (const response of iterable) { + * // process response + * } + * ``` + */ + listLocationsAsync( + request: LocationProtos.google.cloud.location.IListLocationsRequest, + options?: CallOptions, + ): AsyncIterable; + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise; +} diff --git a/handwritten/firestore/types/v1beta1/firestore_client.d.ts b/handwritten/firestore/types/v1beta1/firestore_client.d.ts new file mode 100644 index 00000000000..926a389aaa1 --- /dev/null +++ b/handwritten/firestore/types/v1beta1/firestore_client.d.ts @@ -0,0 +1,1211 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type * as gax from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, +} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../protos/firestore_v1beta1_proto_api'; +/** + * 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 (GCP) accelerate + * building truly serverless apps. + * @class + * @deprecated Use v1/firestore_client instead. + * @memberof v1beta1 + */ +export declare class FirestoreClient { + private _terminated; + private _opts; + private _providedCustomServicePath; + private _gaxModule; + private _gaxGrpc; + private _protos; + private _defaults; + private _universeDomain; + private _servicePath; + auth: gax.GoogleAuth; + descriptors: Descriptors; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: { + [name: string]: Function; + }; + firestoreStub?: Promise<{ + [name: string]: Function; + }>; + /** + * Construct an instance of FirestoreClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreClient({fallback: true}, gax); + * ``` + */ + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ); + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize(): Promise<{ + [name: string]: Function; + }>; + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath(): string; + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint(): string; + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint(): string; + get universeDomain(): string; + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port(): number; + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes(): string[]; + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Gets a single document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to get. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * 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. + * @param {Buffer} request.transaction + * Reads the document in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads the version of the document at the given time. + * This may not be older than 270 seconds. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_GetDocument_async + */ + getDocument( + request?: protos.google.firestore.v1beta1.IGetDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IGetDocumentRequest | undefined, + {} | undefined, + ] + >; + getDocument( + request: protos.google.firestore.v1beta1.IGetDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IGetDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + getDocument( + request: protos.google.firestore.v1beta1.IGetDocumentRequest, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IGetDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Updates or inserts a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.v1beta1.Document} request.document + * Required. The updated document. + * Creates the document if it does not already exist. + * @param {google.firestore.v1beta1.DocumentMask} request.updateMask + * 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. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * 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. + * @param {google.firestore.v1beta1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_UpdateDocument_async + */ + updateDocument( + request?: protos.google.firestore.v1beta1.IUpdateDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IUpdateDocumentRequest | undefined, + {} | undefined, + ] + >; + updateDocument( + request: protos.google.firestore.v1beta1.IUpdateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + updateDocument( + request: protos.google.firestore.v1beta1.IUpdateDocumentRequest, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Deletes a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to delete. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1beta1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_DeleteDocument_async + */ + deleteDocument( + request?: protos.google.firestore.v1beta1.IDeleteDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IDeleteDocumentRequest | undefined, + {} | undefined, + ] + >; + deleteDocument( + request: protos.google.firestore.v1beta1.IDeleteDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + deleteDocument( + request: protos.google.firestore.v1beta1.IDeleteDocumentRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Starts a new transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {google.firestore.v1beta1.TransactionOptions} request.options + * The options for the transaction. + * Defaults to a read-write transaction. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.BeginTransactionResponse|BeginTransactionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_BeginTransaction_async + */ + beginTransaction( + request?: protos.google.firestore.v1beta1.IBeginTransactionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1beta1.IBeginTransactionResponse, + protos.google.firestore.v1beta1.IBeginTransactionRequest | undefined, + {} | undefined, + ] + >; + beginTransaction( + request: protos.google.firestore.v1beta1.IBeginTransactionRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.IBeginTransactionResponse, + | protos.google.firestore.v1beta1.IBeginTransactionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + beginTransaction( + request: protos.google.firestore.v1beta1.IBeginTransactionRequest, + callback: Callback< + protos.google.firestore.v1beta1.IBeginTransactionResponse, + | protos.google.firestore.v1beta1.IBeginTransactionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + /** + * Commits a transaction, while optionally updating documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * The writes to apply. + * + * Always executed atomically and in order. + * @param {Buffer} request.transaction + * If set, applies all writes in this transaction, and commits it. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.CommitResponse|CommitResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_Commit_async + */ + commit( + request?: protos.google.firestore.v1beta1.ICommitRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1beta1.ICommitResponse, + protos.google.firestore.v1beta1.ICommitRequest | undefined, + {} | undefined, + ] + >; + commit( + request: protos.google.firestore.v1beta1.ICommitRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.ICommitResponse, + protos.google.firestore.v1beta1.ICommitRequest | null | undefined, + {} | null | undefined + >, + ): void; + commit( + request: protos.google.firestore.v1beta1.ICommitRequest, + callback: Callback< + protos.google.firestore.v1beta1.ICommitResponse, + protos.google.firestore.v1beta1.ICommitRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Rolls back a transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {Buffer} request.transaction + * Required. The transaction to roll back. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_Rollback_async + */ + rollback( + request?: protos.google.firestore.v1beta1.IRollbackRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IRollbackRequest | undefined, + {} | undefined, + ] + >; + rollback( + request: protos.google.firestore.v1beta1.IRollbackRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + ): void; + rollback( + request: protos.google.firestore.v1beta1.IRollbackRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * 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 + * {@link protos.google.firestore.v1beta1.BatchWriteResponse|BatchWriteResponse} for the success status of each write. + * + * If you require an atomically applied set of writes, use + * {@link protos.google.firestore.v1beta1.Firestore.Commit|Commit} instead. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * 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. + * @param {number[]} request.labels + * Labels associated with this batch write. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.BatchWriteResponse|BatchWriteResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_BatchWrite_async + */ + batchWrite( + request?: protos.google.firestore.v1beta1.IBatchWriteRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1beta1.IBatchWriteResponse, + protos.google.firestore.v1beta1.IBatchWriteRequest | undefined, + {} | undefined, + ] + >; + batchWrite( + request: protos.google.firestore.v1beta1.IBatchWriteRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.IBatchWriteResponse, + protos.google.firestore.v1beta1.IBatchWriteRequest | null | undefined, + {} | null | undefined + >, + ): void; + batchWrite( + request: protos.google.firestore.v1beta1.IBatchWriteRequest, + callback: Callback< + protos.google.firestore.v1beta1.IBatchWriteResponse, + protos.google.firestore.v1beta1.IBatchWriteRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Creates a new document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource. For example: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`. + * @param {string} request.documentId + * The client-assigned document ID to use for this document. + * + * Optional. If not specified, an ID will be assigned by the service. + * @param {google.firestore.v1beta1.Document} request.document + * Required. The document to create. `name` must not be set. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * 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. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_CreateDocument_async + */ + createDocument( + request?: protos.google.firestore.v1beta1.ICreateDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.ICreateDocumentRequest | undefined, + {} | undefined, + ] + >; + createDocument( + request: protos.google.firestore.v1beta1.ICreateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + createDocument( + request: protos.google.firestore.v1beta1.ICreateDocumentRequest, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + >, + ): void; + /** + * Gets multiple documents. + * + * Documents returned by this method are not guaranteed to be returned in the + * same order that they were requested. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.documents + * 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. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * 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. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1beta1.TransactionOptions} request.newTransaction + * 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. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1beta1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_BatchGetDocuments_async + */ + batchGetDocuments( + request?: protos.google.firestore.v1beta1.IBatchGetDocumentsRequest, + options?: CallOptions, + ): gax.CancellableStream; + /** + * Runs a query. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * A structured query. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1beta1.TransactionOptions} request.newTransaction + * 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. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1beta1.RunQueryResponse|RunQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_RunQuery_async + */ + runQuery( + request?: protos.google.firestore.v1beta1.IRunQueryRequest, + options?: CallOptions, + ): gax.CancellableStream; + /** + * Streams batches of document updates and deletes, in order. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1beta1.WriteRequest|WriteRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1beta1.WriteResponse|WriteResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_Write_async + */ + write(options?: CallOptions): gax.CancellableStream; + /** + * Listens to changes. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1beta1.ListenRequest|ListenRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1beta1.ListenResponse|ListenResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_Listen_async + */ + listen(options?: CallOptions): gax.CancellableStream; + /** + * Lists documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` + * or `messages`. + * @param {number} request.pageSize + * The maximum number of documents to return. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous List request, if any. + * @param {string} request.orderBy + * The order to sort results by. For example: `priority desc, name`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * 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. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {boolean} request.showMissing + * If the list should show missing documents. A missing document is a + * document that does not exist but has sub-documents. These documents will + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * + * Requests with `show_missing` may not specify `where` or + * `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1beta1.Document|Document}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocuments( + request?: protos.google.firestore.v1beta1.IListDocumentsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1beta1.IDocument[], + protos.google.firestore.v1beta1.IListDocumentsRequest | null, + protos.google.firestore.v1beta1.IListDocumentsResponse, + ] + >; + listDocuments( + request: protos.google.firestore.v1beta1.IListDocumentsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IListDocumentsRequest, + protos.google.firestore.v1beta1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1beta1.IDocument + >, + ): void; + listDocuments( + request: protos.google.firestore.v1beta1.IListDocumentsRequest, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IListDocumentsRequest, + protos.google.firestore.v1beta1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1beta1.IDocument + >, + ): void; + /** + * Equivalent to `listDocuments`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` + * or `messages`. + * @param {number} request.pageSize + * The maximum number of documents to return. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous List request, if any. + * @param {string} request.orderBy + * The order to sort results by. For example: `priority desc, name`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * 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. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {boolean} request.showMissing + * If the list should show missing documents. A missing document is a + * document that does not exist but has sub-documents. These documents will + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * + * Requests with `show_missing` may not specify `where` or + * `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1beta1.Document|Document} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocumentsStream( + request?: protos.google.firestore.v1beta1.IListDocumentsRequest, + options?: CallOptions, + ): Transform; + /** + * Equivalent to `listDocuments`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` + * or `messages`. + * @param {number} request.pageSize + * The maximum number of documents to return. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous List request, if any. + * @param {string} request.orderBy + * The order to sort results by. For example: `priority desc, name`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * 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. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {boolean} request.showMissing + * If the list should show missing documents. A missing document is a + * document that does not exist but has sub-documents. These documents will + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * + * Requests with `show_missing` may not specify `where` or + * `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1beta1.Document|Document}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_ListDocuments_async + */ + listDocumentsAsync( + request?: protos.google.firestore.v1beta1.IListDocumentsRequest, + options?: CallOptions, + ): AsyncIterable; + /** + * 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. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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. + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * 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. + * @param {number} request.partitionCount + * 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. + * @param {string} request.pageToken + * 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 + * @param {number} request.pageSize + * 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`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1beta1.Cursor|Cursor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQuery( + request?: protos.google.firestore.v1beta1.IPartitionQueryRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.firestore.v1beta1.ICursor[], + protos.google.firestore.v1beta1.IPartitionQueryRequest | null, + protos.google.firestore.v1beta1.IPartitionQueryResponse, + ] + >; + partitionQuery( + request: protos.google.firestore.v1beta1.IPartitionQueryRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IPartitionQueryRequest, + | protos.google.firestore.v1beta1.IPartitionQueryResponse + | null + | undefined, + protos.google.firestore.v1beta1.ICursor + >, + ): void; + partitionQuery( + request: protos.google.firestore.v1beta1.IPartitionQueryRequest, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IPartitionQueryRequest, + | protos.google.firestore.v1beta1.IPartitionQueryResponse + | null + | undefined, + protos.google.firestore.v1beta1.ICursor + >, + ): void; + /** + * Equivalent to `partitionQuery`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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. + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * 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. + * @param {number} request.partitionCount + * 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. + * @param {string} request.pageToken + * 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 + * @param {number} request.pageSize + * 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`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1beta1.Cursor|Cursor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQueryStream( + request?: protos.google.firestore.v1beta1.IPartitionQueryRequest, + options?: CallOptions, + ): Transform; + /** + * Equivalent to `partitionQuery`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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. + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * 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. + * @param {number} request.partitionCount + * 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. + * @param {string} request.pageToken + * 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 + * @param {number} request.pageSize + * 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`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1beta1.Cursor|Cursor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_PartitionQuery_async + */ + partitionQueryAsync( + request?: protos.google.firestore.v1beta1.IPartitionQueryRequest, + options?: CallOptions, + ): AsyncIterable; + /** + * Lists all the collection IDs underneath a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of string. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIds( + request?: protos.google.firestore.v1beta1.IListCollectionIdsRequest, + options?: CallOptions, + ): Promise< + [ + string[], + protos.google.firestore.v1beta1.IListCollectionIdsRequest | null, + protos.google.firestore.v1beta1.IListCollectionIdsResponse, + ] + >; + listCollectionIds( + request: protos.google.firestore.v1beta1.IListCollectionIdsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IListCollectionIdsRequest, + | protos.google.firestore.v1beta1.IListCollectionIdsResponse + | null + | undefined, + string + >, + ): void; + listCollectionIds( + request: protos.google.firestore.v1beta1.IListCollectionIdsRequest, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IListCollectionIdsRequest, + | protos.google.firestore.v1beta1.IListCollectionIdsResponse + | null + | undefined, + string + >, + ): void; + /** + * Equivalent to `listCollectionIds`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing string on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIdsStream( + request?: protos.google.firestore.v1beta1.IListCollectionIdsRequest, + options?: CallOptions, + ): Transform; + /** + * Equivalent to `listCollectionIds`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * 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` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * string. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1beta1_generated_Firestore_ListCollectionIds_async + */ + listCollectionIdsAsync( + request?: protos.google.firestore.v1beta1.IListCollectionIdsRequest, + options?: CallOptions, + ): AsyncIterable; + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise; +} diff --git a/release-please-submodules.json b/release-please-submodules.json index 31841c0d0fd..92bb3eab476 100644 --- a/release-please-submodules.json +++ b/release-please-submodules.json @@ -1,13 +1,7 @@ { - "release-type": "node", - "separate-pull-requests": true, "commit-batch-size": 1, "include-component-in-tag": true, - "tag-separator": "-", "packages": { - "handwritten/logging-winston": { - "component": "logging-winston" - }, "handwritten/bigquery": { "component": "bigquery" }, @@ -17,13 +11,20 @@ "handwritten/datastore": { "component": "datastore" }, + "handwritten/firestore": {}, "handwritten/logging-bunyan": { "component": "logging-bunyan" + }, + "handwritten/logging-winston": { + "component": "logging-winston" } }, "plugins": [ { "type": "sentence-case" } - ] + ], + "release-type": "node", + "separate-pull-requests": true, + "tag-separator": "-" }
include:samples/quickstart.jsinclude:samples/quickstart.jsinclude:samples/generated/v1/firestore_admin.get_index.jsinclude:samples/generated/v1/firestore_admin.delete_index.jsinclude:samples/generated/v1/firestore_admin.get_field.jsinclude:samples/generated/v1/firestore_admin.get_database.jsinclude:samples/generated/v1/firestore_admin.list_databases.jsinclude:samples/generated/v1/firestore_admin.create_user_creds.jsinclude:samples/generated/v1/firestore_admin.get_user_creds.jsinclude:samples/generated/v1/firestore_admin.list_user_creds.jsinclude:samples/generated/v1/firestore_admin.enable_user_creds.jsinclude:samples/generated/v1/firestore_admin.disable_user_creds.jsinclude:samples/generated/v1/firestore_admin.reset_user_password.jsinclude:samples/generated/v1/firestore_admin.delete_user_creds.jsinclude:samples/generated/v1/firestore_admin.get_backup.jsinclude:samples/generated/v1/firestore_admin.list_backups.jsinclude:samples/generated/v1/firestore_admin.delete_backup.jsinclude:samples/generated/v1/firestore_admin.create_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.get_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.list_backup_schedules.jsinclude:samples/generated/v1/firestore_admin.update_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.delete_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.create_index.jsinclude:samples/generated/v1/firestore_admin.create_index.jsinclude:samples/generated/v1/firestore_admin.update_field.jsinclude:samples/generated/v1/firestore_admin.update_field.jsinclude:samples/generated/v1/firestore_admin.export_documents.jsinclude:samples/generated/v1/firestore_admin.export_documents.jsinclude:samples/generated/v1/firestore_admin.import_documents.jsinclude:samples/generated/v1/firestore_admin.import_documents.jsinclude:samples/generated/v1/firestore_admin.bulk_delete_documents.jsinclude:samples/generated/v1/firestore_admin.bulk_delete_documents.jsinclude:samples/generated/v1/firestore_admin.create_database.jsinclude:samples/generated/v1/firestore_admin.create_database.jsinclude:samples/generated/v1/firestore_admin.update_database.jsinclude:samples/generated/v1/firestore_admin.update_database.jsinclude:samples/generated/v1/firestore_admin.delete_database.jsinclude:samples/generated/v1/firestore_admin.delete_database.jsinclude:samples/generated/v1/firestore_admin.restore_database.jsinclude:samples/generated/v1/firestore_admin.restore_database.jsinclude:samples/generated/v1/firestore_admin.clone_database.jsinclude:samples/generated/v1/firestore_admin.clone_database.jsinclude:samples/generated/v1/firestore_admin.list_indexes.jsinclude:samples/generated/v1/firestore_admin.list_fields.jsinclude:samples/generated/v1/firestore.get_document.jsinclude:samples/generated/v1/firestore.update_document.jsinclude:samples/generated/v1/firestore.delete_document.jsinclude:samples/generated/v1/firestore.begin_transaction.jsinclude:samples/generated/v1/firestore.commit.jsinclude:samples/generated/v1/firestore.rollback.jsinclude:samples/generated/v1/firestore.batch_write.jsinclude:samples/generated/v1/firestore.create_document.jsinclude:samples/generated/v1/firestore.batch_get_documents.jsinclude:samples/generated/v1/firestore.run_query.jsinclude:samples/generated/v1/firestore.execute_pipeline.jsinclude:samples/generated/v1/firestore.run_aggregation_query.jsinclude:samples/generated/v1/firestore.write.jsinclude:samples/generated/v1/firestore.listen.jsinclude:samples/generated/v1/firestore.list_documents.jsinclude:samples/generated/v1/firestore.partition_query.jsinclude:samples/generated/v1/firestore.list_collection_ids.jsinclude:samples/generated/v1beta1/firestore.get_document.jsinclude:samples/generated/v1beta1/firestore.update_document.jsinclude:samples/generated/v1beta1/firestore.delete_document.jsinclude:samples/generated/v1beta1/firestore.begin_transaction.jsinclude:samples/generated/v1beta1/firestore.commit.jsinclude:samples/generated/v1beta1/firestore.rollback.jsinclude:samples/generated/v1beta1/firestore.batch_write.jsinclude:samples/generated/v1beta1/firestore.create_document.jsinclude:samples/generated/v1beta1/firestore.batch_get_documents.jsinclude:samples/generated/v1beta1/firestore.run_query.jsinclude:samples/generated/v1beta1/firestore.write.jsinclude:samples/generated/v1beta1/firestore.listen.jsinclude:samples/generated/v1beta1/firestore.list_documents.jsinclude:samples/generated/v1beta1/firestore.partition_query.jsinclude:samples/generated/v1beta1/firestore.list_collection_ids.jsinclude:samples/generated/v1/firestore_admin.get_index.jsinclude:samples/generated/v1/firestore_admin.delete_index.jsinclude:samples/generated/v1/firestore_admin.get_field.jsinclude:samples/generated/v1/firestore_admin.get_database.jsinclude:samples/generated/v1/firestore_admin.list_databases.jsinclude:samples/generated/v1/firestore_admin.get_backup.jsinclude:samples/generated/v1/firestore_admin.list_backups.jsinclude:samples/generated/v1/firestore_admin.delete_backup.jsinclude:samples/generated/v1/firestore_admin.create_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.get_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.list_backup_schedules.jsinclude:samples/generated/v1/firestore_admin.update_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.delete_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.create_index.jsinclude:samples/generated/v1/firestore_admin.create_index.jsinclude:samples/generated/v1/firestore_admin.update_field.jsinclude:samples/generated/v1/firestore_admin.update_field.jsinclude:samples/generated/v1/firestore_admin.export_documents.jsinclude:samples/generated/v1/firestore_admin.export_documents.jsinclude:samples/generated/v1/firestore_admin.import_documents.jsinclude:samples/generated/v1/firestore_admin.import_documents.jsinclude:samples/generated/v1/firestore_admin.bulk_delete_documents.jsinclude:samples/generated/v1/firestore_admin.bulk_delete_documents.jsinclude:samples/generated/v1/firestore_admin.create_database.jsinclude:samples/generated/v1/firestore_admin.create_database.jsinclude:samples/generated/v1/firestore_admin.update_database.jsinclude:samples/generated/v1/firestore_admin.update_database.jsinclude:samples/generated/v1/firestore_admin.delete_database.jsinclude:samples/generated/v1/firestore_admin.delete_database.jsinclude:samples/generated/v1/firestore_admin.restore_database.jsinclude:samples/generated/v1/firestore_admin.restore_database.jsinclude:samples/generated/v1/firestore_admin.list_indexes.jsinclude:samples/generated/v1/firestore_admin.list_fields.jsinclude:samples/generated/v1/firestore.get_document.jsinclude:samples/generated/v1/firestore.update_document.jsinclude:samples/generated/v1/firestore.delete_document.jsinclude:samples/generated/v1/firestore.begin_transaction.jsinclude:samples/generated/v1/firestore.commit.jsinclude:samples/generated/v1/firestore.rollback.jsinclude:samples/generated/v1/firestore.batch_write.jsinclude:samples/generated/v1/firestore.create_document.jsinclude:samples/generated/v1/firestore.batch_get_documents.jsinclude:samples/generated/v1/firestore.run_query.jsinclude:samples/generated/v1/firestore.run_aggregation_query.jsinclude:samples/generated/v1/firestore.write.jsinclude:samples/generated/v1/firestore.listen.jsinclude:samples/generated/v1/firestore.list_documents.jsinclude:samples/generated/v1/firestore.partition_query.jsinclude:samples/generated/v1/firestore.list_collection_ids.jsinclude:samples/generated/v1beta1/firestore.get_document.jsinclude:samples/generated/v1beta1/firestore.update_document.jsinclude:samples/generated/v1beta1/firestore.delete_document.jsinclude:samples/generated/v1beta1/firestore.begin_transaction.jsinclude:samples/generated/v1beta1/firestore.commit.jsinclude:samples/generated/v1beta1/firestore.rollback.jsinclude:samples/generated/v1beta1/firestore.batch_write.jsinclude:samples/generated/v1beta1/firestore.create_document.jsinclude:samples/generated/v1beta1/firestore.batch_get_documents.jsinclude:samples/generated/v1beta1/firestore.run_query.jsinclude:samples/generated/v1beta1/firestore.write.jsinclude:samples/generated/v1beta1/firestore.listen.jsinclude:samples/generated/v1beta1/firestore.list_documents.jsinclude:samples/generated/v1beta1/firestore.partition_query.jsinclude:samples/generated/v1beta1/firestore.list_collection_ids.js